chunhualin1
2026-07-15 2cafb8bad07f8df4eb3dce9b7a02740515d1c1dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
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-SYSTEM:START -->
## 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`
<!-- AI-AGENT-SYSTEM:END -->
""",
    )
    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": "<!-- AI-AGENT-SYSTEM:START -->",
            "end": "<!-- AI-AGENT-SYSTEM: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<!-- AI-AGENT-ROUTING:START -->\nOld routing.\n<!-- AI-AGENT-ROUTING:END -->\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()