from __future__ import annotations import json import subprocess import sys import tempfile import unittest from pathlib import Path SUITE = Path(__file__).resolve().parents[1] SCRIPTS = SUITE / "shared" / "scripts" def run_script(name: str, *args: str) -> subprocess.CompletedProcess[str]: return subprocess.run( [sys.executable, str(SCRIPTS / name), *args], capture_output=True, text=True, encoding="utf-8", check=False, ) def write(path: Path, content: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content, encoding="utf-8", newline="\n") def agent_text(name: str, scope: str = "src/**", readonly: bool = False) -> str: mode = "subagent-readonly" if readonly else "inline" write_scope = "none" if readonly else scope return f"""# {name.replace('-', ' ').title()} ## role Own the distinct {name} decisions, risks, artifacts, and verification. ## input - Stable task and project evidence ## output - Owned result with evidence ## decision - Route cross-domain changes to the primary Agent. ## execution - default_mode: `{mode}` - allowed_modes: - `{mode}` - parallelizable: `{'true' if readonly else 'false'}` - write_scope: - `{write_scope}` - requires: - `stable task` - conflicts_with: - `none` - failure_policy: `return-partial` ## return_contract - status - summary - findings_or_changes - artifacts - files_inspected - files_changed - assumptions - risks - verification - unresolved_items - recommended_next_action """ def skill_text(name: str) -> str: return f"""--- name: {name} description: Execute the {name} repository procedure when its owned lifecycle is requested. --- # {name.replace('-', ' ').title()} ## Steps 1. Read the stable inputs. 2. Execute the repository procedure. 3. Validate the result. ## Output Return the result, evidence, verification, and remaining risks. """ def workflow_text(agent: str, skill: str, execution: str, parallel: bool) -> str: group = "implementation" if parallel else "none" return f"""# Delivery Workflow ## goal Deliver and verify a project change. ## flow Route to stable implementation, integration, and verification. ## execution_graph ```mermaid flowchart TD A["route"] --> B["deliver"] ``` ## steps ### deliver: Deliver - agent: `{agent}` - skill: `.ai/skills/{skill}/SKILL.md` - execution: `{execution}` - depends_on: - `none` - parallel_group: `{group}` - requires: - `stable task` - read_scope: - `src/**` - write_scope: - `{'none' if execution == 'subagent-readonly' else 'src/**'}` - input: - `task` - output: - `verified result` - verification: - `project check` - next: - `primary integration` ## synchronization_gates - Start after inputs are stable. - Integrate after required results return. - Complete after verification. ## routing_rules - Route conflicts to `{agent}`. ## output_format ```markdown # Workflow Result ``` """ def build_candidate(repository: Path, *, complex_project: bool, run_id: str, mode: str = "initialize") -> None: agents = ( ["dev-agent", "qa-agent"] if not complex_project else [ "product-agent", "architect-agent", "frontend-agent", "backend-agent", "data-agent", "security-agent", "qa-agent", "devops-agent", "docs-agent", "review-agent", ] ) skill = "demo-delivery" execution = "inline" if not complex_project else "subagent-worktree" policy_names = [] if not complex_project else [ "execution-policy.md", "subagent-contract.md", "context-policy.md", "merge-policy.md", ] links = [f"- Agent: `.ai/agents/{name}.md`" for name in agents] links.extend([ f"- Skill: `.ai/skills/{skill}/SKILL.md`", "- Workflow: `.ai/workflows/delivery-workflow.md`", f"- Orchestration level: {'parallel' if complex_project else 'inline'}", "- Explicitly named Agents and Skills take precedence over automatic matching.", "- Global Skills require explicit user authorization.", "- Role selection and SubAgent execution are separate decisions.", "- Use one writer per scope, immutable handoffs, structured returns, primary integration, and sequential fallback.", ]) links.extend(f"- Policy: `.ai/orchestration/{name}`" for name in policy_names) managed_block = ( "\n## AI Agent Routing and Orchestration\n\n" + "\n".join(links) + "\n\n" ) agents_path = repository / "AGENTS.md" human_text = agents_path.read_text(encoding="utf-8").rstrip() if agents_path.is_file() else "" write(agents_path, f"{human_text}\n\n{managed_block}" if human_text else managed_block) for name in agents: write(repository / ".ai" / "agents" / f"{name}.md", agent_text(name, readonly=name in {"qa-agent", "security-agent", "review-agent"})) write(repository / ".ai" / "skills" / skill / "SKILL.md", skill_text(skill)) write( repository / ".ai" / "workflows" / "delivery-workflow.md", workflow_text("dev-agent" if not complex_project else "backend-agent", skill, execution, complex_project), ) for name in policy_names: write(repository / ".ai" / "orchestration" / name, f"# {name}\n\nProject-specific orchestration rules.\n") generated_files = ["AGENTS.md"] generated_files.extend(path.relative_to(repository).as_posix() for path in (repository / ".ai").rglob("*") if path.is_file()) generated_files.append(".ai/bootstrap-manifest.json") manifest = { "schema_version": 1, "generator": "ai-agent-system-bootstrap", "suite_version": 4, "run_id": run_id, "blueprint_id": f"{run_id}-blueprint", "generation_mode": mode, "generated_at": "2026-07-16T00:00:00Z", "managed_paths": [".ai"], "agents_md_managed_block": { "start": "", "end": "", }, "generated_files": sorted(set(generated_files)), } write(repository / ".ai" / "bootstrap-manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n") def validate(repository: Path) -> subprocess.CompletedProcess[str]: return run_script("validate-structure.py", "--root", str(repository), "--json") class SuiteScenarioTests(unittest.TestCase): def setUp(self) -> None: self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.repository = Path(self.temp.name) / "repo" self.repository.mkdir() def candidate(self, complex_project: bool, run_id: str = "scenario") -> Path: build_candidate(self.repository, complex_project=complex_project, run_id=run_id) return self.repository def test_small_project_uses_two_agents_and_inline_orchestration(self) -> None: result = validate(self.candidate(False, "small")) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) report = json.loads(result.stdout) self.assertEqual(report["counts"]["agents"], 2) self.assertEqual(report["counts"]["orchestration_policies"], 0) def test_complex_project_supports_more_than_five_distinct_agents(self) -> None: result = validate(self.candidate(True, "complex")) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) report = json.loads(result.stdout) self.assertEqual(report["counts"]["agents"], 10) self.assertEqual(report["counts"]["orchestration_policies"], 4) def test_project_skills_are_under_ai_skills(self) -> None: repository = self.candidate(False, "skill-path") self.assertTrue((repository / ".ai" / "skills" / "demo-delivery" / "SKILL.md").is_file()) self.assertFalse((repository / ".agent").exists()) self.assertFalse((repository / ".agents").exists()) def test_forbidden_agent_directory_is_rejected_in_repository(self) -> None: repository = self.candidate(False, "forbidden") write(repository / ".agents" / "unexpected.md", "unexpected\n") result = validate(repository) self.assertNotEqual(result.returncode, 0) self.assertIn("forbidden-agent-directory", result.stdout) def test_parallel_workflow_requires_full_orchestration(self) -> None: repository = self.candidate(True, "missing-policy") (repository / ".ai" / "orchestration" / "merge-policy.md").unlink() result = validate(repository) self.assertNotEqual(result.returncode, 0) self.assertIn("missing-orchestration", result.stdout) def test_inline_workflow_does_not_require_orchestration_directory(self) -> None: repository = self.candidate(False, "inline") self.assertFalse((repository / ".ai" / "orchestration").exists()) self.assertEqual(validate(repository).returncode, 0) def test_direct_generation_preserves_human_agents_text(self) -> None: write(self.repository / "AGENTS.md", "# Human rules\n\nKeep this.\n") repository = self.candidate(False, "direct") result = validate(repository) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("Keep this.", (self.repository / "AGENTS.md").read_text(encoding="utf-8")) self.assertTrue((self.repository / ".ai" / "skills" / "demo-delivery" / "SKILL.md").is_file()) self.assertFalse((self.repository / ".agent").exists()) self.assertFalse((self.repository / ".agents").exists()) def test_contracts_encode_complete_team_and_adaptive_orchestration(self) -> None: design = (SUITE / "shared" / "policies" / "agent-team-design.md").read_text(encoding="utf-8") scaling = (SUITE / "shared" / "policies" / "orchestration-scaling.md").read_text(encoding="utf-8") self.assertIn("frontend", design) self.assertIn("security", design) self.assertIn("documentation", design) self.assertIn("No numeric target or cap", design) self.assertIn("Inline level", scaling) self.assertIn("Parallel level", scaling) def test_suite_contains_no_generated_agents_skill_path(self) -> None: offenders = [] forbidden = ".agents" + "/skills" for path in [*SUITE.rglob("*.md"), *SUITE.rglob("*.py"), *SUITE.rglob("*.json"), *SUITE.rglob("*.yaml")]: if path.is_file() and forbidden in path.read_text(encoding="utf-8"): offenders.append(path.relative_to(SUITE).as_posix()) self.assertEqual(offenders, []) if __name__ == "__main__": unittest.main()