@walvka-code/proj-doc-builder 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +271 -2
  3. package/README.zh-CN.md +240 -0
  4. package/cordis.patch.yml +8 -0
  5. package/icon.svg +11 -0
  6. package/index.js +164 -0
  7. package/locale/en.json +6 -0
  8. package/locale/zh.json +6 -0
  9. package/package.json +55 -4
  10. package/skills/proj-doc-builder/SKILL.md +350 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +96 -0
  12. package/skills/proj-doc-builder/references/checklist.md +80 -0
  13. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  14. package/skills/proj-doc-builder/references/linking.md +83 -0
  15. package/skills/proj-doc-builder/references/migration.md +32 -0
  16. package/skills/proj-doc-builder/references/phase4.md +200 -0
  17. package/skills/proj-doc-builder/references/templates.md +172 -0
  18. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  19. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  20. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  21. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  22. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  23. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  24. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  25. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  26. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  27. package/skills/proj-doc-builder/tests/conftest.py +11 -0
  28. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  29. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  30. package/skills/proj-doc-builder/tests/test_load_docs.py +248 -0
  31. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  32. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  33. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +781 -0
  34. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  35. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  36. package/skills/proj-doc-builder/tests/test_validate_doc.py +555 -0
  37. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  38. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  39. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  40. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  41. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  42. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  43. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  44. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  45. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
  46. package/skills/proj-doc-builder/tools/claude_doc_index.py +298 -0
  47. package/skills/proj-doc-builder/tools/compute_link.py +233 -0
  48. package/skills/proj-doc-builder/tools/link_check.py +152 -0
  49. package/skills/proj-doc-builder/tools/load_docs.py +380 -0
  50. package/skills/proj-doc-builder/tools/normalize_markers.py +205 -0
  51. package/skills/proj-doc-builder/tools/phase4/__init__.py +57 -0
  52. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +18 -0
  53. package/skills/proj-doc-builder/tools/phase4/engine.py +20 -0
  54. package/skills/proj-doc-builder/tools/phase4/journal.py +22 -0
  55. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +20 -0
  56. package/skills/proj-doc-builder/tools/phase4_exit.py +8459 -0
  57. package/skills/proj-doc-builder/tools/project_docs_contract.py +2318 -0
  58. package/skills/proj-doc-builder/tools/scan_dirs.py +2405 -0
  59. package/skills/proj-doc-builder/tools/sync_project_docs.py +3639 -0
  60. package/skills/proj-doc-builder/tools/validate_doc.py +1299 -0
@@ -0,0 +1,2169 @@
1
+ # -*- coding: utf-8 -*-
2
+ """同步协调器的临时项目事务与幂等性测试。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ from contextlib import contextmanager
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+
14
+ import pytest
15
+
16
+ import claude_doc_index
17
+ import phase4_exit
18
+ import project_docs_contract as contract
19
+ import scan_dirs
20
+ import sync_project_docs as coordinator
21
+
22
+ SYNCED = "2026-07-30T00:00:00+00:00"
23
+ # 可选的外部 reader 技能(默认位置 .dsh/skills/load-project);未安装时对应用例跳过。
24
+ LOAD_TOOL = (
25
+ Path(__file__).resolve().parents[2] / "load-project" / "tools" / "load_project.py"
26
+ )
27
+ SYNC_TOOL = Path(__file__).resolve().parents[1] / "tools" / "sync_project_docs.py"
28
+
29
+
30
+ def _write(path: Path, content: str) -> None:
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ path.write_text(content, encoding="utf-8")
33
+
34
+
35
+ def _claude() -> str:
36
+ lines = ["# CLAUDE.md", "", "manual-before"]
37
+ for section in claude_doc_index.REQUIRED_SECTIONS:
38
+ lines.extend(
39
+ [
40
+ claude_doc_index.section_start(section),
41
+ f"old-{section}",
42
+ claude_doc_index.section_end(section),
43
+ f"manual-after-{section}",
44
+ ]
45
+ )
46
+ return "\n".join(lines) + "\n"
47
+
48
+
49
+ def _placeholder_document(
50
+ *,
51
+ broken_link: bool = False,
52
+ corrupt_marker: bool = False,
53
+ ) -> str:
54
+ optional_link = "\n[缺失文档](missing.md)\n" if broken_link else ""
55
+ marker_tail = " v3.1 -->" if corrupt_marker else ""
56
+ return f"""# module — 占位模块
57
+
58
+ <!-- DOC-PATH: project_docs/module.md -->
59
+ <!-- AUTO-GENERATED v3.0: folder-doc START -->
60
+ <!-- Last synced: {SYNCED} by proj-doc-builder v4.0 -->{marker_tail}
61
+
62
+ **导航**: **module**
63
+
64
+ ## 概述
65
+
66
+ 本目录当前为占位。待后续实现。
67
+
68
+ ## 文件清单
69
+
70
+ | 文件 | 用途 |
71
+ |------|------|
72
+ | `__init__.py` | 包初始化文件 |
73
+
74
+ ## 系统角色
75
+
76
+ 本目录预留模块入口,后续实现将由上层组件调用。
77
+ {optional_link}
78
+ ## 状态
79
+
80
+ ⬜ 占位 — 目录已建立,待实现。
81
+
82
+ <!-- AUTO-GENERATED v3.0: folder-doc END -->
83
+ """
84
+
85
+
86
+ def _project(
87
+ tmp_path: Path,
88
+ *,
89
+ broken_link: bool = False,
90
+ corrupt_marker: bool = False,
91
+ ) -> tuple[Path, Path]:
92
+ root = tmp_path / "project"
93
+ docs_root = root / "project_docs"
94
+ source = root / "module"
95
+ source.mkdir(parents=True)
96
+ _write(source / "__init__.py", "# -*- coding: utf-8 -*-\n")
97
+ _write(root / "CLAUDE.md", _claude())
98
+ _write(
99
+ docs_root / "module.md",
100
+ _placeholder_document(
101
+ broken_link=broken_link,
102
+ corrupt_marker=corrupt_marker,
103
+ ),
104
+ )
105
+ return root, docs_root
106
+
107
+
108
+ def _file_bytes(root: Path) -> dict[str, bytes]:
109
+ return {
110
+ path.relative_to(root).as_posix(): path.read_bytes()
111
+ for path in root.rglob("*")
112
+ if path.is_file()
113
+ }
114
+
115
+
116
+ def _tree_paths(root: Path) -> set[str]:
117
+ return {path.relative_to(root).as_posix() for path in root.rglob("*")}
118
+
119
+
120
+ def test_indirect_project_root_is_rejected(tmp_path: Path) -> None:
121
+ root, _ = _project(tmp_path)
122
+ root_link = tmp_path / "project-link"
123
+ try:
124
+ root_link.symlink_to(root, target_is_directory=True)
125
+ except (NotImplementedError, OSError) as exc:
126
+ pytest.skip(f"directory symlink creation is unavailable: {exc}")
127
+
128
+ with pytest.raises(coordinator.SyncInputError, match="direct real directory"):
129
+ coordinator.synchronize_project(root_link, run_timestamp=SYNCED)
130
+
131
+
132
+ def test_dry_run_passes_all_gates_without_writing(tmp_path: Path) -> None:
133
+ root, _ = _project(tmp_path)
134
+ before = _file_bytes(root)
135
+
136
+ report, exit_code = coordinator.synchronize_project(
137
+ root,
138
+ run_timestamp=SYNCED,
139
+ )
140
+
141
+ assert exit_code == coordinator.EXIT_OK
142
+ assert report["ok"] is True
143
+ assert report["mode"] == "dry-run"
144
+ assert report["manifest"]["schema_version"] == 2
145
+ assert report["scan"]["changes"]["new"] == ["", "module"]
146
+ assert [item["path"] for item in report["scan"]["worklist"]["directories"]] == [
147
+ "module",
148
+ "",
149
+ ]
150
+ scaffold = report["scan"]["worklist"]["scaffold"]
151
+ assert len(scaffold) == 2
152
+ assert scaffold[0]["path"] == "module"
153
+ assert scaffold[0]["change"] == "new"
154
+ assert scaffold[0]["doc_path"] == "project_docs/module.md"
155
+ assert scaffold[0]["recommended_profile"] == "placeholder"
156
+ assert "precomputed_links" in scaffold[0]
157
+ assert scaffold[1]["path"] == ""
158
+ assert scaffold[1]["change"] == "new"
159
+ assert scaffold[1]["doc_path"] == "project_docs/index.md"
160
+ assert report["links"]["broken_count"] == 0
161
+ assert report["publish"]["requested"] is False
162
+ assert _file_bytes(root) == before
163
+
164
+
165
+ def test_dry_run_stages_outside_project_and_removes_stage_tree(
166
+ tmp_path: Path,
167
+ monkeypatch: pytest.MonkeyPatch,
168
+ ) -> None:
169
+ root, _ = _project(tmp_path)
170
+ original_prepare = coordinator._prepare
171
+ observed_stage_roots: list[Path] = []
172
+
173
+ def record_stage(paths, stage_docs, **kwargs):
174
+ stage_root = stage_docs.parent.resolve(strict=True)
175
+ observed_stage_roots.append(stage_root)
176
+ assert not stage_root.is_relative_to(root.resolve())
177
+ return original_prepare(paths, stage_docs, **kwargs)
178
+
179
+ monkeypatch.setattr(coordinator, "_prepare", record_stage)
180
+
181
+ report, exit_code = coordinator.synchronize_project(
182
+ root,
183
+ run_timestamp=SYNCED,
184
+ )
185
+
186
+ assert exit_code == coordinator.EXIT_OK
187
+ assert report["ok"] is True
188
+ assert len(observed_stage_roots) == 1
189
+ assert not observed_stage_roots[0].exists()
190
+
191
+
192
+ def test_stage_cleanup_failure_is_not_silently_ignored(
193
+ tmp_path: Path,
194
+ monkeypatch: pytest.MonkeyPatch,
195
+ ) -> None:
196
+ root, _ = _project(tmp_path)
197
+ original_rmtree = shutil.rmtree
198
+ staged: list[Path] = []
199
+
200
+ def fail_cleanup(path: str | os.PathLike[str]) -> None:
201
+ staged.append(Path(path))
202
+ raise OSError("injected staging cleanup failure")
203
+
204
+ monkeypatch.setattr(coordinator.shutil, "rmtree", fail_cleanup)
205
+ try:
206
+ with pytest.raises(
207
+ coordinator.SyncInputError,
208
+ match="cannot clean coordinator staging directory",
209
+ ):
210
+ coordinator.synchronize_project(root, run_timestamp=SYNCED)
211
+ finally:
212
+ monkeypatch.setattr(coordinator.shutil, "rmtree", original_rmtree)
213
+ for path in staged:
214
+ if path.exists():
215
+ original_rmtree(path)
216
+
217
+ assert len(staged) == 1
218
+
219
+
220
+ def test_cli_dry_run_without_bytecode_env_writes_no_project_paths_or_cache(
221
+ tmp_path: Path,
222
+ ) -> None:
223
+ root, _ = _project(tmp_path / "target")
224
+ copied_tools = tmp_path / "standalone-skill" / "tools"
225
+ shutil.copytree(
226
+ SYNC_TOOL.parent,
227
+ copied_tools,
228
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo"),
229
+ )
230
+ copied_cli = copied_tools / SYNC_TOOL.name
231
+ before_paths = _tree_paths(root)
232
+ environment = dict(os.environ)
233
+ environment.pop("PYTHONDONTWRITEBYTECODE", None)
234
+ environment.pop("PYTHONPYCACHEPREFIX", None)
235
+ environment["PYTHONIOENCODING"] = "utf-8"
236
+
237
+ completed = subprocess.run(
238
+ [
239
+ sys.executable,
240
+ str(copied_cli),
241
+ str(root),
242
+ "--dry-run",
243
+ "--json",
244
+ ],
245
+ cwd=root,
246
+ env=environment,
247
+ capture_output=True,
248
+ text=True,
249
+ encoding="utf-8",
250
+ check=False,
251
+ )
252
+
253
+ assert completed.returncode == coordinator.EXIT_OK, completed.stdout
254
+ assert completed.stderr == ""
255
+ assert json.loads(completed.stdout)["ok"] is True
256
+ assert _tree_paths(root) == before_paths
257
+ assert not list(copied_tools.rglob("__pycache__"))
258
+ assert not list(copied_tools.rglob("*.py[co]"))
259
+
260
+
261
+ def test_apply_publishes_v2_state_and_second_run_is_noop(tmp_path: Path) -> None:
262
+ root, docs_root = _project(tmp_path)
263
+
264
+ first, first_code = coordinator.synchronize_project(
265
+ root,
266
+ apply=True,
267
+ run_timestamp=SYNCED,
268
+ )
269
+
270
+ assert first_code == coordinator.EXIT_OK
271
+ assert first["publish"]["completed"] is True
272
+ assert first["publish"]["manifest_commit_point"] is True
273
+ assert first["publish"]["scan_state_committed"] is True
274
+ manifest = contract.load_manifest(docs_root, verify_files=True)
275
+ assert manifest["schema_version"] == 2
276
+ assert manifest["total"] == 1
277
+ assert (docs_root / coordinator.SCAN_STATE_FILENAME).is_file()
278
+ assert "old-doc-tree-instruction" not in (root / "CLAUDE.md").read_text(
279
+ encoding="utf-8"
280
+ )
281
+
282
+ committed = _file_bytes(root)
283
+ second, second_code = coordinator.synchronize_project(
284
+ root,
285
+ run_timestamp="2026-07-30T01:00:00+00:00",
286
+ )
287
+
288
+ assert second_code == coordinator.EXIT_OK
289
+ assert second["planned_writes"] == []
290
+ assert second["manifest"]["changed"] is False
291
+ assert second["scan"]["commit_needed"] is False
292
+ assert _file_bytes(root) == committed
293
+
294
+
295
+ @pytest.mark.skipif(
296
+ not LOAD_TOOL.is_file(),
297
+ reason="optional 'load-project' skill is not installed; reader integration skipped",
298
+ )
299
+ def test_applied_project_loads_overview_and_target_without_writes(
300
+ tmp_path: Path,
301
+ ) -> None:
302
+ root, _ = _project(tmp_path)
303
+ report, exit_code = coordinator.synchronize_project(
304
+ root,
305
+ apply=True,
306
+ run_timestamp=SYNCED,
307
+ )
308
+ assert exit_code == coordinator.EXIT_OK
309
+ assert report["publish"]["completed"] is True
310
+ before_load = _file_bytes(root)
311
+ environment = dict(os.environ)
312
+ environment["PYTHONIOENCODING"] = "utf-8"
313
+ environment["PYTHONDONTWRITEBYTECODE"] = "1"
314
+
315
+ for mode_args, expected_mode in (
316
+ (["--mode", "overview"], "overview"),
317
+ (["--target", "module"], "target"),
318
+ ):
319
+ completed = subprocess.run(
320
+ [
321
+ sys.executable,
322
+ str(LOAD_TOOL),
323
+ "--project-root",
324
+ str(root),
325
+ *mode_args,
326
+ ],
327
+ check=False,
328
+ capture_output=True,
329
+ env=environment,
330
+ )
331
+ assert completed.returncode == 0, completed.stdout.decode("utf-8")
332
+ assert completed.stderr == b""
333
+ payload = json.loads(completed.stdout.decode("utf-8"))
334
+ assert payload["ok"] is True
335
+ assert payload["mode"] == expected_mode
336
+ assert payload["manifest"]["compatibility"] == "v2_verified"
337
+ assert payload["selected"]["count"] == 1
338
+ assert payload["omitted"]["count"] == 0
339
+
340
+ assert _file_bytes(root) == before_load
341
+
342
+
343
+ def test_broken_link_blocks_apply_without_any_publish(tmp_path: Path) -> None:
344
+ root, docs_root = _project(tmp_path, broken_link=True)
345
+ before = _file_bytes(root)
346
+
347
+ report, exit_code = coordinator.synchronize_project(
348
+ root,
349
+ apply=True,
350
+ run_timestamp=SYNCED,
351
+ )
352
+
353
+ assert exit_code == coordinator.EXIT_GATE_FAILED
354
+ assert report["ok"] is False
355
+ assert report["links"]["broken_count"] == 1
356
+ assert any(error["code"] == "broken-document-links" for error in report["errors"])
357
+ assert report["publish"]["completed"] is False
358
+ assert not (docs_root / contract.MANIFEST_FILENAME).exists()
359
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
360
+ assert _file_bytes(root) == before
361
+
362
+
363
+ def test_apply_uses_shared_project_root_lock(
364
+ tmp_path: Path,
365
+ monkeypatch: pytest.MonkeyPatch,
366
+ ) -> None:
367
+ root, _ = _project(tmp_path)
368
+ events: list[tuple[str, Path, float | None]] = []
369
+
370
+ @contextmanager
371
+ def recording_lock(
372
+ project_root: Path,
373
+ *,
374
+ timeout: float | None = 10.0,
375
+ poll_interval: float = 0.05,
376
+ ):
377
+ assert poll_interval == 0.05
378
+ events.append(("enter", Path(project_root), timeout))
379
+ try:
380
+ yield object()
381
+ finally:
382
+ events.append(("exit", Path(project_root), timeout))
383
+
384
+ monkeypatch.setattr(contract, "project_sync_lock", recording_lock)
385
+
386
+ report, exit_code = coordinator.synchronize_project(
387
+ root,
388
+ apply=True,
389
+ lock_timeout=2.0,
390
+ run_timestamp=SYNCED,
391
+ )
392
+
393
+ assert exit_code == coordinator.EXIT_OK
394
+ assert report["publish"]["completed"] is True
395
+ assert events == [
396
+ ("enter", root.resolve(), 2.0),
397
+ ("exit", root.resolve(), 2.0),
398
+ ]
399
+
400
+
401
+ def test_unknown_manifest_schema_is_not_silently_rebuilt(tmp_path: Path) -> None:
402
+ root, docs_root = _project(tmp_path)
403
+ (docs_root / contract.MANIFEST_FILENAME).write_text(
404
+ '{"schema_version": 99, "files": []}\n',
405
+ encoding="utf-8",
406
+ )
407
+ before = _file_bytes(root)
408
+
409
+ with pytest.raises(coordinator.SyncInputError, match="unknown schema"):
410
+ coordinator.synchronize_project(
411
+ root,
412
+ apply=True,
413
+ run_timestamp=SYNCED,
414
+ )
415
+
416
+ assert _file_bytes(root) == before
417
+
418
+
419
+ def test_unhandled_phase4_candidate_blocks_scan_baseline_advance(
420
+ tmp_path: Path,
421
+ ) -> None:
422
+ root, docs_root = _project(tmp_path)
423
+ (root / "module" / "__init__.py").unlink()
424
+ (root / "module").rmdir()
425
+
426
+ report, exit_code = coordinator.synchronize_project(
427
+ root,
428
+ apply=True,
429
+ run_timestamp=SYNCED,
430
+ )
431
+
432
+ assert exit_code == coordinator.EXIT_OK
433
+ assert report["phase4"]["counts"]["candidates"] == 1
434
+ assert any(
435
+ isinstance(warning, dict) and warning["code"] == "phase4-candidates-pending"
436
+ for warning in report["warnings"]
437
+ )
438
+ assert any(
439
+ isinstance(warning, dict) and warning["code"] == "scan-baseline-frozen"
440
+ for warning in report["warnings"]
441
+ )
442
+ # Documents and the manifest publish normally; only the scan baseline stays
443
+ # frozen until the candidate is quarantined.
444
+ assert (docs_root / contract.MANIFEST_FILENAME).exists()
445
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
446
+
447
+
448
+ def test_manifest_publish_failure_rolls_back_markers_and_claude(
449
+ tmp_path: Path,
450
+ monkeypatch: pytest.MonkeyPatch,
451
+ ) -> None:
452
+ root, docs_root = _project(tmp_path, corrupt_marker=True)
453
+ before = _file_bytes(root)
454
+ original_set_state = coordinator._set_publish_path_state
455
+
456
+ def fail_manifest(path: Path, before, after, **kwargs) -> None:
457
+ if (
458
+ path == docs_root / contract.MANIFEST_FILENAME
459
+ and kwargs["label"] == "manifest"
460
+ and kwargs["desired_after"] is True
461
+ and kwargs["allow_both"] is False
462
+ ):
463
+ raise OSError("injected manifest failure")
464
+ original_set_state(path, before, after, **kwargs)
465
+
466
+ monkeypatch.setattr(coordinator, "_set_publish_path_state", fail_manifest)
467
+
468
+ with pytest.raises(coordinator.SyncPublishError) as caught:
469
+ coordinator.synchronize_project(
470
+ root,
471
+ apply=True,
472
+ run_timestamp=SYNCED,
473
+ )
474
+
475
+ publish = caught.value.result["publish"]
476
+ assert publish["manifest_commit_point"] is False
477
+ assert publish["rolled_back"] is True
478
+ assert publish["rollback_failures"] == []
479
+ assert not (docs_root / contract.MANIFEST_FILENAME).exists()
480
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
481
+ assert _file_bytes(root) == before
482
+
483
+
484
+ def test_scan_state_failure_reports_partial_commit_without_reverting_manifest(
485
+ tmp_path: Path,
486
+ monkeypatch: pytest.MonkeyPatch,
487
+ ) -> None:
488
+ root, docs_root = _project(tmp_path)
489
+ original_set_state = coordinator._set_publish_path_state
490
+
491
+ def fail_scan_state(path: Path, before, after, **kwargs) -> None:
492
+ if (
493
+ path == docs_root / coordinator.SCAN_STATE_FILENAME
494
+ and kwargs["label"] == "scan state"
495
+ and kwargs["desired_after"] is True
496
+ and kwargs["allow_both"] is False
497
+ ):
498
+ raise OSError("injected scan-state failure")
499
+ original_set_state(path, before, after, **kwargs)
500
+
501
+ monkeypatch.setattr(coordinator, "_set_publish_path_state", fail_scan_state)
502
+
503
+ with pytest.raises(coordinator.SyncPublishError) as caught:
504
+ coordinator.synchronize_project(
505
+ root,
506
+ apply=True,
507
+ run_timestamp=SYNCED,
508
+ )
509
+
510
+ publish = caught.value.result["publish"]
511
+ assert publish["disposition"] == "partially-installed"
512
+ assert publish["manifest_disposition"] == "installed"
513
+ assert publish["scan_state_disposition"] == "not-installed"
514
+ assert publish["manifest_commit_point"] is True
515
+ assert publish["scan_state_committed"] is False
516
+ assert publish["partial_commit"] is True
517
+ assert "manifest=installed" in str(caught.value)
518
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
519
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
520
+
521
+
522
+ def test_scan_state_only_failure_is_not_reported_as_partial_manifest_commit(
523
+ tmp_path: Path,
524
+ monkeypatch: pytest.MonkeyPatch,
525
+ ) -> None:
526
+ root, docs_root = _project(tmp_path)
527
+ initial, initial_code = coordinator.synchronize_project(
528
+ root,
529
+ apply=True,
530
+ run_timestamp=SYNCED,
531
+ )
532
+ assert initial_code == coordinator.EXIT_OK
533
+ assert initial["publish"]["completed"] is True
534
+ manifest_before = (docs_root / contract.MANIFEST_FILENAME).read_bytes()
535
+ scan_before = (docs_root / coordinator.SCAN_STATE_FILENAME).read_bytes()
536
+ _write(
537
+ root / "module" / "__init__.py",
538
+ "# -*- coding: utf-8 -*-\nVALUE = 1\n",
539
+ )
540
+ original_set_state = coordinator._set_publish_path_state
541
+
542
+ def fail_scan_state(path: Path, before, after, **kwargs) -> None:
543
+ if (
544
+ path == docs_root / coordinator.SCAN_STATE_FILENAME
545
+ and kwargs["label"] == "scan state"
546
+ and kwargs["desired_after"] is True
547
+ and kwargs["allow_both"] is False
548
+ ):
549
+ raise OSError("injected scan-state-only failure")
550
+ original_set_state(path, before, after, **kwargs)
551
+
552
+ monkeypatch.setattr(coordinator, "_set_publish_path_state", fail_scan_state)
553
+
554
+ with pytest.raises(coordinator.SyncPublishError) as caught:
555
+ coordinator.synchronize_project(
556
+ root,
557
+ apply=True,
558
+ run_timestamp="2026-07-30T01:00:00+00:00",
559
+ )
560
+
561
+ result = caught.value.result
562
+ publish = result["publish"]
563
+ assert result["manifest"]["changed"] is False
564
+ assert result["markers"]["candidate_count"] == 0
565
+ assert result["claude"]["changed"] is False
566
+ assert publish["disposition"] == "not-installed"
567
+ assert publish["manifest_disposition"] == "unchanged"
568
+ assert publish["scan_state_disposition"] == "not-installed"
569
+ assert publish["manifest_commit_point"] is False
570
+ assert publish["scan_state_committed"] is False
571
+ assert publish["partial_commit"] is False
572
+ assert publish["published"] == []
573
+ assert "manifest=unchanged" in str(caught.value)
574
+ assert "installed_artifacts=0" in str(caught.value)
575
+ assert "manifest is committed" not in str(caught.value)
576
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == manifest_before
577
+ assert (docs_root / coordinator.SCAN_STATE_FILENAME).read_bytes() == scan_before
578
+
579
+
580
+ def test_pending_phase4_journal_blocks_coordinator_before_scan(
581
+ tmp_path: Path,
582
+ monkeypatch: pytest.MonkeyPatch,
583
+ ) -> None:
584
+ root, docs_root = _project(tmp_path)
585
+ initial, initial_code = coordinator.synchronize_project(
586
+ root,
587
+ apply=True,
588
+ run_timestamp=SYNCED,
589
+ )
590
+ assert initial_code == coordinator.EXIT_OK
591
+ assert initial["publish"]["completed"] is True
592
+ manifest_before = (docs_root / contract.MANIFEST_FILENAME).read_bytes()
593
+ scan_state_before = (docs_root / coordinator.SCAN_STATE_FILENAME).read_bytes()
594
+ (root / "module" / "__init__.py").unlink()
595
+ (root / "module").rmdir()
596
+
597
+ class SimulatedCrash(BaseException):
598
+ pass
599
+
600
+ def crash_after_prepare(point: str) -> None:
601
+ if point == "quarantine-journal-ready":
602
+ raise SimulatedCrash(point)
603
+
604
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", crash_after_prepare)
605
+ with pytest.raises(SimulatedCrash):
606
+ phase4_exit.apply_quarantine(root)
607
+
608
+ journals = [
609
+ docs_root
610
+ / phase4_exit.QUARANTINE_DIRNAME
611
+ / phase4_exit._TRANSACTION_CANONICAL_FILENAME
612
+ ]
613
+ assert journals[0].is_file()
614
+ report, exit_code = coordinator.synchronize_project(
615
+ root,
616
+ apply=True,
617
+ run_timestamp="2026-07-30T01:00:00+00:00",
618
+ )
619
+
620
+ assert exit_code == coordinator.EXIT_GATE_FAILED
621
+ assert report["status"] == "phase4-recovery-required"
622
+ assert report["scan"]["commit_needed"] is False
623
+ assert report["scan"]["blocked_by_phase4_recovery"] is True
624
+ assert report["planned_writes"] == []
625
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == manifest_before
626
+ assert (
627
+ docs_root / coordinator.SCAN_STATE_FILENAME
628
+ ).read_bytes() == scan_state_before
629
+ assert journals[0].is_file()
630
+
631
+
632
+ def test_pending_coordinator_journal_blocks_runs_and_recovers_clean_preimage(
633
+ tmp_path: Path,
634
+ monkeypatch: pytest.MonkeyPatch,
635
+ ) -> None:
636
+ root, _ = _project(tmp_path)
637
+ before = _file_bytes(root)
638
+
639
+ def crash_after_journal(point: str) -> None:
640
+ if point == "publish-journal-ready":
641
+ raise KeyboardInterrupt("journal-ready")
642
+
643
+ monkeypatch.setattr(coordinator, "_publish_fault", crash_after_journal)
644
+ with pytest.raises(KeyboardInterrupt, match="journal-ready"):
645
+ coordinator.synchronize_project(
646
+ root,
647
+ apply=True,
648
+ run_timestamp=SYNCED,
649
+ )
650
+
651
+ paths = coordinator._project_paths(root)
652
+ journal_path = coordinator._publish_journal_path(paths)
653
+ assert journal_path.is_file()
654
+ assert _file_bytes(root) == before
655
+
656
+ blocked, blocked_code = coordinator.synchronize_project(
657
+ root,
658
+ run_timestamp=SYNCED,
659
+ )
660
+ assert blocked_code == coordinator.EXIT_GATE_FAILED
661
+ assert blocked["status"] == "coordinator-recovery-required"
662
+ assert blocked["planned_writes"] == []
663
+
664
+ recovered, recovered_code = coordinator.recover_project(root)
665
+ assert recovered_code == coordinator.EXIT_OK
666
+ assert recovered["recovery"]["action"] == "rolled-back"
667
+ assert not journal_path.exists()
668
+ assert _file_bytes(root) == before
669
+
670
+
671
+ def test_precommit_process_loss_recovers_marker_and_claude_preimages(
672
+ tmp_path: Path,
673
+ monkeypatch: pytest.MonkeyPatch,
674
+ ) -> None:
675
+ root, docs_root = _project(tmp_path, corrupt_marker=True)
676
+ before = _file_bytes(root)
677
+
678
+ def fail_before_manifest(_prepared: coordinator.PreparedSync) -> None:
679
+ raise OSError("before-manifest")
680
+
681
+ def terminate_during_rollback(
682
+ _artifacts,
683
+ _paths,
684
+ _artifact_root,
685
+ _artifact_root_identity,
686
+ ) -> list[dict[str, str]]:
687
+ raise KeyboardInterrupt("rollback-process-loss")
688
+
689
+ monkeypatch.setattr(coordinator, "_documents_match_candidate", fail_before_manifest)
690
+ monkeypatch.setattr(coordinator, "_rollback_artifacts", terminate_during_rollback)
691
+
692
+ with pytest.raises(KeyboardInterrupt, match="rollback-process-loss"):
693
+ coordinator.synchronize_project(
694
+ root,
695
+ apply=True,
696
+ run_timestamp=SYNCED,
697
+ )
698
+
699
+ paths = coordinator._project_paths(root)
700
+ journal_path = coordinator._publish_journal_path(paths)
701
+ assert journal_path.is_file()
702
+ assert (root / "CLAUDE.md").read_bytes() != before["CLAUDE.md"]
703
+ assert (docs_root / "module.md").read_bytes() != before["project_docs/module.md"]
704
+ assert not (docs_root / contract.MANIFEST_FILENAME).exists()
705
+
706
+ recovered, recovered_code = coordinator.recover_project(root)
707
+ assert recovered_code == coordinator.EXIT_OK
708
+ assert recovered["recovery"]["action"] == "rolled-back"
709
+ assert not journal_path.exists()
710
+ assert _file_bytes(root) == before
711
+
712
+
713
+ def test_forged_committed_slot_cannot_finalize_precommit_state(
714
+ tmp_path: Path,
715
+ monkeypatch: pytest.MonkeyPatch,
716
+ ) -> None:
717
+ root, _ = _project(tmp_path)
718
+
719
+ def interrupt_after_journal(point: str) -> None:
720
+ if point == "publish-journal-ready":
721
+ raise KeyboardInterrupt("journal-ready")
722
+
723
+ monkeypatch.setattr(coordinator, "_publish_fault", interrupt_after_journal)
724
+ with pytest.raises(KeyboardInterrupt, match="journal-ready"):
725
+ coordinator.synchronize_project(
726
+ root,
727
+ apply=True,
728
+ run_timestamp=SYNCED,
729
+ )
730
+
731
+ slots = contract.coordinator_publish_journal_paths(root)
732
+ slots["prepared"].rename(slots["committed"])
733
+ with pytest.raises(
734
+ coordinator.SyncInputError,
735
+ match="committed publish outcome does not match",
736
+ ):
737
+ coordinator.recover_project(root)
738
+ assert slots["committed"].is_file()
739
+
740
+ slots["committed"].rename(slots["prepared"])
741
+ monkeypatch.setattr(coordinator, "_publish_fault", lambda _point: None)
742
+ recovered, recovered_code = coordinator.recover_project(root)
743
+ assert recovered_code == coordinator.EXIT_OK
744
+ assert recovered["recovery"]["action"] == "rolled-back"
745
+ assert not any(path.exists() for path in slots.values())
746
+
747
+
748
+
749
+ def test_forged_rolled_back_slot_cannot_finalize_partial_state(
750
+ tmp_path: Path,
751
+ monkeypatch: pytest.MonkeyPatch,
752
+ ) -> None:
753
+ root, _ = _project(tmp_path, corrupt_marker=True)
754
+ before = _file_bytes(root)
755
+
756
+ def fail_before_manifest(_prepared: coordinator.PreparedSync) -> None:
757
+ raise OSError("before-manifest")
758
+
759
+ def terminate_during_rollback(
760
+ _artifacts,
761
+ _paths,
762
+ _artifact_root,
763
+ _artifact_root_identity,
764
+ ) -> list[dict[str, str]]:
765
+ raise KeyboardInterrupt("rollback-process-loss")
766
+
767
+ monkeypatch.setattr(coordinator, "_documents_match_candidate", fail_before_manifest)
768
+ monkeypatch.setattr(coordinator, "_rollback_artifacts", terminate_during_rollback)
769
+ with pytest.raises(KeyboardInterrupt, match="rollback-process-loss"):
770
+ coordinator.synchronize_project(
771
+ root,
772
+ apply=True,
773
+ run_timestamp=SYNCED,
774
+ )
775
+
776
+ slots = contract.coordinator_publish_journal_paths(root)
777
+ slots["prepared"].rename(slots["rolled_back"])
778
+ with pytest.raises(
779
+ coordinator.SyncInputError,
780
+ match="rolled_back publish outcome does not match",
781
+ ):
782
+ coordinator.recover_project(root)
783
+ assert slots["rolled_back"].is_file()
784
+
785
+ slots["rolled_back"].rename(slots["prepared"])
786
+ recovered, recovered_code = coordinator.recover_project(root)
787
+ assert recovered_code == coordinator.EXIT_OK
788
+ assert recovered["recovery"]["action"] == "rolled-back"
789
+ assert _file_bytes(root) == before
790
+ assert not any(path.exists() for path in slots.values())
791
+
792
+
793
+
794
+ def test_post_manifest_recovery_completes_scan_state_forward(
795
+ tmp_path: Path,
796
+ monkeypatch: pytest.MonkeyPatch,
797
+ ) -> None:
798
+ root, docs_root = _project(tmp_path)
799
+
800
+ def interrupt_after_manifest(point: str) -> None:
801
+ if point == "manifest-verified":
802
+ raise KeyboardInterrupt("manifest-verified")
803
+
804
+ monkeypatch.setattr(coordinator, "_publish_fault", interrupt_after_manifest)
805
+ with pytest.raises(coordinator.SyncPublishError) as caught:
806
+ coordinator.synchronize_project(
807
+ root,
808
+ apply=True,
809
+ run_timestamp=SYNCED,
810
+ )
811
+
812
+ assert caught.value.result["publish"]["manifest_commit_point"] is True
813
+ paths = coordinator._project_paths(root)
814
+ journal_path = coordinator._publish_journal_path(paths)
815
+ assert journal_path.is_file()
816
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
817
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
818
+
819
+ recovered, recovered_code = coordinator.recover_project(root)
820
+ assert recovered_code == coordinator.EXIT_OK
821
+ assert recovered["recovery"]["action"] == "completed-forward"
822
+ assert recovered["publish"]["completed"] is True
823
+ assert not journal_path.exists()
824
+ assert (
825
+ scan_dirs.load_previous_state(docs_root / coordinator.SCAN_STATE_FILENAME)
826
+ is not None
827
+ )
828
+
829
+
830
+ def test_manifest_preimage_replacement_after_candidate_selection_is_not_overwritten(
831
+ tmp_path: Path,
832
+ monkeypatch: pytest.MonkeyPatch,
833
+ ) -> None:
834
+ root, docs_root = _project(tmp_path)
835
+ initial, initial_code = coordinator.synchronize_project(
836
+ root,
837
+ apply=True,
838
+ run_timestamp=SYNCED,
839
+ )
840
+ assert initial_code == coordinator.EXIT_OK
841
+ assert initial["publish"]["completed"] is True
842
+
843
+ external_manifest = b'{"external":"manifest replacement"}\n'
844
+ original_select = coordinator._select_manifest
845
+
846
+ def replace_after_selection(*args, **kwargs):
847
+ selected = original_select(*args, **kwargs)
848
+ (docs_root / contract.MANIFEST_FILENAME).write_bytes(external_manifest)
849
+ return selected
850
+
851
+ monkeypatch.setattr(coordinator, "_select_manifest", replace_after_selection)
852
+
853
+ with pytest.raises(
854
+ coordinator.SyncInputError, match="manifest changed during staging"
855
+ ):
856
+ coordinator.synchronize_project(
857
+ root,
858
+ apply=True,
859
+ run_timestamp="2026-07-30T01:00:00+00:00",
860
+ )
861
+
862
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == external_manifest
863
+
864
+
865
+ def test_scan_state_preimage_replacement_after_candidate_build_is_not_overwritten(
866
+ tmp_path: Path,
867
+ monkeypatch: pytest.MonkeyPatch,
868
+ ) -> None:
869
+ root, docs_root = _project(tmp_path)
870
+ initial, initial_code = coordinator.synchronize_project(
871
+ root,
872
+ apply=True,
873
+ run_timestamp=SYNCED,
874
+ )
875
+ assert initial_code == coordinator.EXIT_OK
876
+ assert initial["publish"]["completed"] is True
877
+ manifest_before = (docs_root / contract.MANIFEST_FILENAME).read_bytes()
878
+
879
+ external_state = b'{"external":"scan-state replacement"}\n'
880
+ original_scan_candidate = coordinator._scan_candidate
881
+
882
+ def replace_after_candidate(*args, **kwargs):
883
+ selected = original_scan_candidate(*args, **kwargs)
884
+ (docs_root / coordinator.SCAN_STATE_FILENAME).write_bytes(external_state)
885
+ return selected
886
+
887
+ monkeypatch.setattr(coordinator, "_scan_candidate", replace_after_candidate)
888
+
889
+ with pytest.raises(
890
+ coordinator.SyncInputError, match="scan state changed during staging"
891
+ ):
892
+ coordinator.synchronize_project(
893
+ root,
894
+ apply=True,
895
+ run_timestamp="2026-07-30T01:00:00+00:00",
896
+ )
897
+
898
+ assert (docs_root / coordinator.SCAN_STATE_FILENAME).read_bytes() == external_state
899
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == manifest_before
900
+
901
+
902
+ def test_document_added_after_final_precommit_check_reports_partial_commit(
903
+ tmp_path: Path,
904
+ monkeypatch: pytest.MonkeyPatch,
905
+ ) -> None:
906
+ root, docs_root = _project(tmp_path)
907
+ original_check = coordinator._documents_match_candidate
908
+
909
+ def add_after_check(prepared: coordinator.PreparedSync) -> None:
910
+ original_check(prepared)
911
+ _write(docs_root / "late.md", "# Late\n")
912
+
913
+ monkeypatch.setattr(coordinator, "_documents_match_candidate", add_after_check)
914
+
915
+ with pytest.raises(coordinator.SyncPublishError) as caught:
916
+ coordinator.synchronize_project(
917
+ root,
918
+ apply=True,
919
+ run_timestamp=SYNCED,
920
+ )
921
+
922
+ publish = caught.value.result["publish"]
923
+ assert publish["manifest_commit_point"] is True
924
+ assert publish["partial_commit"] is True
925
+ assert publish["rolled_back"] is False
926
+ assert (docs_root / "late.md").read_text(encoding="utf-8") == "# Late\n"
927
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
928
+ with pytest.raises(contract.ManifestValidationError):
929
+ contract.load_manifest(docs_root, verify_files=True, verify_complete_set=True)
930
+
931
+
932
+ def test_document_modified_after_final_precommit_check_is_never_overwritten(
933
+ tmp_path: Path,
934
+ monkeypatch: pytest.MonkeyPatch,
935
+ ) -> None:
936
+ root, docs_root = _project(tmp_path)
937
+ document = docs_root / "module.md"
938
+ external_content = "# concurrent document replacement\n"
939
+ original_check = coordinator._documents_match_candidate
940
+
941
+ def replace_after_check(prepared: coordinator.PreparedSync) -> None:
942
+ original_check(prepared)
943
+ document.write_text(external_content, encoding="utf-8")
944
+
945
+ monkeypatch.setattr(coordinator, "_documents_match_candidate", replace_after_check)
946
+
947
+ with pytest.raises(coordinator.SyncPublishError) as caught:
948
+ coordinator.synchronize_project(
949
+ root,
950
+ apply=True,
951
+ run_timestamp=SYNCED,
952
+ )
953
+
954
+ publish = caught.value.result["publish"]
955
+ assert publish["manifest_commit_point"] is True
956
+ assert publish["partial_commit"] is True
957
+ assert document.read_text(encoding="utf-8") == external_content
958
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
959
+
960
+
961
+ def test_noop_apply_rechecks_pending_phase4_journal_inside_lock(
962
+ tmp_path: Path,
963
+ monkeypatch: pytest.MonkeyPatch,
964
+ ) -> None:
965
+ root, docs_root = _project(tmp_path)
966
+ initial, initial_code = coordinator.synchronize_project(
967
+ root,
968
+ apply=True,
969
+ run_timestamp=SYNCED,
970
+ )
971
+ assert initial_code == coordinator.EXIT_OK
972
+ assert initial["publish"]["completed"] is True
973
+ manifest_before = (docs_root / contract.MANIFEST_FILENAME).read_bytes()
974
+ scan_state_before = (docs_root / coordinator.SCAN_STATE_FILENAME).read_bytes()
975
+
976
+ original_pending = phase4_exit.pending_recovery_status
977
+ calls = 0
978
+ journal = (
979
+ docs_root
980
+ / phase4_exit.QUARANTINE_DIRNAME
981
+ / f"{phase4_exit._TRANSACTION_PREFIX}{'0' * 32}.json"
982
+ )
983
+
984
+ def create_journal_after_unlocked_gate(root_value):
985
+ nonlocal calls
986
+ calls += 1
987
+ result = original_pending(root_value)
988
+ if calls == 2:
989
+ journal.parent.mkdir(parents=True, exist_ok=True)
990
+ journal.write_text("{", encoding="utf-8")
991
+ return result
992
+
993
+ monkeypatch.setattr(
994
+ phase4_exit,
995
+ "pending_recovery_status",
996
+ create_journal_after_unlocked_gate,
997
+ )
998
+
999
+ report, exit_code = coordinator.synchronize_project(
1000
+ root,
1001
+ apply=True,
1002
+ run_timestamp="2026-07-30T01:00:00+00:00",
1003
+ )
1004
+
1005
+ assert calls == 3
1006
+ assert exit_code == coordinator.EXIT_GATE_FAILED
1007
+ assert report["status"] == "phase4-recovery-required"
1008
+ assert report["planned_writes"] == []
1009
+ assert report["publish"]["completed"] is False
1010
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == manifest_before
1011
+ assert (
1012
+ docs_root / coordinator.SCAN_STATE_FILENAME
1013
+ ).read_bytes() == scan_state_before
1014
+ assert journal.read_text(encoding="utf-8") == "{"
1015
+
1016
+
1017
+ def test_marker_post_replace_keyboard_interrupt_is_rolled_back(
1018
+ tmp_path: Path,
1019
+ monkeypatch: pytest.MonkeyPatch,
1020
+ ) -> None:
1021
+ root, docs_root = _project(tmp_path, corrupt_marker=True)
1022
+ before = _file_bytes(root)
1023
+ original_set_snapshot = phase4_exit._set_snapshot_state
1024
+ interrupted = False
1025
+
1026
+ def interrupt_after_marker_replace(
1027
+ path: Path,
1028
+ base: Path,
1029
+ description: str,
1030
+ desired,
1031
+ allowed_current,
1032
+ **kwargs,
1033
+ ) -> None:
1034
+ nonlocal interrupted
1035
+ original_set_snapshot(
1036
+ path,
1037
+ base,
1038
+ description,
1039
+ desired,
1040
+ allowed_current,
1041
+ **kwargs,
1042
+ )
1043
+ if (
1044
+ path == docs_root / "module.md"
1045
+ and description == "marker"
1046
+ and not interrupted
1047
+ ):
1048
+ interrupted = True
1049
+ raise KeyboardInterrupt("marker-post-replace")
1050
+
1051
+ monkeypatch.setattr(
1052
+ phase4_exit,
1053
+ "_set_snapshot_state",
1054
+ interrupt_after_marker_replace,
1055
+ )
1056
+
1057
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1058
+ coordinator.synchronize_project(
1059
+ root,
1060
+ apply=True,
1061
+ run_timestamp=SYNCED,
1062
+ )
1063
+
1064
+ publish = caught.value.result["publish"]
1065
+ assert interrupted is True
1066
+ assert publish["manifest_commit_point"] is False
1067
+ assert publish["rolled_back"] is True
1068
+ assert publish["rollback_failures"] == []
1069
+ assert _file_bytes(root) == before
1070
+
1071
+
1072
+ def test_claude_post_replace_keyboard_interrupt_is_rolled_back(
1073
+ tmp_path: Path,
1074
+ monkeypatch: pytest.MonkeyPatch,
1075
+ ) -> None:
1076
+ root, _ = _project(tmp_path)
1077
+ before = _file_bytes(root)
1078
+ original_set_snapshot = phase4_exit._set_snapshot_state
1079
+ interrupted = False
1080
+
1081
+ def interrupt_after_claude_replace(
1082
+ path: Path,
1083
+ base: Path,
1084
+ description: str,
1085
+ desired,
1086
+ allowed_current,
1087
+ **kwargs,
1088
+ ) -> None:
1089
+ nonlocal interrupted
1090
+ original_set_snapshot(
1091
+ path,
1092
+ base,
1093
+ description,
1094
+ desired,
1095
+ allowed_current,
1096
+ **kwargs,
1097
+ )
1098
+ if (
1099
+ path == root / "CLAUDE.md"
1100
+ and description == "claude-index"
1101
+ and not interrupted
1102
+ ):
1103
+ interrupted = True
1104
+ raise KeyboardInterrupt("claude-post-replace")
1105
+
1106
+ monkeypatch.setattr(
1107
+ phase4_exit,
1108
+ "_set_snapshot_state",
1109
+ interrupt_after_claude_replace,
1110
+ )
1111
+
1112
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1113
+ coordinator.synchronize_project(
1114
+ root,
1115
+ apply=True,
1116
+ run_timestamp=SYNCED,
1117
+ )
1118
+
1119
+ publish = caught.value.result["publish"]
1120
+ assert interrupted is True
1121
+ assert publish["manifest_commit_point"] is False
1122
+ assert publish["rolled_back"] is True
1123
+ assert publish["rollback_failures"] == []
1124
+ assert _file_bytes(root) == before
1125
+
1126
+
1127
+ def test_manifest_post_replace_keyboard_interrupt_is_partial_commit(
1128
+ tmp_path: Path,
1129
+ monkeypatch: pytest.MonkeyPatch,
1130
+ ) -> None:
1131
+ root, docs_root = _project(tmp_path)
1132
+ original_set_snapshot = phase4_exit._set_snapshot_state
1133
+ interrupted = False
1134
+
1135
+ def interrupt_after_manifest_replace(
1136
+ path: Path,
1137
+ base: Path,
1138
+ description: str,
1139
+ desired,
1140
+ allowed_current,
1141
+ **kwargs,
1142
+ ) -> None:
1143
+ nonlocal interrupted
1144
+ original_set_snapshot(
1145
+ path,
1146
+ base,
1147
+ description,
1148
+ desired,
1149
+ allowed_current,
1150
+ **kwargs,
1151
+ )
1152
+ if (
1153
+ path == docs_root / contract.MANIFEST_FILENAME
1154
+ and description == "manifest"
1155
+ and not interrupted
1156
+ ):
1157
+ interrupted = True
1158
+ raise KeyboardInterrupt("manifest-post-replace")
1159
+
1160
+ monkeypatch.setattr(
1161
+ phase4_exit,
1162
+ "_set_snapshot_state",
1163
+ interrupt_after_manifest_replace,
1164
+ )
1165
+
1166
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1167
+ coordinator.synchronize_project(
1168
+ root,
1169
+ apply=True,
1170
+ run_timestamp=SYNCED,
1171
+ )
1172
+
1173
+ publish = caught.value.result["publish"]
1174
+ assert interrupted is True
1175
+ assert publish["manifest_commit_point"] is True
1176
+ assert publish["partial_commit"] is True
1177
+ assert publish["rolled_back"] is False
1178
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
1179
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
1180
+
1181
+
1182
+ def test_scan_state_post_replace_keyboard_interrupt_is_reported_as_committed(
1183
+ tmp_path: Path,
1184
+ monkeypatch: pytest.MonkeyPatch,
1185
+ ) -> None:
1186
+ root, docs_root = _project(tmp_path)
1187
+ original_set_snapshot = phase4_exit._set_snapshot_state
1188
+ interrupted = False
1189
+
1190
+ def interrupt_after_scan_replace(
1191
+ path: Path,
1192
+ base: Path,
1193
+ description: str,
1194
+ desired,
1195
+ allowed_current,
1196
+ **kwargs,
1197
+ ) -> None:
1198
+ nonlocal interrupted
1199
+ original_set_snapshot(
1200
+ path,
1201
+ base,
1202
+ description,
1203
+ desired,
1204
+ allowed_current,
1205
+ **kwargs,
1206
+ )
1207
+ if (
1208
+ path == docs_root / coordinator.SCAN_STATE_FILENAME
1209
+ and description == "scan state"
1210
+ and not interrupted
1211
+ ):
1212
+ interrupted = True
1213
+ raise KeyboardInterrupt("scan-post-replace")
1214
+
1215
+ monkeypatch.setattr(
1216
+ phase4_exit,
1217
+ "_set_snapshot_state",
1218
+ interrupt_after_scan_replace,
1219
+ )
1220
+
1221
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1222
+ coordinator.synchronize_project(
1223
+ root,
1224
+ apply=True,
1225
+ run_timestamp=SYNCED,
1226
+ )
1227
+
1228
+ publish = caught.value.result["publish"]
1229
+ assert interrupted is True
1230
+ assert publish["manifest_commit_point"] is True
1231
+ assert publish["scan_state_committed"] is True
1232
+ assert publish["partial_commit"] is True
1233
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
1234
+ committed_state = scan_dirs.load_previous_state(
1235
+ docs_root / coordinator.SCAN_STATE_FILENAME
1236
+ )
1237
+ assert committed_state is not None
1238
+ assert committed_state["state_role"] == "committed"
1239
+
1240
+
1241
+ def test_manifest_post_replace_with_failed_readback_is_never_rolled_back(
1242
+ tmp_path: Path,
1243
+ monkeypatch: pytest.MonkeyPatch,
1244
+ ) -> None:
1245
+ root, docs_root = _project(tmp_path)
1246
+ original_set_snapshot = phase4_exit._set_snapshot_state
1247
+ original_optional_bytes = coordinator._optional_bytes
1248
+ manifest_replaced = False
1249
+
1250
+ def fail_after_manifest_replace(
1251
+ path: Path,
1252
+ base: Path,
1253
+ description: str,
1254
+ desired,
1255
+ allowed_current,
1256
+ **kwargs,
1257
+ ) -> None:
1258
+ nonlocal manifest_replaced
1259
+ original_set_snapshot(
1260
+ path,
1261
+ base,
1262
+ description,
1263
+ desired,
1264
+ allowed_current,
1265
+ **kwargs,
1266
+ )
1267
+ if (
1268
+ path == docs_root / contract.MANIFEST_FILENAME
1269
+ and description == "manifest"
1270
+ ):
1271
+ manifest_replaced = True
1272
+ raise OSError("injected post-replace failure")
1273
+
1274
+ def fail_manifest_readback(path: Path) -> bytes | None:
1275
+ if manifest_replaced and path == docs_root / contract.MANIFEST_FILENAME:
1276
+ raise OSError("injected manifest readback failure")
1277
+ return original_optional_bytes(path)
1278
+
1279
+ monkeypatch.setattr(
1280
+ phase4_exit,
1281
+ "_set_snapshot_state",
1282
+ fail_after_manifest_replace,
1283
+ )
1284
+ monkeypatch.setattr(coordinator, "_optional_bytes", fail_manifest_readback)
1285
+
1286
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1287
+ coordinator.synchronize_project(
1288
+ root,
1289
+ apply=True,
1290
+ run_timestamp=SYNCED,
1291
+ )
1292
+
1293
+ publish = caught.value.result["publish"]
1294
+ assert manifest_replaced is True
1295
+ assert publish["manifest_commit_point"] is False
1296
+ assert publish["manifest_commit_ambiguous"] is True
1297
+ assert publish["partial_commit"] is True
1298
+ assert publish["rolled_back"] is False
1299
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
1300
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
1301
+
1302
+
1303
+ def test_marker_source_changed_between_collection_and_staging_is_preserved(
1304
+ tmp_path: Path,
1305
+ monkeypatch: pytest.MonkeyPatch,
1306
+ ) -> None:
1307
+ root, docs_root = _project(tmp_path, corrupt_marker=True)
1308
+ document = docs_root / "module.md"
1309
+ concurrent_content = document.read_text(encoding="utf-8") + "\n并发新增内容。\n"
1310
+ original_collect = coordinator._normalized_marker_files
1311
+
1312
+ def mutate_after_collection(project_docs: Path):
1313
+ result = original_collect(project_docs)
1314
+ document.write_text(concurrent_content, encoding="utf-8")
1315
+ return result
1316
+
1317
+ monkeypatch.setattr(
1318
+ coordinator,
1319
+ "_normalized_marker_files",
1320
+ mutate_after_collection,
1321
+ )
1322
+
1323
+ with pytest.raises(
1324
+ coordinator.SyncInputError,
1325
+ match="marker source changed between collection and staging",
1326
+ ):
1327
+ coordinator.synchronize_project(
1328
+ root,
1329
+ apply=True,
1330
+ run_timestamp=SYNCED,
1331
+ )
1332
+
1333
+ assert document.read_text(encoding="utf-8") == concurrent_content
1334
+ assert not (docs_root / contract.MANIFEST_FILENAME).exists()
1335
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
1336
+
1337
+
1338
+ def test_claude_candidate_never_rereads_live_path_after_preimage_capture(
1339
+ tmp_path: Path,
1340
+ monkeypatch: pytest.MonkeyPatch,
1341
+ ) -> None:
1342
+ root, _ = _project(tmp_path)
1343
+ claude_path = root / "CLAUDE.md"
1344
+ original = claude_path.read_text(encoding="utf-8")
1345
+ transient = original.replace("manual-before", "transient-manual-content")
1346
+ reread_calls = 0
1347
+
1348
+ def transient_claude_reread(path: Path) -> str:
1349
+ nonlocal reread_calls
1350
+ reread_calls += 1
1351
+ claude_path.write_text(transient, encoding="utf-8")
1352
+ try:
1353
+ return transient
1354
+ finally:
1355
+ claude_path.write_text(original, encoding="utf-8")
1356
+
1357
+ monkeypatch.setattr(claude_doc_index, "read_utf8", transient_claude_reread)
1358
+
1359
+ report, exit_code = coordinator.synchronize_project(
1360
+ root,
1361
+ apply=True,
1362
+ run_timestamp=SYNCED,
1363
+ )
1364
+
1365
+ assert exit_code == coordinator.EXIT_OK
1366
+ assert report["publish"]["completed"] is True
1367
+ assert reread_calls == 0
1368
+ committed = claude_path.read_text(encoding="utf-8")
1369
+ assert "manual-before" in committed
1370
+ assert "transient-manual-content" not in committed
1371
+
1372
+
1373
+ def test_manifest_candidate_is_derived_from_captured_bytes_during_aba(
1374
+ tmp_path: Path,
1375
+ monkeypatch: pytest.MonkeyPatch,
1376
+ ) -> None:
1377
+ root, docs_root = _project(tmp_path)
1378
+ initial, initial_code = coordinator.synchronize_project(
1379
+ root,
1380
+ apply=True,
1381
+ run_timestamp=SYNCED,
1382
+ )
1383
+ assert initial_code == coordinator.EXIT_OK
1384
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
1385
+ original_bytes = manifest_path.read_bytes()
1386
+ transient_manifest = json.loads(original_bytes.decode("utf-8"))
1387
+ transient_manifest["last_synced"] = "2099-01-01T00:00:00+00:00"
1388
+ transient_bytes = contract.stable_json_dumps(transient_manifest).encode("utf-8")
1389
+ original_loader = coordinator._load_current_manifest
1390
+
1391
+ def load_during_aba(paths, captured_bytes, captured_docs):
1392
+ manifest_path.write_bytes(transient_bytes)
1393
+ try:
1394
+ return original_loader(paths, captured_bytes, captured_docs)
1395
+ finally:
1396
+ manifest_path.write_bytes(original_bytes)
1397
+
1398
+ monkeypatch.setattr(coordinator, "_load_current_manifest", load_during_aba)
1399
+
1400
+ report, exit_code = coordinator.synchronize_project(
1401
+ root,
1402
+ apply=True,
1403
+ run_timestamp="2026-07-30T01:00:00+00:00",
1404
+ )
1405
+
1406
+ assert exit_code == coordinator.EXIT_OK
1407
+ assert report["manifest"]["changed"] is False
1408
+ assert report["publish"]["published"] == []
1409
+ assert manifest_path.read_bytes() == original_bytes
1410
+
1411
+
1412
+ def test_captured_manifest_is_validated_against_frozen_document_bytes(
1413
+ tmp_path: Path,
1414
+ monkeypatch: pytest.MonkeyPatch,
1415
+ ) -> None:
1416
+ root, docs_root = _project(tmp_path)
1417
+ initial, initial_code = coordinator.synchronize_project(
1418
+ root,
1419
+ apply=True,
1420
+ run_timestamp=SYNCED,
1421
+ )
1422
+ assert initial_code == coordinator.EXIT_OK
1423
+ document = docs_root / "module.md"
1424
+ original_document = document.read_bytes()
1425
+ original_loader = coordinator._load_current_manifest
1426
+
1427
+ def load_while_live_document_is_transient(paths, captured_bytes, captured_docs):
1428
+ document.write_bytes(b"# transient live document\n")
1429
+ try:
1430
+ return original_loader(paths, captured_bytes, captured_docs)
1431
+ finally:
1432
+ document.write_bytes(original_document)
1433
+
1434
+ monkeypatch.setattr(
1435
+ coordinator,
1436
+ "_load_current_manifest",
1437
+ load_while_live_document_is_transient,
1438
+ )
1439
+
1440
+ report, exit_code = coordinator.synchronize_project(
1441
+ root,
1442
+ apply=True,
1443
+ run_timestamp="2026-07-30T01:00:00+00:00",
1444
+ )
1445
+
1446
+ assert exit_code == coordinator.EXIT_OK
1447
+ assert report["manifest"]["changed"] is False
1448
+ assert report["planned_writes"] == []
1449
+ assert document.read_bytes() == original_document
1450
+
1451
+
1452
+ def test_validation_uses_the_stable_source_snapshot_during_aba(
1453
+ tmp_path: Path,
1454
+ monkeypatch: pytest.MonkeyPatch,
1455
+ ) -> None:
1456
+ root, _ = _project(tmp_path)
1457
+ transient_file = root / "module" / "payload.py"
1458
+ original_validate = coordinator._validate_documents
1459
+
1460
+ def validate_during_source_aba(*args, **kwargs):
1461
+ transient_file.write_text("value = 1\n", encoding="utf-8")
1462
+ try:
1463
+ return original_validate(*args, **kwargs)
1464
+ finally:
1465
+ transient_file.unlink()
1466
+
1467
+ monkeypatch.setattr(coordinator, "_validate_documents", validate_during_source_aba)
1468
+
1469
+ report, exit_code = coordinator.synchronize_project(
1470
+ root,
1471
+ apply=True,
1472
+ run_timestamp=SYNCED,
1473
+ )
1474
+
1475
+ assert exit_code == coordinator.EXIT_OK
1476
+ assert report["validation"]["blocking_failure_count"] == 0
1477
+ assert report["publish"]["completed"] is True
1478
+ assert not transient_file.exists()
1479
+
1480
+
1481
+ def test_phase4_uses_frozen_absence_during_source_aba(
1482
+ tmp_path: Path,
1483
+ monkeypatch: pytest.MonkeyPatch,
1484
+ ) -> None:
1485
+ root, docs_root = _project(tmp_path)
1486
+ ghost_doc = _placeholder_document().replace("module", "ghost")
1487
+ _write(docs_root / "ghost.md", ghost_doc)
1488
+ transient_source = root / "ghost"
1489
+ original_phase4 = coordinator._phase4_report
1490
+
1491
+ def phase4_during_source_aba(*args, **kwargs):
1492
+ transient_source.mkdir()
1493
+ try:
1494
+ return original_phase4(*args, **kwargs)
1495
+ finally:
1496
+ transient_source.rmdir()
1497
+
1498
+ monkeypatch.setattr(coordinator, "_phase4_report", phase4_during_source_aba)
1499
+
1500
+ report, exit_code = coordinator.synchronize_project(
1501
+ root,
1502
+ run_timestamp=SYNCED,
1503
+ )
1504
+
1505
+ assert exit_code == coordinator.EXIT_OK
1506
+ assert report["phase4"]["counts"]["candidates"] == 1
1507
+ assert report["phase4"]["candidates"][0]["path"] == "ghost.md"
1508
+ assert not transient_source.exists()
1509
+
1510
+
1511
+ def test_scan_candidate_is_derived_from_captured_bytes_during_aba(
1512
+ tmp_path: Path,
1513
+ monkeypatch: pytest.MonkeyPatch,
1514
+ ) -> None:
1515
+ root, docs_root = _project(tmp_path)
1516
+ initial, initial_code = coordinator.synchronize_project(
1517
+ root,
1518
+ apply=True,
1519
+ run_timestamp=SYNCED,
1520
+ )
1521
+ assert initial_code == coordinator.EXIT_OK
1522
+ state_path = docs_root / coordinator.SCAN_STATE_FILENAME
1523
+ original_bytes = state_path.read_bytes()
1524
+ transient_state = json.loads(original_bytes.decode("utf-8"))
1525
+ transient_state["committed_at"] = "2099-01-01T00:00:00+00:00"
1526
+ transient_bytes = contract.stable_json_dumps(transient_state).encode("utf-8")
1527
+ original_scan_candidate = coordinator._scan_candidate
1528
+ observed_precondition: dict[str, object] = {}
1529
+
1530
+ def scan_during_aba(
1531
+ paths,
1532
+ captured_bytes,
1533
+ *,
1534
+ force_full,
1535
+ manifest_generation_id,
1536
+ ):
1537
+ state_path.write_bytes(transient_bytes)
1538
+ try:
1539
+ selected = original_scan_candidate(
1540
+ paths,
1541
+ captured_bytes,
1542
+ force_full=force_full,
1543
+ manifest_generation_id=manifest_generation_id,
1544
+ )
1545
+ observed_precondition.update(selected[1]["baseline_precondition"])
1546
+ return selected
1547
+ finally:
1548
+ state_path.write_bytes(original_bytes)
1549
+
1550
+ monkeypatch.setattr(coordinator, "_scan_candidate", scan_during_aba)
1551
+
1552
+ report, exit_code = coordinator.synchronize_project(
1553
+ root,
1554
+ apply=True,
1555
+ run_timestamp="2026-07-30T01:00:00+00:00",
1556
+ )
1557
+
1558
+ assert exit_code == coordinator.EXIT_OK
1559
+ assert report["planned_writes"] == []
1560
+ assert observed_precondition["sha256"] == contract.sha256_bytes(original_bytes)
1561
+ assert observed_precondition["sha256"] != contract.sha256_bytes(transient_bytes)
1562
+ assert state_path.read_bytes() == original_bytes
1563
+
1564
+
1565
+ def test_successful_noop_apply_still_verifies_under_lock(tmp_path: Path) -> None:
1566
+ root, _ = _project(tmp_path)
1567
+ initial, initial_code = coordinator.synchronize_project(
1568
+ root,
1569
+ apply=True,
1570
+ run_timestamp=SYNCED,
1571
+ )
1572
+ assert initial_code == coordinator.EXIT_OK
1573
+ committed = _file_bytes(root)
1574
+
1575
+ report, exit_code = coordinator.synchronize_project(
1576
+ root,
1577
+ apply=True,
1578
+ run_timestamp="2026-07-30T01:00:00+00:00",
1579
+ )
1580
+
1581
+ assert exit_code == coordinator.EXIT_OK
1582
+ assert report["planned_writes"] == []
1583
+ assert report["publish"]["completed"] is True
1584
+ assert report["publish"]["disposition"] == "unchanged"
1585
+ assert report["publish"]["manifest_disposition"] == "unchanged"
1586
+ assert report["publish"]["scan_state_disposition"] == "unchanged"
1587
+ assert report["publish"]["manifest_commit_point"] is False
1588
+ assert report["publish"]["partial_commit"] is False
1589
+ assert report["publish"]["published"] == []
1590
+ assert _file_bytes(root) == committed
1591
+
1592
+
1593
+ def test_document_deleted_after_final_precommit_check_reports_partial_commit(
1594
+ tmp_path: Path,
1595
+ monkeypatch: pytest.MonkeyPatch,
1596
+ ) -> None:
1597
+ root, docs_root = _project(tmp_path)
1598
+ document = docs_root / "module.md"
1599
+ original_check = coordinator._documents_match_candidate
1600
+
1601
+ def delete_after_check(prepared: coordinator.PreparedSync) -> None:
1602
+ original_check(prepared)
1603
+ document.unlink()
1604
+
1605
+ monkeypatch.setattr(coordinator, "_documents_match_candidate", delete_after_check)
1606
+
1607
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1608
+ coordinator.synchronize_project(
1609
+ root,
1610
+ apply=True,
1611
+ run_timestamp=SYNCED,
1612
+ )
1613
+
1614
+ publish = caught.value.result["publish"]
1615
+ assert publish["manifest_commit_point"] is True
1616
+ assert publish["partial_commit"] is True
1617
+ assert not document.exists()
1618
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
1619
+
1620
+
1621
+ def test_document_change_after_manifest_verification_blocks_scan_promotion(
1622
+ tmp_path: Path,
1623
+ monkeypatch: pytest.MonkeyPatch,
1624
+ ) -> None:
1625
+ root, docs_root = _project(tmp_path)
1626
+ document = docs_root / "module.md"
1627
+ external_content = "# changed after manifest verification\n"
1628
+ original_verify = coordinator._verify_committed_manifest
1629
+ calls = 0
1630
+
1631
+ def change_after_first_verification(prepared: coordinator.PreparedSync) -> None:
1632
+ nonlocal calls
1633
+ original_verify(prepared)
1634
+ calls += 1
1635
+ if calls == 1:
1636
+ document.write_text(external_content, encoding="utf-8")
1637
+
1638
+ monkeypatch.setattr(
1639
+ coordinator,
1640
+ "_verify_committed_manifest",
1641
+ change_after_first_verification,
1642
+ )
1643
+
1644
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1645
+ coordinator.synchronize_project(
1646
+ root,
1647
+ apply=True,
1648
+ run_timestamp=SYNCED,
1649
+ )
1650
+
1651
+ publish = caught.value.result["publish"]
1652
+ assert calls == 1
1653
+ assert publish["manifest_commit_point"] is True
1654
+ assert publish["partial_commit"] is True
1655
+ assert document.read_text(encoding="utf-8") == external_content
1656
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
1657
+
1658
+
1659
+ def test_scan_state_build_keyboard_interrupt_happens_before_publication(
1660
+ tmp_path: Path,
1661
+ monkeypatch: pytest.MonkeyPatch,
1662
+ ) -> None:
1663
+ root, docs_root = _project(tmp_path)
1664
+
1665
+ def interrupt_build(candidate, state_path):
1666
+ raise KeyboardInterrupt("scan-build")
1667
+
1668
+ monkeypatch.setattr(
1669
+ coordinator,
1670
+ "_build_committed_scan_state",
1671
+ interrupt_build,
1672
+ )
1673
+
1674
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1675
+ coordinator.synchronize_project(
1676
+ root,
1677
+ apply=True,
1678
+ run_timestamp=SYNCED,
1679
+ )
1680
+
1681
+ publish = caught.value.result["publish"]
1682
+ assert publish["manifest_commit_point"] is False
1683
+ assert publish["scan_state_committed"] is False
1684
+ assert publish["scan_state_commit_ambiguous"] is False
1685
+ assert publish["partial_commit"] is False
1686
+ assert publish["rolled_back"] is True
1687
+ assert not (docs_root / contract.MANIFEST_FILENAME).exists()
1688
+ assert not (docs_root / coordinator.SCAN_STATE_FILENAME).exists()
1689
+
1690
+
1691
+ def test_scan_state_foreign_bytes_after_failure_are_ambiguous(
1692
+ tmp_path: Path,
1693
+ monkeypatch: pytest.MonkeyPatch,
1694
+ ) -> None:
1695
+ root, docs_root = _project(tmp_path)
1696
+ foreign_state = b'{"foreign":"scan state"}\n'
1697
+ state_path = docs_root / coordinator.SCAN_STATE_FILENAME
1698
+ original_rename = phase4_exit._rename_no_replace
1699
+
1700
+ def install_foreign_scan_state(source: Path, destination: Path) -> None:
1701
+ if Path(destination) == state_path:
1702
+ state_path.write_bytes(foreign_state)
1703
+ raise FileExistsError("injected foreign scan state")
1704
+ original_rename(source, destination)
1705
+
1706
+ monkeypatch.setattr(
1707
+ phase4_exit,
1708
+ "_rename_no_replace",
1709
+ install_foreign_scan_state,
1710
+ )
1711
+
1712
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1713
+ coordinator.synchronize_project(
1714
+ root,
1715
+ apply=True,
1716
+ run_timestamp=SYNCED,
1717
+ )
1718
+
1719
+ publish = caught.value.result["publish"]
1720
+ assert publish["disposition"] == "unknown"
1721
+ assert publish["manifest_commit_point"] is True
1722
+ assert publish["scan_state_committed"] is False
1723
+ assert publish["scan_state_commit_ambiguous"] is True
1724
+ assert publish["partial_commit"] is True
1725
+ assert (docs_root / coordinator.SCAN_STATE_FILENAME).read_bytes() == foreign_state
1726
+
1727
+
1728
+ def test_manifest_foreign_bytes_after_failure_are_ambiguous(
1729
+ tmp_path: Path,
1730
+ monkeypatch: pytest.MonkeyPatch,
1731
+ ) -> None:
1732
+ root, docs_root = _project(tmp_path)
1733
+ foreign_manifest = b'{"foreign":"manifest"}\n'
1734
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
1735
+ original_rename = phase4_exit._rename_no_replace
1736
+
1737
+ def install_foreign_manifest(source: Path, destination: Path) -> None:
1738
+ if Path(destination) == manifest_path:
1739
+ manifest_path.write_bytes(foreign_manifest)
1740
+ raise FileExistsError("injected foreign manifest")
1741
+ original_rename(source, destination)
1742
+
1743
+ monkeypatch.setattr(
1744
+ phase4_exit,
1745
+ "_rename_no_replace",
1746
+ install_foreign_manifest,
1747
+ )
1748
+
1749
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1750
+ coordinator.synchronize_project(
1751
+ root,
1752
+ apply=True,
1753
+ run_timestamp=SYNCED,
1754
+ )
1755
+
1756
+ publish = caught.value.result["publish"]
1757
+ assert publish["manifest_commit_point"] is False
1758
+ assert publish["manifest_commit_ambiguous"] is True
1759
+ assert publish["partial_commit"] is True
1760
+ assert publish["rolled_back"] is False
1761
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == foreign_manifest
1762
+
1763
+
1764
+ def test_lock_release_failure_after_commit_reports_installed_disposition(
1765
+ tmp_path: Path,
1766
+ monkeypatch: pytest.MonkeyPatch,
1767
+ ) -> None:
1768
+ root, docs_root = _project(tmp_path)
1769
+
1770
+ @contextmanager
1771
+ def fail_on_release(
1772
+ project_root: Path,
1773
+ *,
1774
+ timeout: float | None = 10.0,
1775
+ poll_interval: float = 0.05,
1776
+ ):
1777
+ assert project_root == root.resolve()
1778
+ assert timeout == 10.0
1779
+ assert poll_interval == 0.05
1780
+ yield object()
1781
+ raise OSError("injected lock release failure")
1782
+
1783
+ monkeypatch.setattr(contract, "project_sync_lock", fail_on_release)
1784
+
1785
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1786
+ coordinator.synchronize_project(
1787
+ root,
1788
+ apply=True,
1789
+ run_timestamp=SYNCED,
1790
+ )
1791
+
1792
+ publish = caught.value.result["publish"]
1793
+ assert publish["completed"] is False
1794
+ assert publish["disposition"] == "installed"
1795
+ assert publish["manifest_disposition"] == "installed"
1796
+ assert publish["scan_state_disposition"] == "installed"
1797
+ assert publish["manifest_commit_point"] is True
1798
+ assert publish["scan_state_committed"] is True
1799
+ assert publish["partial_commit"] is False
1800
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
1801
+ assert (
1802
+ scan_dirs.load_previous_state(docs_root / coordinator.SCAN_STATE_FILENAME)
1803
+ is not None
1804
+ )
1805
+
1806
+
1807
+ def test_noop_lock_release_failure_is_unchanged_not_partial(
1808
+ tmp_path: Path,
1809
+ monkeypatch: pytest.MonkeyPatch,
1810
+ ) -> None:
1811
+ root, _ = _project(tmp_path)
1812
+ initial, initial_code = coordinator.synchronize_project(
1813
+ root,
1814
+ apply=True,
1815
+ run_timestamp=SYNCED,
1816
+ )
1817
+ assert initial_code == coordinator.EXIT_OK
1818
+ assert initial["publish"]["completed"] is True
1819
+ before = _file_bytes(root)
1820
+
1821
+ @contextmanager
1822
+ def fail_on_release(
1823
+ project_root: Path,
1824
+ *,
1825
+ timeout: float | None = 10.0,
1826
+ poll_interval: float = 0.05,
1827
+ ):
1828
+ assert project_root == root.resolve()
1829
+ assert timeout == 10.0
1830
+ assert poll_interval == 0.05
1831
+ yield object()
1832
+ raise OSError("injected no-op lock release failure")
1833
+
1834
+ monkeypatch.setattr(contract, "project_sync_lock", fail_on_release)
1835
+
1836
+ with pytest.raises(coordinator.SyncPublishError) as caught:
1837
+ coordinator.synchronize_project(
1838
+ root,
1839
+ apply=True,
1840
+ run_timestamp="2026-07-30T01:00:00+00:00",
1841
+ )
1842
+
1843
+ publish = caught.value.result["publish"]
1844
+ assert publish["completed"] is False
1845
+ assert publish["disposition"] == "unchanged"
1846
+ assert publish["manifest_disposition"] == "unchanged"
1847
+ assert publish["scan_state_disposition"] == "unchanged"
1848
+ assert publish["manifest_commit_point"] is False
1849
+ assert publish["manifest_commit_ambiguous"] is False
1850
+ assert publish["scan_state_committed"] is False
1851
+ assert publish["scan_state_commit_ambiguous"] is False
1852
+ assert publish["partial_commit"] is False
1853
+ assert publish["published"] == []
1854
+ assert _file_bytes(root) == before
1855
+
1856
+
1857
+ def test_partial_canonical_journal_publish_blocks_until_manual_cleanup(
1858
+ tmp_path: Path,
1859
+ monkeypatch: pytest.MonkeyPatch,
1860
+ ) -> None:
1861
+ root, _ = _project(tmp_path)
1862
+ paths = coordinator._project_paths(root)
1863
+ journal_path = coordinator._publish_journal_path(paths)
1864
+
1865
+ original_rename = phase4_exit._rename_no_replace
1866
+
1867
+ def publish_partial(source: Path, target: Path) -> None:
1868
+ if Path(target) == journal_path:
1869
+ payload = Path(source).read_bytes()
1870
+ journal_path.write_bytes(payload[: max(1, len(payload) // 2)])
1871
+ return
1872
+ original_rename(source, target)
1873
+
1874
+ monkeypatch.setattr(phase4_exit, "_rename_no_replace", publish_partial)
1875
+ try:
1876
+ with pytest.raises(coordinator.SyncInputError, match="exact readback"):
1877
+ coordinator._publish_journal_exclusive(
1878
+ journal_path,
1879
+ {"transaction": "candidate"},
1880
+ )
1881
+ assert journal_path.is_file()
1882
+ assert journal_path.read_bytes()
1883
+ with pytest.raises(contract.JsonContractError):
1884
+ coordinator._load_publish_journal(paths)
1885
+ finally:
1886
+ journal_path.unlink(missing_ok=True)
1887
+ coordinator._cleanup_publish_journal_temps(journal_path)
1888
+
1889
+
1890
+ def test_journal_publish_is_no_replace_and_preserves_foreign_path(
1891
+ tmp_path: Path,
1892
+ monkeypatch: pytest.MonkeyPatch,
1893
+ ) -> None:
1894
+ root, _ = _project(tmp_path)
1895
+ paths = coordinator._project_paths(root)
1896
+ journal_path = coordinator._publish_journal_path(paths)
1897
+ foreign = b"foreign canonical journal\n"
1898
+
1899
+ original_rename = phase4_exit._rename_no_replace
1900
+
1901
+ def lose_publish_race(_source: Path, target: Path) -> None:
1902
+ if Path(target) == journal_path:
1903
+ journal_path.write_bytes(foreign)
1904
+ raise FileExistsError("injected competing journal")
1905
+ original_rename(_source, target)
1906
+
1907
+ monkeypatch.setattr(phase4_exit, "_rename_no_replace", lose_publish_race)
1908
+ try:
1909
+ with pytest.raises(coordinator.SyncInputError, match="concurrent"):
1910
+ coordinator._publish_journal_exclusive(
1911
+ journal_path,
1912
+ {"transaction": "candidate"},
1913
+ )
1914
+ assert journal_path.read_bytes() == foreign
1915
+ finally:
1916
+ journal_path.unlink(missing_ok=True)
1917
+ coordinator._cleanup_publish_journal_temps(journal_path)
1918
+
1919
+
1920
+ def test_stale_partial_journal_temp_blocks_publication_without_cleanup(
1921
+ tmp_path: Path,
1922
+ ) -> None:
1923
+ root, _ = _project(tmp_path)
1924
+ paths = coordinator._project_paths(root)
1925
+ journal_path = coordinator._publish_journal_path(paths)
1926
+ residue = journal_path.with_name(
1927
+ f"{journal_path.name}{coordinator._PUBLISH_JOURNAL_TEMP_MARKER}dead.tmp"
1928
+ )
1929
+ residue.write_bytes(b"partial journal")
1930
+
1931
+ try:
1932
+ report, exit_code = coordinator.synchronize_project(
1933
+ root,
1934
+ apply=True,
1935
+ run_timestamp=SYNCED,
1936
+ )
1937
+
1938
+ assert exit_code == coordinator.EXIT_GATE_FAILED
1939
+ assert report["status"] == "coordinator-recovery-required"
1940
+ assert report["planned_writes"] == []
1941
+ assert report["publish"]["completed"] is False
1942
+ assert residue.read_bytes() == b"partial journal"
1943
+ assert not journal_path.exists()
1944
+ finally:
1945
+ residue.unlink(missing_ok=True)
1946
+
1947
+
1948
+ def test_corrupt_canonical_journal_blocks_runs_and_recovery(
1949
+ tmp_path: Path,
1950
+ ) -> None:
1951
+ root, _ = _project(tmp_path)
1952
+ paths = coordinator._project_paths(root)
1953
+ journal_path = coordinator._publish_journal_path(paths)
1954
+ journal_path.write_bytes(b'{"schema_version":')
1955
+ try:
1956
+ blocked, blocked_code = coordinator.synchronize_project(
1957
+ root,
1958
+ run_timestamp=SYNCED,
1959
+ )
1960
+ assert blocked_code == coordinator.EXIT_GATE_FAILED
1961
+ assert blocked["status"] == "coordinator-recovery-required"
1962
+ assert "detail" in blocked["recovery"]
1963
+ with pytest.raises(contract.JsonContractError):
1964
+ coordinator.recover_project(root)
1965
+ assert journal_path.is_file()
1966
+ finally:
1967
+ journal_path.unlink(missing_ok=True)
1968
+
1969
+
1970
+ def test_recovery_rejects_foreign_artifact_and_retains_journal(
1971
+ tmp_path: Path,
1972
+ monkeypatch: pytest.MonkeyPatch,
1973
+ ) -> None:
1974
+ root, docs_root = _project(tmp_path, corrupt_marker=True)
1975
+ document = docs_root / "module.md"
1976
+ original = document.read_bytes()
1977
+
1978
+ def interrupt_after_journal(point: str) -> None:
1979
+ if point == "publish-journal-ready":
1980
+ raise KeyboardInterrupt("journal-ready")
1981
+
1982
+ monkeypatch.setattr(coordinator, "_publish_fault", interrupt_after_journal)
1983
+ with pytest.raises(KeyboardInterrupt, match="journal-ready"):
1984
+ coordinator.synchronize_project(
1985
+ root,
1986
+ apply=True,
1987
+ run_timestamp=SYNCED,
1988
+ )
1989
+
1990
+ paths = coordinator._project_paths(root)
1991
+ journal_path = coordinator._publish_journal_path(paths)
1992
+ document.write_bytes(b"foreign document content\n")
1993
+ with pytest.raises(
1994
+ coordinator.SyncInputError,
1995
+ match=r"CAS refused \[recovery-conflict\]",
1996
+ ):
1997
+ coordinator.recover_project(root)
1998
+ assert journal_path.is_file()
1999
+
2000
+ document.write_bytes(original)
2001
+ recovered, recovered_code = coordinator.recover_project(root)
2002
+ assert recovered_code == coordinator.EXIT_OK
2003
+ assert recovered["recovery"]["action"] == "rolled-back"
2004
+ assert not journal_path.exists()
2005
+
2006
+
2007
+ def test_recovery_rejects_foreign_manifest_and_retains_journal(
2008
+ tmp_path: Path,
2009
+ monkeypatch: pytest.MonkeyPatch,
2010
+ ) -> None:
2011
+ root, docs_root = _project(tmp_path)
2012
+
2013
+ def interrupt_after_journal(point: str) -> None:
2014
+ if point == "publish-journal-ready":
2015
+ raise KeyboardInterrupt("journal-ready")
2016
+
2017
+ monkeypatch.setattr(coordinator, "_publish_fault", interrupt_after_journal)
2018
+ with pytest.raises(KeyboardInterrupt, match="journal-ready"):
2019
+ coordinator.synchronize_project(
2020
+ root,
2021
+ apply=True,
2022
+ run_timestamp=SYNCED,
2023
+ )
2024
+
2025
+ paths = coordinator._project_paths(root)
2026
+ journal_path = coordinator._publish_journal_path(paths)
2027
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
2028
+ manifest_path.write_bytes(b'{"foreign":"manifest"}\n')
2029
+ with pytest.raises(
2030
+ coordinator.SyncInputError, match="neither the recorded preimage"
2031
+ ):
2032
+ coordinator.recover_project(root)
2033
+ assert journal_path.is_file()
2034
+ assert manifest_path.read_bytes() == b'{"foreign":"manifest"}\n'
2035
+
2036
+ manifest_path.unlink()
2037
+ recovered, recovered_code = coordinator.recover_project(root)
2038
+ assert recovered_code == coordinator.EXIT_OK
2039
+ assert recovered["recovery"]["action"] == "rolled-back"
2040
+ assert not journal_path.exists()
2041
+
2042
+
2043
+ def test_committed_journal_finalization_failure_requires_cleanup_recovery(
2044
+ tmp_path: Path,
2045
+ monkeypatch: pytest.MonkeyPatch,
2046
+ ) -> None:
2047
+ root, docs_root = _project(tmp_path)
2048
+ original_fault = coordinator._publish_fault
2049
+
2050
+ def fail_before_history(point: str) -> None:
2051
+ if point == "journal-finalize-before-history":
2052
+ raise OSError("injected journal history failure")
2053
+ original_fault(point)
2054
+
2055
+ monkeypatch.setattr(coordinator, "_publish_fault", fail_before_history)
2056
+ with pytest.raises(coordinator.SyncPublishError) as caught:
2057
+ coordinator.synchronize_project(
2058
+ root,
2059
+ apply=True,
2060
+ run_timestamp=SYNCED,
2061
+ )
2062
+
2063
+ publish = caught.value.result["publish"]
2064
+ assert publish["disposition"] == "installed"
2065
+ assert publish["manifest_disposition"] == "installed"
2066
+ assert publish["scan_state_disposition"] == "installed"
2067
+ assert publish["partial_commit"] is False
2068
+ assert publish["finalization_pending"] is True
2069
+ slots = contract.coordinator_publish_journal_paths(root)
2070
+ assert not slots["prepared"].exists()
2071
+ assert slots["committed"].is_file()
2072
+ assert not slots["rolled_back"].exists()
2073
+ assert contract.load_manifest(docs_root, verify_files=True)["schema_version"] == 2
2074
+
2075
+ monkeypatch.setattr(coordinator, "_publish_fault", original_fault)
2076
+ recovered, recovered_code = coordinator.recover_project(root)
2077
+ assert recovered_code == coordinator.EXIT_OK
2078
+ assert recovered["recovery"]["action"] == "finalized-committed"
2079
+ assert recovered["publish"]["disposition"] == "installed"
2080
+ assert not any(path.exists() for path in slots.values())
2081
+
2082
+
2083
+ def test_recovery_rejects_hardlinked_journal_without_cleanup(
2084
+ tmp_path: Path,
2085
+ monkeypatch: pytest.MonkeyPatch,
2086
+ ) -> None:
2087
+ root, _ = _project(tmp_path)
2088
+
2089
+ def interrupt_after_journal(point: str) -> None:
2090
+ if point == "publish-journal-ready":
2091
+ raise KeyboardInterrupt("journal-ready")
2092
+
2093
+ monkeypatch.setattr(coordinator, "_publish_fault", interrupt_after_journal)
2094
+ with pytest.raises(KeyboardInterrupt, match="journal-ready"):
2095
+ coordinator.synchronize_project(
2096
+ root,
2097
+ apply=True,
2098
+ run_timestamp=SYNCED,
2099
+ )
2100
+
2101
+ paths = coordinator._project_paths(root)
2102
+ journal_path = coordinator._publish_journal_path(paths)
2103
+ loaded = coordinator._load_publish_journal(paths)
2104
+ assert loaded is not None
2105
+ artifact_root = coordinator._publish_artifact_root(paths, loaded.journal)
2106
+ residue = journal_path.with_name(
2107
+ f"{journal_path.name}{coordinator._PUBLISH_JOURNAL_TEMP_MARKER}linked.tmp"
2108
+ )
2109
+ os.link(journal_path, residue)
2110
+ assert os.path.samefile(journal_path, residue)
2111
+
2112
+ try:
2113
+ with pytest.raises(
2114
+ coordinator.SyncInputError,
2115
+ match="must have exactly one filesystem link",
2116
+ ):
2117
+ coordinator.recover_project(root)
2118
+ assert journal_path.is_file()
2119
+ assert residue.is_file()
2120
+ assert os.path.samefile(journal_path, residue)
2121
+ finally:
2122
+ residue.unlink(missing_ok=True)
2123
+ journal_path.unlink(missing_ok=True)
2124
+ if artifact_root.exists():
2125
+ artifact_root.rmdir()
2126
+
2127
+
2128
+ def test_cli_recover_resolves_pending_coordinator_journal(
2129
+ tmp_path: Path,
2130
+ monkeypatch: pytest.MonkeyPatch,
2131
+ ) -> None:
2132
+ root, _ = _project(tmp_path)
2133
+
2134
+ def interrupt_after_journal(point: str) -> None:
2135
+ if point == "publish-journal-ready":
2136
+ raise KeyboardInterrupt("journal-ready")
2137
+
2138
+ monkeypatch.setattr(coordinator, "_publish_fault", interrupt_after_journal)
2139
+ with pytest.raises(KeyboardInterrupt, match="journal-ready"):
2140
+ coordinator.synchronize_project(
2141
+ root,
2142
+ apply=True,
2143
+ run_timestamp=SYNCED,
2144
+ )
2145
+
2146
+ completed = subprocess.run(
2147
+ [
2148
+ sys.executable,
2149
+ str(SYNC_TOOL),
2150
+ str(root),
2151
+ "--recover",
2152
+ "--json",
2153
+ ],
2154
+ cwd=root,
2155
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
2156
+ capture_output=True,
2157
+ text=True,
2158
+ encoding="utf-8",
2159
+ check=False,
2160
+ )
2161
+
2162
+ assert completed.returncode == coordinator.EXIT_OK
2163
+ assert completed.stderr == ""
2164
+ result = json.loads(completed.stdout)
2165
+ assert result["mode"] == "recover"
2166
+ assert result["recovery"]["action"] == "rolled-back"
2167
+ assert result["publish"]["disposition"] == "not-installed"
2168
+ paths = coordinator._project_paths(root)
2169
+ assert not coordinator._publish_journal_path(paths).exists()