from __future__ import annotations import json import importlib.util import os 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 create_staging(repository: Path, run_id: str = "test-run") -> Path: result = run_script( "create-staging-area.py", "--repository", str(repository), "--run-id", run_id ) if result.returncode != 0: raise AssertionError(result.stderr) return Path(json.loads(result.stdout)["staging_root"]) def build_valid_candidate(staging: Path, mode: str = "initialize") -> None: write( staging / "AGENTS.generated.md", """ ## AI Agent Routing and Orchestration - Primary: `.ai/agents/dev-agent.md` - Skill: `.agents/skills/demo-build/SKILL.md` - Workflow: `.ai/workflows/dev-workflow.md` - Policies: `.ai/orchestration/execution-policy.md`, `.ai/orchestration/subagent-contract.md`, `.ai/orchestration/context-policy.md`, `.ai/orchestration/merge-policy.md` """, ) write( staging / ".ai" / "agents" / "dev-agent.md", """# Dev Agent ## role Own implementation. ## input - Stable task ## output - Implementation ## decision - Use `.agents/skills/demo-build/SKILL.md` for the build procedure. ## execution - default_mode: `inline` - allowed_modes: - `inline` - parallelizable: `false` - write_scope: - `src/**` ## return_contract - status - summary - findings_or_changes - artifacts - files_inspected - files_changed - assumptions - risks - verification - unresolved_items - recommended_next_action """, ) write( staging / ".agents" / "skills" / "demo-build" / "SKILL.md", """--- name: demo-build description: Build the demo when implementation changes require repository verification. --- # Demo Build ## Steps 1. Build the demo. ## Output Return the build result. """, ) write( staging / ".ai" / "workflows" / "dev-workflow.md", """# Development Workflow ## goal Implement and verify a change. ## flow Route to implementation and verification. ## execution_graph ```mermaid flowchart TD R[\"route\"] --> I[\"implement\"] ``` ## steps ### route: Route - agent: `dev-agent` - skill: `.agents/skills/demo-build/SKILL.md` - execution: `inline` - depends_on: - `none` - parallel_group: `none` - requires: - `task` - read_scope: - `src/**` - write_scope: - `src/**` - input: - `task` - output: - `implementation` - verification: - `build` - next: - `complete` ## synchronization_gates - Implementation starts after routing. ## routing_rules - Conflicts return to `dev-agent`. ## output_format ```markdown # Workflow Result ``` """, ) for name in ( "execution-policy.md", "subagent-contract.md", "context-policy.md", "merge-policy.md", ): write(staging / ".ai" / "orchestration" / name, f"# {name}\n") generated_files = [ "AGENTS.md", ".ai/bootstrap-manifest.json", ".ai/agents/dev-agent.md", ".ai/workflows/dev-workflow.md", ".ai/orchestration/execution-policy.md", ".ai/orchestration/subagent-contract.md", ".ai/orchestration/context-policy.md", ".ai/orchestration/merge-policy.md", ".agents/skills/demo-build/SKILL.md", ] run_id = json.loads((staging / ".bootstrap-staging.json").read_text(encoding="utf-8"))["run_id"] manifest = { "schema_version": 1, "generator": "ai-agent-system-bootstrap", "suite_version": 3, "run_id": run_id, "blueprint_id": f"{run_id}-blueprint", "generation_mode": mode, "generated_at": "2026-07-14T00:00:00Z", "managed_paths": [".ai", ".agents/skills/demo-build"], "agents_md_managed_block": { "start": "", "end": "", }, "generated_files": generated_files, } write( staging / ".ai" / "bootstrap-manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", ) def validation_report(staging: Path) -> dict: result = run_script("validate-structure.py", "--root", str(staging), "--json") if result.returncode != 0: raise AssertionError(result.stdout + result.stderr) return json.loads(result.stdout) def install_candidate(repository: Path, staging: Path, *allowed_warnings: str) -> subprocess.CompletedProcess[str]: report = validation_report(staging) args = [ "--repository", str(repository), "--staging", str(staging), "--expected-digest", report["candidate_digest"], "--expected-run-id", report["run_id"], "--expected-blueprint-id", report["blueprint_id"], ] for code in allowed_warnings: args.extend(["--allow-warning", code]) return run_script("atomic-replace.py", *args) class ScriptTests(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 test_create_and_cleanup_staging(self) -> None: staging = create_staging(self.repository) duplicate = run_script( "create-staging-area.py", "--repository", str(self.repository), "--run-id", "test-run", ) self.assertNotEqual(duplicate.returncode, 0) cleanup = run_script( "cleanup-staging.py", "--repository", str(self.repository), "--staging", str(staging), ) self.assertEqual(cleanup.returncode, 0, cleanup.stderr) self.assertFalse(staging.exists()) def test_validator_accepts_valid_utf8_candidate(self) -> None: staging = create_staging(self.repository) build_valid_candidate(staging) result = run_script("validate-structure.py", "--root", str(staging), "--json") self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertEqual(json.loads(result.stdout)["status"], "passed") def test_validator_rejects_invalid_skill_and_cycle(self) -> None: staging = create_staging(self.repository) build_valid_candidate(staging) skill = staging / ".agents" / "skills" / "demo-build" / "SKILL.md" skill.write_text("# Missing Frontmatter\n\n## Steps\n\n1. Run.\n\n## Output\n", encoding="utf-8") workflow = staging / ".ai" / "workflows" / "dev-workflow.md" workflow.write_text( workflow.read_text(encoding="utf-8").replace(" - `none`", " - `route`", 1), encoding="utf-8", ) result = run_script("validate-structure.py", "--root", str(staging), "--json") self.assertNotEqual(result.returncode, 0) codes = {item["code"] for item in json.loads(result.stdout)["errors"]} self.assertIn("invalid-frontmatter", codes) self.assertIn("workflow-cycle", codes) def test_transactional_install_preserves_human_content_and_unmanaged_skill(self) -> None: human = (SUITE / "tests" / "fixtures" / "human-owned-agents-md" / "AGENTS.md").read_text(encoding="utf-8") (self.repository / "AGENTS.md").write_text(human, encoding="utf-8", newline="\r\n") write( self.repository / ".agents" / "skills" / "manual-skill" / "SKILL.md", "---\nname: manual-skill\ndescription: Human-owned fixture.\n---\n", ) staging = create_staging(self.repository) build_valid_candidate(staging) result = install_candidate(self.repository, staging) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertFalse(staging.exists()) agents_text = (self.repository / "AGENTS.md").read_text(encoding="utf-8") self.assertIn("人工维护的项目规则", agents_text) self.assertIn("AI-AGENT-SYSTEM:START", agents_text) self.assertTrue((self.repository / ".agents" / "skills" / "manual-skill" / "SKILL.md").exists()) self.assertTrue((self.repository / ".agents" / "skills" / "demo-build" / "SKILL.md").exists()) self.assertTrue((self.repository / ".ai" / "bootstrap-manifest.json").exists()) def test_rebuild_replaces_managed_team_without_duplicate_markers(self) -> None: (self.repository / "AGENTS.md").write_text("# Human Rules\n", encoding="utf-8") first = create_staging(self.repository, "first-run") build_valid_candidate(first) installed = install_candidate(self.repository, first) self.assertEqual(installed.returncode, 0, installed.stdout + installed.stderr) second = create_staging(self.repository, "second-run") build_valid_candidate(second, "rebuild") agent = second / ".ai" / "agents" / "dev-agent.md" agent.write_text( agent.read_text(encoding="utf-8").replace("Own implementation.", "Own implementation version two."), encoding="utf-8", ) rebuilt = install_candidate(self.repository, second) self.assertEqual(rebuilt.returncode, 0, rebuilt.stdout + rebuilt.stderr) agents_text = (self.repository / "AGENTS.md").read_text(encoding="utf-8") self.assertEqual(agents_text.count("AI-AGENT-SYSTEM:START"), 1) installed_agent = self.repository / ".ai" / "agents" / "dev-agent.md" self.assertIn("Own implementation version two.", installed_agent.read_text(encoding="utf-8")) def test_legacy_marker_is_migrated(self) -> None: write( self.repository / "AGENTS.md", "# Human Rules\n\n\nOld routing.\n\n", ) write(self.repository / ".ai" / "agents" / "old-agent.md", "# Old Agent\n") write(self.repository / ".ai" / "workflows" / "old-workflow.md", "# Old Workflow\n") staging = create_staging(self.repository, "legacy-run") build_valid_candidate(staging, "rebuild") result = install_candidate(self.repository, staging) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) text = (self.repository / "AGENTS.md").read_text(encoding="utf-8") self.assertNotIn("AI-AGENT-ROUTING", text) self.assertEqual(text.count("AI-AGENT-SYSTEM:START"), 1) def test_unmanaged_skill_collision_blocks_replacement(self) -> None: original = "---\nname: demo-build\ndescription: Human-owned collision.\n---\n" write(self.repository / ".agents" / "skills" / "demo-build" / "SKILL.md", original) staging = create_staging(self.repository, "collision-run") build_valid_candidate(staging) result = install_candidate(self.repository, staging) self.assertNotEqual(result.returncode, 0) self.assertFalse((self.repository / ".ai").exists()) self.assertEqual( (self.repository / ".agents" / "skills" / "demo-build" / "SKILL.md").read_text(encoding="utf-8"), original, ) def test_invalid_existing_manifest_does_not_claim_ai_ownership(self) -> None: write(self.repository / ".ai" / "bootstrap-manifest.json", "{}\n") write(self.repository / ".ai" / "private.txt", "human owned\n") staging = create_staging(self.repository, "invalid-owner") build_valid_candidate(staging) result = install_candidate(self.repository, staging) self.assertNotEqual(result.returncode, 0) self.assertEqual((self.repository / ".ai" / "private.txt").read_text(encoding="utf-8"), "human owned\n") def test_human_agents_text_is_not_reference_validated(self) -> None: write( self.repository / "AGENTS.md", "# Human rules\n\nHuman note: `.ai/agents/not-generated.md` is historical.\n", ) staging = create_staging(self.repository, "human-reference") build_valid_candidate(staging) result = install_candidate(self.repository, staging) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("not-generated.md", (self.repository / "AGENTS.md").read_text(encoding="utf-8")) def test_validator_rejects_unsafe_paths_and_missing_step_agent(self) -> None: staging = create_staging(self.repository, "unsafe-paths") build_valid_candidate(staging) agent = staging / ".ai" / "agents" / "dev-agent.md" agent.write_text( agent.read_text(encoding="utf-8").replace( ".agents/skills/demo-build/SKILL.md", ".ai/agents/../../../outside.txt", ), encoding="utf-8", ) workflow = staging / ".ai" / "workflows" / "dev-workflow.md" workflow.write_text( workflow.read_text(encoding="utf-8") .replace("- agent: `dev-agent`\n", "") .replace(" - `src/**`", " - `C:/outside/**`", 1) .replace(" - `src/**`", " - `./src/**`", 1), encoding="utf-8", ) result = run_script("validate-structure.py", "--root", str(staging), "--json") self.assertNotEqual(result.returncode, 0) codes = {item["code"] for item in json.loads(result.stdout)["errors"]} self.assertIn("unsafe-reference", codes) self.assertIn("invalid-read-scope", codes) self.assertIn("invalid-write-scope", codes) self.assertIn("missing-workflow-field", codes) def test_validator_rejects_malformed_frontmatter_and_unlisted_skill(self) -> None: staging = create_staging(self.repository, "invalid-render") build_valid_candidate(staging) skill = staging / ".agents" / "skills" / "demo-build" / "SKILL.md" skill.write_text( skill.read_text(encoding="utf-8").replace( "description: Build the demo when implementation changes require repository verification.", 'description: "unterminated', ), encoding="utf-8", ) write( staging / ".agents" / "skills" / "unlisted-skill" / "SKILL.md", "---\nname: unlisted-skill\ndescription: Extra staged Skill.\n---\n\n## Steps\n\n1. Run.\n\n## Output\n\nReturn.\n", ) result = run_script("validate-structure.py", "--root", str(staging), "--json") self.assertNotEqual(result.returncode, 0) codes = {item["code"] for item in json.loads(result.stdout)["errors"]} self.assertIn("invalid-frontmatter", codes) self.assertIn("unlisted-staged-skill", codes) def test_validator_rejects_yaml_typed_frontmatter_and_invalid_timestamp(self) -> None: staging = create_staging(self.repository, "typed-frontmatter") build_valid_candidate(staging) skill = staging / ".agents" / "skills" / "demo-build" / "SKILL.md" skill.write_text( skill.read_text(encoding="utf-8").replace( "description: Build the demo when implementation changes require repository verification.", "description: null", ), encoding="utf-8", ) manifest_path = staging / ".ai" / "bootstrap-manifest.json" manifest = json.loads(manifest_path.read_text(encoding="utf-8")) manifest["generated_at"] = "yesterday" write(manifest_path, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n") result = run_script("validate-structure.py", "--root", str(staging), "--json") self.assertNotEqual(result.returncode, 0) codes = {item["code"] for item in json.loads(result.stdout)["errors"]} self.assertIn("invalid-frontmatter", codes) self.assertIn("invalid-manifest", codes) def test_validator_rejects_missing_workflow_skill_and_directory_reference(self) -> None: staging = create_staging(self.repository, "reference-types") build_valid_candidate(staging) workflow = staging / ".ai" / "workflows" / "dev-workflow.md" workflow.write_text( workflow.read_text(encoding="utf-8").replace( ".agents/skills/demo-build/SKILL.md", ".agents/skills/not-generated/SKILL.md", ), encoding="utf-8", ) context_policy = staging / ".ai" / "orchestration" / "context-policy.md" context_policy.unlink() context_policy.mkdir() result = run_script("validate-structure.py", "--root", str(staging), "--json") self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) report = json.loads(result.stdout) codes = {item["code"] for item in report["errors"]} self.assertIn("missing-workflow-skill", codes) self.assertIn("missing-reference", codes) self.assertIn("invalid-managed-entry", codes) def test_warning_requires_explicit_allowlist(self) -> None: staging = create_staging(self.repository, "warning-gate") build_valid_candidate(staging) policy = staging / ".ai" / "orchestration" / "execution-policy.md" policy.write_bytes(b"\xef\xbb\xbf" + policy.read_bytes()) blocked = install_candidate(self.repository, staging) self.assertNotEqual(blocked.returncode, 0) self.assertTrue(staging.exists()) accepted = install_candidate(self.repository, staging, "utf8-bom") self.assertEqual(accepted.returncode, 0, accepted.stdout + accepted.stderr) def test_digest_and_run_id_are_bound_to_replacement(self) -> None: staging = create_staging(self.repository, "bound-run") build_valid_candidate(staging) report = validation_report(staging) manifest_path = staging / ".ai" / "bootstrap-manifest.json" manifest = json.loads(manifest_path.read_text(encoding="utf-8")) manifest["run_id"] = "different-run" write(manifest_path, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n") result = run_script( "atomic-replace.py", "--repository", str(self.repository), "--staging", str(staging), "--expected-digest", report["candidate_digest"], "--expected-run-id", report["run_id"], "--expected-blueprint-id", report["blueprint_id"], ) self.assertNotEqual(result.returncode, 0) self.assertFalse((self.repository / ".ai").exists()) def test_unicode_repository_path_uses_utf8_stdio(self) -> None: repository = Path(self.temp.name) / "仓库-🧪" repository.mkdir() staging = create_staging(repository, "unicode-run") build_valid_candidate(staging) result = install_candidate(repository, staging) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertEqual(json.loads(result.stdout)["repository_root"], str(repository.resolve())) def test_installed_validation_ignores_human_agents_generated_file(self) -> None: write(self.repository / "AGENTS.generated.md", "# Human-owned draft\n") staging = create_staging(self.repository, "human-draft") build_valid_candidate(staging) result = install_candidate(self.repository, staging) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertEqual( (self.repository / "AGENTS.generated.md").read_text(encoding="utf-8"), "# Human-owned draft\n", ) def test_parent_symlink_cannot_redirect_generated_skills(self) -> None: external = Path(self.temp.name) / "external" external.mkdir() agents_link = self.repository / ".agents" try: os.symlink(external, agents_link, target_is_directory=True) except OSError as symlink_error: if os.name != "nt": self.skipTest(f"directory symlink unavailable: {symlink_error}") junction = subprocess.run( ["cmd.exe", "/d", "/c", "mklink", "/J", str(agents_link), str(external)], capture_output=True, check=False, ) if junction.returncode != 0: self.skipTest(f"directory junction unavailable after symlink failure: {junction.stderr!r}") try: staging = create_staging(self.repository, "link-escape") build_valid_candidate(staging) result = install_candidate(self.repository, staging) self.assertNotEqual(result.returncode, 0) self.assertFalse((external / "skills" / "demo-build").exists()) finally: if agents_link.is_symlink(): agents_link.unlink() elif hasattr(agents_link, "is_junction") and agents_link.is_junction(): agents_link.rmdir() def test_cli_run_and_blueprint_identifiers_are_checked_independently(self) -> None: staging = create_staging(self.repository, "identifier-gate") build_valid_candidate(staging) report = validation_report(staging) common = [ "--repository", str(self.repository), "--staging", str(staging), "--expected-digest", report["candidate_digest"], ] wrong_run = run_script( "atomic-replace.py", *common, "--expected-run-id", "wrong-run", "--expected-blueprint-id", report["blueprint_id"], ) self.assertNotEqual(wrong_run.returncode, 0) wrong_blueprint = run_script( "atomic-replace.py", *common, "--expected-run-id", report["run_id"], "--expected-blueprint-id", "wrong-blueprint", ) self.assertNotEqual(wrong_blueprint.returncode, 0) self.assertFalse((self.repository / ".ai").exists()) def test_rollback_continues_after_one_compensation_fails(self) -> None: module_path = SCRIPTS / "atomic-replace.py" spec = importlib.util.spec_from_file_location("atomic_replace_test", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) staging = Path(self.temp.name) / "rollback-staging" backup_ai = staging / ".rollback" / ".ai" write(backup_ai / "old.txt", "old\n") marker_path = staging / ".bootstrap-staging.json" write(marker_path, "{}\n") target_agents = self.repository / "AGENTS.md" write(target_agents, "new\n") target_ai = self.repository / ".ai" old_skill_backup = staging / ".rollback" / ".agents" / "skills" / "old-skill" / "SKILL.md" write(old_skill_backup, "old skill\n") (self.repository / ".agents" / "skills").mkdir(parents=True) state = module.TransactionState( new_agents_installed=True, old_ai_moved=True, moved_old_skills={"old-skill"}, ) original_remove = module.remove_path def fail_agents_only(path: Path) -> None: if path == target_agents: raise OSError("injected remove failure") original_remove(path) module.remove_path = fail_agents_only try: errors = module.rollback( self.repository, staging, marker_path, {}, state, target_ai, target_agents, self.repository / ".agents" / "skills", True, True, RuntimeError("forward failure"), ) finally: module.remove_path = original_remove self.assertTrue(any("remove new AGENTS.md" in error for error in errors)) self.assertEqual((target_ai / "old.txt").read_text(encoding="utf-8"), "old\n") self.assertEqual( (self.repository / ".agents" / "skills" / "old-skill" / "SKILL.md").read_text(encoding="utf-8"), "old skill\n", ) self.assertFalse((staging / ".rollback" / ".agents").exists()) if __name__ == "__main__": unittest.main()