@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,3895 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Focused safety and transaction tests for ``phase4_exit``."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import subprocess
10
+ import sys
11
+ from typing import Mapping
12
+
13
+ import pytest
14
+
15
+ import phase4_exit
16
+ import project_docs_contract as contract
17
+
18
+ SYNCED_AT = "2026-07-30T12:00:00+08:00"
19
+
20
+
21
+ def _assert_only_inactive_cleanup_residue(quarantine_root: Path) -> None:
22
+ entries = list(quarantine_root.iterdir())
23
+ unexpected = [
24
+ path
25
+ for path in entries
26
+ if path.name != ".phase4.lock"
27
+ and not (
28
+ os.name == "posix" and path.name.startswith(phase4_exit._ARCHIVE_PREFIX)
29
+ )
30
+ ]
31
+ assert unexpected == []
32
+
33
+
34
+ def _make_root(tmp_path: Path) -> tuple[Path, Path]:
35
+ root = tmp_path / "project"
36
+ docs_root = root / "project_docs"
37
+ docs_root.mkdir(parents=True)
38
+ return root, docs_root
39
+
40
+
41
+ def _write_doc(
42
+ path: Path,
43
+ title: str = "文档",
44
+ *,
45
+ exact_marker: bool = True,
46
+ overview: str | None = "目录说明。",
47
+ body: str = "",
48
+ ) -> None:
49
+ path.parent.mkdir(parents=True, exist_ok=True)
50
+ marker = (
51
+ phase4_exit.AUTO_MARKER
52
+ if exact_marker
53
+ else "<!-- AUTO-GENERATED v3.0: folder-doc -->"
54
+ )
55
+ sections = [
56
+ f"# {title}",
57
+ "",
58
+ marker,
59
+ f"<!-- Last synced: {SYNCED_AT} by proj-doc-builder v4.0 -->",
60
+ ]
61
+ if overview is not None:
62
+ sections.extend(["", "## 概述", "", overview])
63
+ if body:
64
+ sections.extend(["", body])
65
+ sections.extend(["", "## 状态", "", "✅ 完整", ""])
66
+ path.write_text("\n".join(sections), encoding="utf-8")
67
+
68
+
69
+ def _write_manifest(docs_root: Path) -> dict:
70
+ manifest = contract.build_manifest(docs_root, last_synced=SYNCED_AT)
71
+ contract.atomic_write_json(docs_root / contract.MANIFEST_FILENAME, manifest)
72
+ return manifest
73
+
74
+
75
+ def _write_supported_claude(root: Path) -> Path:
76
+ indexer = phase4_exit.claude_doc_index
77
+ lines = ["# CLAUDE.md", "manual-before"]
78
+ for section in indexer.REQUIRED_SECTIONS:
79
+ lines.extend(
80
+ [
81
+ indexer.section_start(section),
82
+ f"old-{section}",
83
+ indexer.section_end(section),
84
+ f"manual-after-{section}",
85
+ ]
86
+ )
87
+ path = root / "CLAUDE.md"
88
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
89
+ return path
90
+
91
+
92
+ def _run_json(
93
+ capsys: pytest.CaptureFixture[str],
94
+ root: Path,
95
+ *arguments: str,
96
+ ) -> tuple[int, dict]:
97
+ exit_code = phase4_exit.main([str(root), *arguments, "--json"])
98
+ captured = capsys.readouterr()
99
+ assert captured.err == ""
100
+ payload = json.loads(captured.out)
101
+ assert captured.out == contract.stable_json_dumps(payload)
102
+ assert payload["exit_code"] == exit_code
103
+ return exit_code, payload
104
+
105
+
106
+ def _eligible_project(
107
+ tmp_path: Path, name: str = "orphan.md"
108
+ ) -> tuple[Path, Path, Path]:
109
+ root, docs_root = _make_root(tmp_path)
110
+ document = docs_root / name
111
+ _write_doc(document, title="待退出目录")
112
+ _write_manifest(docs_root)
113
+ return root, docs_root, document
114
+
115
+
116
+ def _apply_one(
117
+ tmp_path: Path,
118
+ capsys: pytest.CaptureFixture[str],
119
+ ) -> tuple[Path, Path, Path, dict, Path]:
120
+ root, docs_root, document = _eligible_project(tmp_path)
121
+ exit_code, payload = _run_json(capsys, root, "--apply")
122
+ assert exit_code == phase4_exit.EXIT_OK, contract.stable_json_dumps(payload)
123
+ assert payload["ok"] is True
124
+ assert len(payload["quarantined"]) == 1
125
+ receipt_id = payload["quarantined"][0]["receipt_id"]
126
+ receipt_dir = docs_root / phase4_exit.QUARANTINE_DIRNAME / receipt_id
127
+ return root, docs_root, document, payload, receipt_dir
128
+
129
+
130
+ def test_default_report_is_non_mutating_and_json_is_pure(
131
+ tmp_path: Path,
132
+ capsys: pytest.CaptureFixture[str],
133
+ ) -> None:
134
+ root, docs_root, document = _eligible_project(tmp_path)
135
+
136
+ exit_code, payload = _run_json(capsys, root)
137
+
138
+ assert exit_code == phase4_exit.EXIT_OK, payload
139
+ assert payload["action"] == "report"
140
+ assert payload["mode"] == "report-only"
141
+ assert payload["counts"]["candidates"] == 1
142
+ assert payload["candidates"][0]["path"] == "orphan.md"
143
+ assert document.is_file()
144
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
145
+
146
+
147
+ @pytest.mark.parametrize(
148
+ "arguments",
149
+ [
150
+ ("--dry-run",),
151
+ ("--auto-approve", "A"),
152
+ ("--auto-approve", "A+B"),
153
+ ("--dry-run", "--auto-approve", "A+B"),
154
+ ],
155
+ )
156
+ def test_legacy_report_options_never_mutate(
157
+ tmp_path: Path,
158
+ capsys: pytest.CaptureFixture[str],
159
+ arguments: tuple[str, ...],
160
+ ) -> None:
161
+ root, docs_root, document = _eligible_project(tmp_path)
162
+ original = document.read_bytes()
163
+
164
+ exit_code, payload = _run_json(capsys, root, *arguments)
165
+
166
+ assert exit_code == phase4_exit.EXIT_OK, payload
167
+ assert payload["action"] == "report"
168
+ assert payload["mode"] == "report-only"
169
+ assert payload["warnings"]
170
+ assert document.read_bytes() == original
171
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
172
+
173
+
174
+ @pytest.mark.parametrize(
175
+ ("manifest_text", "expected_code"),
176
+ [
177
+ (None, "manifest-missing"),
178
+ ('{"files": [], "files": []}\n', "manifest-invalid"),
179
+ ('{"schema_version": 99}\n', "manifest-invalid"),
180
+ ],
181
+ )
182
+ def test_missing_or_malformed_manifest_fails_closed(
183
+ tmp_path: Path,
184
+ capsys: pytest.CaptureFixture[str],
185
+ manifest_text: str | None,
186
+ expected_code: str,
187
+ ) -> None:
188
+ root, docs_root = _make_root(tmp_path)
189
+ document = docs_root / "orphan.md"
190
+ _write_doc(document)
191
+ if manifest_text is not None:
192
+ (docs_root / contract.MANIFEST_FILENAME).write_text(
193
+ manifest_text,
194
+ encoding="utf-8",
195
+ )
196
+
197
+ exit_code, payload = _run_json(capsys, root, "--apply")
198
+
199
+ assert exit_code == phase4_exit.EXIT_REFUSED
200
+ assert payload["errors"][0]["code"] == expected_code
201
+ assert document.is_file()
202
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
203
+
204
+
205
+ def test_manifest_hash_mismatch_fails_closed(
206
+ tmp_path: Path,
207
+ capsys: pytest.CaptureFixture[str],
208
+ ) -> None:
209
+ root, docs_root, document = _eligible_project(tmp_path)
210
+ document.write_text(
211
+ document.read_text(encoding="utf-8") + "changed\n", encoding="utf-8"
212
+ )
213
+
214
+ exit_code, payload = _run_json(capsys, root, "--apply")
215
+
216
+ assert exit_code == phase4_exit.EXIT_REFUSED
217
+ assert payload["errors"][0]["code"] == "manifest-invalid"
218
+ assert document.is_file()
219
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
220
+
221
+
222
+ def test_unregistered_document_blocks_the_entire_apply(
223
+ tmp_path: Path,
224
+ capsys: pytest.CaptureFixture[str],
225
+ ) -> None:
226
+ root, docs_root, candidate = _eligible_project(tmp_path)
227
+ rogue = docs_root / "rogue.md"
228
+ _write_doc(rogue, title="未注册")
229
+
230
+ exit_code, payload = _run_json(capsys, root, "--apply")
231
+
232
+ assert exit_code == phase4_exit.EXIT_REFUSED
233
+ assert payload["unregistered"] == ["rogue.md"]
234
+ assert any(error["code"] == "unregistered-documents" for error in payload["errors"])
235
+ assert candidate.is_file()
236
+ assert rogue.is_file()
237
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
238
+
239
+
240
+ def test_exact_marker_is_required_and_empty_content_is_not_a_reason(
241
+ tmp_path: Path,
242
+ capsys: pytest.CaptureFixture[str],
243
+ ) -> None:
244
+ root, docs_root = _make_root(tmp_path)
245
+ markerless = docs_root / "markerless.md"
246
+ _write_doc(markerless, exact_marker=False, overview=None)
247
+ _write_manifest(docs_root)
248
+
249
+ exit_code, payload = _run_json(capsys, root, "--apply")
250
+
251
+ assert exit_code == phase4_exit.EXIT_OK, payload
252
+ assert payload["quarantined"] == []
253
+ assert payload["blocked"] == [
254
+ {
255
+ "inbound_references": 0,
256
+ "inbound_sources": [],
257
+ "path": "markerless.md",
258
+ "reason": "missing-exact-auto-marker",
259
+ "source_path": "markerless",
260
+ }
261
+ ]
262
+ assert markerless.is_file()
263
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
264
+
265
+
266
+ def test_short_or_missing_overview_does_not_override_real_safety_gates(
267
+ tmp_path: Path,
268
+ capsys: pytest.CaptureFixture[str],
269
+ ) -> None:
270
+ root, docs_root = _make_root(tmp_path)
271
+ document = docs_root / "short.md"
272
+ _write_doc(document, overview=None)
273
+ _write_manifest(docs_root)
274
+
275
+ exit_code, payload = _run_json(capsys, root, "--apply")
276
+
277
+ assert exit_code == phase4_exit.EXIT_OK, payload
278
+ assert len(payload["quarantined"]) == 1
279
+ assert not document.exists()
280
+
281
+
282
+ @pytest.mark.parametrize("boundary_filename", ["CLAUDE.md", "claude.md", "Claude.md"])
283
+ def test_boundary_descendant_is_never_a_candidate(
284
+ tmp_path: Path,
285
+ capsys: pytest.CaptureFixture[str],
286
+ boundary_filename: str,
287
+ ) -> None:
288
+ root, docs_root = _make_root(tmp_path)
289
+ source_child = root / "boundary" / "child"
290
+ source_child.mkdir(parents=True)
291
+ (root / "boundary" / boundary_filename).write_text(
292
+ "# Boundary\n",
293
+ encoding="utf-8",
294
+ )
295
+ document = docs_root / "boundary" / "child.md"
296
+ _write_doc(document)
297
+ _write_manifest(docs_root)
298
+
299
+ exit_code, payload = _run_json(capsys, root, "--apply")
300
+
301
+ assert exit_code == phase4_exit.EXIT_OK, payload
302
+ assert payload["candidates"] == []
303
+ assert payload["blocked"][0]["reason"] == "boundary-descendant"
304
+ assert payload["blocked"][0]["boundary"] == "boundary"
305
+ assert document.is_file()
306
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
307
+
308
+
309
+ @pytest.mark.parametrize(
310
+ ("target_name", "link_target"),
311
+ [
312
+ ("target.md", "../target"),
313
+ ("gone target.md", "../gone%20target?mode=1#part"),
314
+ ],
315
+ )
316
+ def test_shared_markdown_resolver_counts_structural_inbound_links(
317
+ tmp_path: Path,
318
+ capsys: pytest.CaptureFixture[str],
319
+ target_name: str,
320
+ link_target: str,
321
+ ) -> None:
322
+ root, docs_root = _make_root(tmp_path)
323
+ target = docs_root / target_name
324
+ referrer = docs_root / "refs" / "source.md"
325
+ _write_doc(target, title="目标")
326
+ _write_doc(referrer, title="引用者", body=f"[target]({link_target})")
327
+ (root / "refs" / "source").mkdir(parents=True)
328
+ _write_manifest(docs_root)
329
+
330
+ exit_code, payload = _run_json(capsys, root, "--apply")
331
+
332
+ assert exit_code == phase4_exit.EXIT_OK, payload
333
+ blocked = {item["path"]: item for item in payload["blocked"]}
334
+ assert blocked[target_name]["reason"] == "inbound-references"
335
+ assert blocked[target_name]["inbound_references"] == 1
336
+ assert blocked[target_name]["inbound_sources"] == ["refs/source.md"]
337
+ assert target.is_file()
338
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
339
+
340
+
341
+ def test_reference_style_inbound_link_blocks_quarantine(
342
+ tmp_path: Path,
343
+ capsys: pytest.CaptureFixture[str],
344
+ ) -> None:
345
+ root, docs_root = _make_root(tmp_path)
346
+ target = docs_root / "target.md"
347
+ referrer = docs_root / "refs" / "source.md"
348
+ _write_doc(target, title="目标")
349
+ _write_doc(
350
+ referrer,
351
+ title="引用者",
352
+ body="[目标][target-id]\n\n[target-id]: ../target.md",
353
+ )
354
+ (root / "refs" / "source").mkdir(parents=True)
355
+ _write_manifest(docs_root)
356
+
357
+ exit_code, payload = _run_json(capsys, root, "--apply")
358
+
359
+ assert exit_code == phase4_exit.EXIT_OK, payload
360
+ blocked = {item["path"]: item for item in payload["blocked"]}
361
+ assert blocked["target.md"]["reason"] == "inbound-references"
362
+ assert blocked["target.md"]["inbound_sources"] == ["refs/source.md"]
363
+ assert target.is_file()
364
+
365
+
366
+ def test_invalid_local_markdown_target_blocks_apply(
367
+ tmp_path: Path,
368
+ capsys: pytest.CaptureFixture[str],
369
+ ) -> None:
370
+ root, docs_root = _make_root(tmp_path)
371
+ candidate = docs_root / "candidate.md"
372
+ referrer = docs_root / "refs" / "source.md"
373
+ _write_doc(candidate)
374
+ _write_doc(referrer, body="[unsafe](../../../outside.md)")
375
+ (root / "refs" / "source").mkdir(parents=True)
376
+ _write_manifest(docs_root)
377
+
378
+ exit_code, payload = _run_json(capsys, root, "--apply")
379
+
380
+ assert exit_code == phase4_exit.EXIT_REFUSED
381
+ assert any(
382
+ error["code"] == "invalid-markdown-target" for error in payload["errors"]
383
+ )
384
+ assert candidate.is_file()
385
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
386
+
387
+
388
+ def test_quarantine_is_excluded_from_candidates_and_reference_scan(
389
+ tmp_path: Path,
390
+ capsys: pytest.CaptureFixture[str],
391
+ ) -> None:
392
+ root, docs_root, candidate = _eligible_project(tmp_path, "candidate.md")
393
+ old_payload = (
394
+ docs_root
395
+ / phase4_exit.QUARANTINE_DIRNAME
396
+ / "old-receipt"
397
+ / "document"
398
+ / "ignored.md"
399
+ )
400
+ old_payload.parent.mkdir(parents=True)
401
+ old_payload.write_bytes(b"[candidate](../../../candidate)\n\xff")
402
+
403
+ exit_code, payload = _run_json(capsys, root, "--apply")
404
+
405
+ assert exit_code == phase4_exit.EXIT_OK, payload
406
+ assert len(payload["quarantined"]) == 1
407
+ assert not candidate.exists()
408
+ assert old_payload.read_bytes().endswith(b"\xff")
409
+ assert payload["counts"]["active_documents"] == 1
410
+
411
+
412
+ def test_apply_moves_to_receipt_with_required_integrity_metadata(
413
+ tmp_path: Path,
414
+ capsys: pytest.CaptureFixture[str],
415
+ ) -> None:
416
+ root, docs_root, document = _eligible_project(tmp_path)
417
+ original = document.read_bytes()
418
+ expected_hash = contract.sha256_file(document)
419
+
420
+ exit_code, payload = _run_json(capsys, root, "--apply")
421
+
422
+ assert exit_code == phase4_exit.EXIT_OK, payload
423
+ assert not document.exists()
424
+ receipt_id = payload["quarantined"][0]["receipt_id"]
425
+ receipt_dir = docs_root / phase4_exit.QUARANTINE_DIRNAME / receipt_id
426
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
427
+ quarantined = receipt_dir / receipt["quarantined_path"]
428
+ assert quarantined.read_bytes() == original
429
+ assert receipt["original_path"] == "orphan.md"
430
+ assert receipt["sha256"] == expected_hash
431
+ assert receipt["reason"] == phase4_exit.QUARANTINE_REASON
432
+ assert receipt["generation"] == payload["generation"]
433
+ assert receipt["state"] == "quarantined"
434
+ assert receipt["restored_at"] is None
435
+ assert quarantined.is_file()
436
+ assert "os.remove" not in Path(phase4_exit.__file__).read_text(encoding="utf-8")
437
+
438
+
439
+ def test_receipt_write_failure_rolls_document_back(
440
+ tmp_path: Path,
441
+ capsys: pytest.CaptureFixture[str],
442
+ monkeypatch: pytest.MonkeyPatch,
443
+ ) -> None:
444
+ root, docs_root, document = _eligible_project(tmp_path)
445
+ original = document.read_bytes()
446
+
447
+ real_write_snapshot = phase4_exit._write_exclusive_snapshot
448
+
449
+ def fail_receipt_write(
450
+ path: Path,
451
+ base: Path,
452
+ description: str,
453
+ snapshot: dict,
454
+ *,
455
+ staging_root: Path | None = None,
456
+ staging_trusted_root: Path | None = None,
457
+ ) -> phase4_exit.ExclusiveCopy:
458
+ if description.startswith("quarantine receipt "):
459
+ raise OSError("injected receipt failure")
460
+ return real_write_snapshot(
461
+ path,
462
+ base,
463
+ description,
464
+ snapshot,
465
+ staging_root=staging_root,
466
+ staging_trusted_root=staging_trusted_root,
467
+ )
468
+
469
+ monkeypatch.setattr(phase4_exit, "_write_exclusive_snapshot", fail_receipt_write)
470
+ exit_code, payload = _run_json(capsys, root, "--apply")
471
+
472
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
473
+ assert payload["errors"][0]["code"] == "quarantine-transaction-failed"
474
+ assert document.read_bytes() == original
475
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
476
+ assert quarantine_root.is_dir()
477
+ _assert_only_inactive_cleanup_residue(quarantine_root)
478
+
479
+
480
+ def test_restore_by_receipt_succeeds_and_keeps_audit_receipt(
481
+ tmp_path: Path,
482
+ capsys: pytest.CaptureFixture[str],
483
+ ) -> None:
484
+ root, _, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
485
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
486
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
487
+ payload_path = receipt_dir / receipt["quarantined_path"]
488
+
489
+ exit_code, restore_payload = _run_json(capsys, root, "--restore", receipt_id)
490
+
491
+ assert exit_code == phase4_exit.EXIT_OK, restore_payload
492
+ assert restore_payload["restored"]["original_path"] == "orphan.md"
493
+ assert document.is_file()
494
+ assert contract.sha256_file(document) == receipt["sha256"]
495
+ receipt_after = contract.read_json_strict(
496
+ receipt_dir / phase4_exit.RECEIPT_FILENAME
497
+ )
498
+ assert receipt_after["state"] == "restored"
499
+ assert isinstance(receipt_after["restored_at"], str)
500
+ assert restore_payload["restored"]["no_op"] is False
501
+ restored_manifest = contract.load_manifest(document.parent)
502
+ assert [entry["path"] for entry in restored_manifest["files"]] == ["orphan.md"]
503
+ assert not payload_path.exists()
504
+
505
+
506
+ def test_restore_refuses_existing_destination_without_overwrite(
507
+ tmp_path: Path,
508
+ capsys: pytest.CaptureFixture[str],
509
+ ) -> None:
510
+ root, _, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
511
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
512
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
513
+ payload_path = receipt_dir / receipt["quarantined_path"]
514
+ document.write_text("conflict\n", encoding="utf-8")
515
+
516
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
517
+
518
+ assert exit_code == phase4_exit.EXIT_REFUSED
519
+ assert payload["errors"][0]["code"] == "restore-conflict"
520
+ assert document.read_text(encoding="utf-8") == "conflict\n"
521
+ assert payload_path.is_file()
522
+
523
+
524
+ def test_restore_refuses_payload_hash_mismatch(
525
+ tmp_path: Path,
526
+ capsys: pytest.CaptureFixture[str],
527
+ ) -> None:
528
+ root, _, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
529
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
530
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
531
+ payload_path = receipt_dir / receipt["quarantined_path"]
532
+ payload_path.write_text("tampered\n", encoding="utf-8")
533
+
534
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
535
+
536
+ assert exit_code == phase4_exit.EXIT_REFUSED
537
+ assert payload["errors"][0]["code"] == "receipt-hash-mismatch"
538
+ assert not document.exists()
539
+ assert payload_path.is_file()
540
+
541
+
542
+ def test_restore_refuses_non_utf8_payload(
543
+ tmp_path: Path,
544
+ capsys: pytest.CaptureFixture[str],
545
+ ) -> None:
546
+ root, _, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
547
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
548
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
549
+ payload_path = receipt_dir / receipt["quarantined_path"]
550
+ payload_path.write_bytes(b"\xff")
551
+ receipt["sha256"] = contract.sha256_file(payload_path)
552
+ contract.atomic_write_json(receipt_dir / phase4_exit.RECEIPT_FILENAME, receipt)
553
+
554
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
555
+
556
+ assert exit_code == phase4_exit.EXIT_REFUSED
557
+ assert payload["errors"][0]["code"] == "receipt-payload-invalid"
558
+ assert not document.exists()
559
+
560
+
561
+ def test_restore_refuses_non_utf8_receipt(
562
+ tmp_path: Path,
563
+ capsys: pytest.CaptureFixture[str],
564
+ ) -> None:
565
+ root, _, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
566
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
567
+ (receipt_dir / phase4_exit.RECEIPT_FILENAME).write_bytes(b"{\xff}")
568
+
569
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
570
+
571
+ assert exit_code == phase4_exit.EXIT_REFUSED
572
+ assert payload["errors"][0]["code"] == "receipt-invalid"
573
+ assert not document.exists()
574
+
575
+
576
+ def test_restore_rejects_unsafe_receipt_id_before_path_use(
577
+ tmp_path: Path,
578
+ capsys: pytest.CaptureFixture[str],
579
+ ) -> None:
580
+ root, docs_root = _make_root(tmp_path)
581
+ (docs_root / phase4_exit.QUARANTINE_DIRNAME).mkdir()
582
+
583
+ exit_code, payload = _run_json(capsys, root, "--restore", "../escape")
584
+
585
+ assert exit_code == phase4_exit.EXIT_REFUSED
586
+ assert payload["errors"][0]["code"] == "invalid-receipt-id"
587
+
588
+
589
+ def test_restore_rejects_unsafe_original_path_in_receipt(
590
+ tmp_path: Path,
591
+ capsys: pytest.CaptureFixture[str],
592
+ ) -> None:
593
+ root, _, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
594
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
595
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
596
+ receipt = contract.read_json_strict(receipt_path)
597
+ receipt["original_path"] = "../escape.md"
598
+ contract.atomic_write_json(receipt_path, receipt)
599
+
600
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
601
+
602
+ assert exit_code == phase4_exit.EXIT_REFUSED
603
+ assert payload["errors"][0]["code"] == "receipt-invalid"
604
+ assert not document.exists()
605
+
606
+
607
+ def test_active_document_symlink_escape_is_rejected(
608
+ tmp_path: Path,
609
+ capsys: pytest.CaptureFixture[str],
610
+ ) -> None:
611
+ root, docs_root, candidate = _eligible_project(tmp_path)
612
+ outside = tmp_path / "outside.md"
613
+ _write_doc(outside)
614
+ link = docs_root / "linked.md"
615
+ try:
616
+ link.symlink_to(outside)
617
+ except (NotImplementedError, OSError) as exc:
618
+ pytest.skip(f"symlink creation unavailable: {exc}")
619
+
620
+ exit_code, payload = _run_json(capsys, root, "--apply")
621
+
622
+ assert exit_code == phase4_exit.EXIT_REFUSED
623
+ assert payload["errors"][0]["code"] == "untrusted-path"
624
+ assert candidate.is_file()
625
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
626
+
627
+
628
+ def test_non_utf8_active_unregistered_document_fails_closed(
629
+ tmp_path: Path,
630
+ capsys: pytest.CaptureFixture[str],
631
+ ) -> None:
632
+ root, docs_root, candidate = _eligible_project(tmp_path)
633
+ (docs_root / "bad.md").write_bytes(b"# valid\n\xff")
634
+
635
+ exit_code, payload = _run_json(capsys, root, "--apply")
636
+
637
+ assert exit_code == phase4_exit.EXIT_REFUSED
638
+ assert payload["errors"][0]["code"] == "active-document-invalid"
639
+ assert candidate.is_file()
640
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
641
+
642
+
643
+ def test_legacy_auto_approve_cannot_be_combined_with_apply(
644
+ tmp_path: Path,
645
+ capsys: pytest.CaptureFixture[str],
646
+ ) -> None:
647
+ root, docs_root, document = _eligible_project(tmp_path)
648
+
649
+ exit_code, payload = _run_json(
650
+ capsys,
651
+ root,
652
+ "--apply",
653
+ "--auto-approve",
654
+ "A+B",
655
+ )
656
+
657
+ assert exit_code == phase4_exit.EXIT_REFUSED
658
+ assert payload["errors"][0]["code"] == "legacy-option-refused"
659
+ assert document.is_file()
660
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
661
+
662
+
663
+ def test_candidate_snapshot_uses_staged_docs_and_real_source_inventory(
664
+ tmp_path: Path,
665
+ ) -> None:
666
+ root, _ = _make_root(tmp_path)
667
+ (root / "present").mkdir()
668
+ stage_docs = root / ".proj-doc-builder-stage-test" / "project_docs"
669
+ _write_doc(stage_docs / "present.md", title="现有目录")
670
+ _write_doc(stage_docs / "orphan.md", title="退出候选")
671
+ manifest = contract.build_manifest(stage_docs, last_synced=SYNCED_AT)
672
+
673
+ analysis = phase4_exit.analyze_snapshot(root, stage_docs, manifest)
674
+ payload = phase4_exit.analysis_result(
675
+ analysis,
676
+ action="report",
677
+ mode="candidate-snapshot",
678
+ )
679
+
680
+ assert payload["ok"] is True
681
+ assert [item["path"] for item in payload["candidates"]] == ["orphan.md"]
682
+ assert payload["counts"]["active_documents"] == 2
683
+ assert payload["counts"]["manifest_documents"] == 2
684
+ assert (stage_docs / "orphan.md").is_file()
685
+
686
+
687
+ def test_candidate_snapshot_rejects_manifest_not_matching_stage(
688
+ tmp_path: Path,
689
+ ) -> None:
690
+ root, _ = _make_root(tmp_path)
691
+ stage_docs = root / ".proj-doc-builder-stage-test" / "project_docs"
692
+ _write_doc(stage_docs / "orphan.md")
693
+ manifest = contract.build_manifest(stage_docs, last_synced=SYNCED_AT)
694
+ (stage_docs / "orphan.md").write_text("changed\n", encoding="utf-8")
695
+
696
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
697
+ phase4_exit.analyze_snapshot(root, stage_docs, manifest)
698
+
699
+ assert caught.value.code == "manifest-invalid"
700
+
701
+
702
+ def test_apply_updates_v2_manifest_and_supported_claude_tree(
703
+ tmp_path: Path,
704
+ capsys: pytest.CaptureFixture[str],
705
+ ) -> None:
706
+ root, docs_root = _make_root(tmp_path)
707
+ (root / "present").mkdir()
708
+ present = docs_root / "present.md"
709
+ orphan = docs_root / "orphan.md"
710
+ _write_doc(present, title="present — 活动文档")
711
+ _write_doc(orphan, title="orphan — 退出文档")
712
+ _write_manifest(docs_root)
713
+ claude_path = _write_supported_claude(root)
714
+
715
+ exit_code, payload = _run_json(capsys, root, "--apply")
716
+
717
+ assert exit_code == phase4_exit.EXIT_OK, payload
718
+ assert not orphan.exists()
719
+ assert present.is_file()
720
+ manifest = contract.load_manifest(docs_root)
721
+ assert manifest["schema_version"] == contract.MANIFEST_SCHEMA_VERSION
722
+ assert manifest["generation_id"] == payload["manifest_generation"]
723
+ assert manifest["total"] == 1
724
+ assert [entry["path"] for entry in manifest["files"]] == ["present.md"]
725
+ claude_content = claude_path.read_text(encoding="utf-8")
726
+ assert "old-doc-tree-instruction" not in claude_content
727
+ assert "old-project-overview" in claude_content
728
+ assert "present — 活动文档 ✅" in claude_content
729
+ assert "orphan — 退出文档" not in claude_content
730
+
731
+
732
+ def test_all_candidates_are_prevalidated_before_first_move(
733
+ tmp_path: Path,
734
+ capsys: pytest.CaptureFixture[str],
735
+ monkeypatch: pytest.MonkeyPatch,
736
+ ) -> None:
737
+ root, docs_root = _make_root(tmp_path)
738
+ first = docs_root / "a.md"
739
+ second = docs_root / "b.md"
740
+ _write_doc(first, title="A")
741
+ _write_doc(second, title="B")
742
+ _write_manifest(docs_root)
743
+ real_revalidate = phase4_exit._revalidate_candidate
744
+ visited: list[str] = []
745
+
746
+ def fail_second(
747
+ analysis: phase4_exit.Analysis,
748
+ candidate: dict,
749
+ expected_active: set[str],
750
+ ) -> Path:
751
+ visited.append(candidate["path"])
752
+ if len(visited) == 2:
753
+ raise phase4_exit.Phase4Refusal(
754
+ "injected-prevalidation-failure",
755
+ "second candidate failed before the batch started",
756
+ )
757
+ return real_revalidate(analysis, candidate, expected_active)
758
+
759
+ monkeypatch.setattr(phase4_exit, "_revalidate_candidate", fail_second)
760
+ exit_code, payload = _run_json(capsys, root, "--apply")
761
+
762
+ assert exit_code == phase4_exit.EXIT_REFUSED
763
+ assert payload["errors"][-1]["code"] == "injected-prevalidation-failure"
764
+ assert visited == ["a.md", "b.md"]
765
+ assert first.is_file() and second.is_file()
766
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
767
+ assert contract.load_manifest(docs_root)["total"] == 2
768
+
769
+
770
+ def test_multi_candidate_receipt_failure_rolls_back_entire_batch(
771
+ tmp_path: Path,
772
+ capsys: pytest.CaptureFixture[str],
773
+ monkeypatch: pytest.MonkeyPatch,
774
+ ) -> None:
775
+ root, docs_root = _make_root(tmp_path)
776
+ documents = [docs_root / "a.md", docs_root / "b.md"]
777
+ for document in documents:
778
+ _write_doc(document, title=document.stem)
779
+ manifest_before = docs_root / contract.MANIFEST_FILENAME
780
+ _write_manifest(docs_root)
781
+ manifest_bytes = manifest_before.read_bytes()
782
+ real_write_snapshot = phase4_exit._write_exclusive_snapshot
783
+ receipt_writes = 0
784
+
785
+ def fail_second_receipt(
786
+ path: Path,
787
+ base: Path,
788
+ description: str,
789
+ snapshot: dict,
790
+ *,
791
+ staging_root: Path | None = None,
792
+ staging_trusted_root: Path | None = None,
793
+ ) -> phase4_exit.ExclusiveCopy:
794
+ nonlocal receipt_writes
795
+ if description.startswith("quarantine receipt "):
796
+ receipt_writes += 1
797
+ if receipt_writes == 2:
798
+ raise OSError("injected second receipt failure")
799
+ return real_write_snapshot(
800
+ path,
801
+ base,
802
+ description,
803
+ snapshot,
804
+ staging_root=staging_root,
805
+ staging_trusted_root=staging_trusted_root,
806
+ )
807
+
808
+ monkeypatch.setattr(
809
+ phase4_exit,
810
+ "_write_exclusive_snapshot",
811
+ fail_second_receipt,
812
+ )
813
+ exit_code, payload = _run_json(capsys, root, "--apply")
814
+
815
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
816
+ assert payload["errors"][-1]["code"] == "quarantine-transaction-failed"
817
+ assert payload["quarantined"] == []
818
+ assert all(document.is_file() for document in documents)
819
+ assert manifest_before.read_bytes() == manifest_bytes
820
+ assert contract.load_manifest(docs_root)["total"] == 2
821
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
822
+ assert quarantine_root.is_dir()
823
+ _assert_only_inactive_cleanup_residue(quarantine_root)
824
+
825
+
826
+ def test_manifest_commit_failure_restores_documents_receipts_and_claude(
827
+ tmp_path: Path,
828
+ capsys: pytest.CaptureFixture[str],
829
+ monkeypatch: pytest.MonkeyPatch,
830
+ ) -> None:
831
+ root, docs_root = _make_root(tmp_path)
832
+ (root / "present").mkdir()
833
+ present = docs_root / "present.md"
834
+ orphan = docs_root / "orphan.md"
835
+ _write_doc(present, title="present")
836
+ _write_doc(orphan, title="orphan")
837
+ _write_manifest(docs_root)
838
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
839
+ manifest_before = manifest_path.read_bytes()
840
+ claude_path = _write_supported_claude(root)
841
+ claude_before = claude_path.read_bytes()
842
+ _fail_at(
843
+ monkeypatch,
844
+ "manifest-candidate-staged",
845
+ OSError("injected manifest commit failure"),
846
+ )
847
+
848
+ exit_code, payload = _run_json(capsys, root, "--apply")
849
+
850
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
851
+ assert payload["errors"][-1]["code"] == "quarantine-transaction-failed"
852
+ assert orphan.is_file() and present.is_file()
853
+ assert manifest_path.read_bytes() == manifest_before
854
+ assert claude_path.read_bytes() == claude_before
855
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
856
+ assert quarantine_root.is_dir()
857
+ _assert_only_inactive_cleanup_residue(quarantine_root)
858
+
859
+
860
+ def test_apply_reloads_snapshot_only_after_project_lock_is_entered(
861
+ tmp_path: Path,
862
+ capsys: pytest.CaptureFixture[str],
863
+ monkeypatch: pytest.MonkeyPatch,
864
+ ) -> None:
865
+ root, docs_root, document = _eligible_project(tmp_path)
866
+ real_project_lock = phase4_exit.contract.project_sync_lock
867
+ entered: list[Path] = []
868
+
869
+ class MutatingLock:
870
+ def __init__(self, inner: object) -> None:
871
+ self.inner = inner
872
+
873
+ def __enter__(self) -> object:
874
+ lock = getattr(self.inner, "__enter__")()
875
+ entered.append(root.resolve())
876
+ (root / "orphan").mkdir()
877
+ return lock
878
+
879
+ def __exit__(self, *args: object) -> object:
880
+ return getattr(self.inner, "__exit__")(*args)
881
+
882
+ def wrapped_lock(project_root: Path, **kwargs: object) -> MutatingLock:
883
+ assert Path(project_root).resolve() == root.resolve()
884
+ return MutatingLock(real_project_lock(project_root, **kwargs))
885
+
886
+ monkeypatch.setattr(phase4_exit.contract, "project_sync_lock", wrapped_lock)
887
+ exit_code, payload = _run_json(capsys, root, "--apply")
888
+
889
+ assert exit_code == phase4_exit.EXIT_OK, payload
890
+ assert entered == [root.resolve()]
891
+ assert payload["quarantined"] == []
892
+ assert document.is_file()
893
+ assert not (docs_root / phase4_exit.QUARANTINE_DIRNAME).exists()
894
+
895
+
896
+ def test_apply_and_restore_share_the_canonical_project_lock_domain(
897
+ tmp_path: Path,
898
+ capsys: pytest.CaptureFixture[str],
899
+ monkeypatch: pytest.MonkeyPatch,
900
+ ) -> None:
901
+ root, _, _ = _eligible_project(tmp_path)
902
+ real_project_lock = phase4_exit.contract.project_sync_lock
903
+ calls: list[Path] = []
904
+
905
+ def tracking_lock(project_root: Path, **kwargs: object) -> object:
906
+ calls.append(Path(project_root).resolve())
907
+ return real_project_lock(project_root, **kwargs)
908
+
909
+ monkeypatch.setattr(phase4_exit.contract, "project_sync_lock", tracking_lock)
910
+ apply_code, apply_payload = _run_json(capsys, root, "--apply")
911
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
912
+ restore_code, restore_payload = _run_json(
913
+ capsys,
914
+ root,
915
+ "--restore",
916
+ receipt_id,
917
+ )
918
+
919
+ assert apply_code == phase4_exit.EXIT_OK, apply_payload
920
+ assert restore_code == phase4_exit.EXIT_OK, restore_payload
921
+ assert calls == [root.resolve(), root.resolve()]
922
+
923
+
924
+ def test_restore_concurrent_target_creation_is_atomic_no_replace(
925
+ tmp_path: Path,
926
+ capsys: pytest.CaptureFixture[str],
927
+ monkeypatch: pytest.MonkeyPatch,
928
+ ) -> None:
929
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(
930
+ tmp_path,
931
+ capsys,
932
+ )
933
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
934
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
935
+ receipt_before = contract.read_json_strict(receipt_path)
936
+ payload_path = receipt_dir / receipt_before["quarantined_path"]
937
+ real_exclusive_copy = phase4_exit._exclusive_copy_file
938
+
939
+ def create_racing_target(
940
+ source: Path,
941
+ destination: Path,
942
+ expected_digest: str,
943
+ expected_identity: tuple[int, int, int, int],
944
+ *,
945
+ archive_root: Path,
946
+ archive_trusted_root: Path,
947
+ cleanup_on_failure: bool = True,
948
+ ) -> phase4_exit.ExclusiveCopy:
949
+ destination.write_text("concurrent creator\n", encoding="utf-8")
950
+ return real_exclusive_copy(
951
+ source,
952
+ destination,
953
+ expected_digest,
954
+ expected_identity,
955
+ archive_root=archive_root,
956
+ archive_trusted_root=archive_trusted_root,
957
+ cleanup_on_failure=cleanup_on_failure,
958
+ )
959
+
960
+ monkeypatch.setattr(
961
+ phase4_exit,
962
+ "_exclusive_copy_file",
963
+ create_racing_target,
964
+ )
965
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
966
+
967
+ assert exit_code == phase4_exit.EXIT_REFUSED
968
+ assert payload["errors"][-1]["code"] == "restore-conflict"
969
+ assert document.read_text(encoding="utf-8") == "concurrent creator\n"
970
+ assert payload_path.is_file()
971
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
972
+ manifest = contract.read_json_strict(docs_root / contract.MANIFEST_FILENAME)
973
+ assert manifest["total"] == 0
974
+
975
+
976
+ def test_restore_manifest_failure_rolls_back_target_and_receipt_state(
977
+ tmp_path: Path,
978
+ capsys: pytest.CaptureFixture[str],
979
+ monkeypatch: pytest.MonkeyPatch,
980
+ ) -> None:
981
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(
982
+ tmp_path,
983
+ capsys,
984
+ )
985
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
986
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
987
+ receipt_before = receipt_path.read_bytes()
988
+ receipt = contract.read_json_strict(receipt_path)
989
+ payload_path = receipt_dir / receipt["quarantined_path"]
990
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
991
+ manifest_before = manifest_path.read_bytes()
992
+ _fail_at(
993
+ monkeypatch,
994
+ "manifest-candidate-staged",
995
+ OSError("injected restore manifest failure"),
996
+ )
997
+
998
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
999
+
1000
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
1001
+ assert payload["errors"][-1]["code"] == "restore-transaction-failed"
1002
+ assert not document.exists()
1003
+ assert payload_path.is_file()
1004
+ assert receipt_path.read_bytes() == receipt_before
1005
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
1006
+ assert manifest_path.read_bytes() == manifest_before
1007
+
1008
+
1009
+ def test_restore_is_idempotent_after_atomic_receipt_transition(
1010
+ tmp_path: Path,
1011
+ capsys: pytest.CaptureFixture[str],
1012
+ ) -> None:
1013
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(
1014
+ tmp_path,
1015
+ capsys,
1016
+ )
1017
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1018
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
1019
+
1020
+ first_code, first_payload = _run_json(capsys, root, "--restore", receipt_id)
1021
+ receipt_after_first = contract.read_json_strict(receipt_path)
1022
+ receipt_bytes = receipt_path.read_bytes()
1023
+ second_code, second_payload = _run_json(capsys, root, "--restore", receipt_id)
1024
+
1025
+ assert first_code == phase4_exit.EXIT_OK
1026
+ assert first_payload["restored"]["no_op"] is False
1027
+ assert receipt_after_first["state"] == "restored"
1028
+ assert isinstance(receipt_after_first["restored_at"], str)
1029
+ assert second_code == phase4_exit.EXIT_OK
1030
+ assert second_payload["restored"]["no_op"] is True
1031
+ assert second_payload["counts"] == {"no_op": 1, "restored": 0}
1032
+ assert receipt_path.read_bytes() == receipt_bytes
1033
+ assert document.is_file()
1034
+ assert contract.sha256_file(document) == receipt_after_first["sha256"]
1035
+ manifest = contract.load_manifest(docs_root)
1036
+ assert [entry["path"] for entry in manifest["files"]] == ["orphan.md"]
1037
+
1038
+
1039
+ class _SimulatedCrash(BaseException):
1040
+ """Test-only abrupt-stop stand-in; no process is actually terminated."""
1041
+
1042
+
1043
+ def _crash_at(monkeypatch: pytest.MonkeyPatch, point_name: str) -> None:
1044
+ def crash(point: str) -> None:
1045
+ if point == point_name:
1046
+ raise _SimulatedCrash(point)
1047
+
1048
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", crash)
1049
+
1050
+
1051
+ def _fail_at(
1052
+ monkeypatch: pytest.MonkeyPatch,
1053
+ point_name: str,
1054
+ error: Exception,
1055
+ ) -> None:
1056
+ def fail(point: str) -> None:
1057
+ if point == point_name:
1058
+ raise error
1059
+
1060
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", fail)
1061
+
1062
+
1063
+ def _transaction_journals(docs_root: Path) -> list[Path]:
1064
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
1065
+ if not quarantine_root.exists():
1066
+ return []
1067
+ candidates = list(quarantine_root.glob(f"{phase4_exit._TRANSACTION_PREFIX}*.json"))
1068
+ canonical = quarantine_root / phase4_exit._TRANSACTION_CANONICAL_FILENAME
1069
+ if canonical.exists():
1070
+ candidates.append(canonical)
1071
+ return sorted(candidates)
1072
+
1073
+
1074
+ def test_recover_quarantine_before_manifest_rolls_back_batch(
1075
+ tmp_path: Path,
1076
+ capsys: pytest.CaptureFixture[str],
1077
+ monkeypatch: pytest.MonkeyPatch,
1078
+ ) -> None:
1079
+ root, docs_root, document = _eligible_project(tmp_path)
1080
+ original = document.read_bytes()
1081
+ _crash_at(monkeypatch, "quarantine-journal-ready")
1082
+
1083
+ with pytest.raises(_SimulatedCrash):
1084
+ phase4_exit.apply_quarantine(root)
1085
+
1086
+ assert not document.exists()
1087
+ assert len(_transaction_journals(docs_root)) == 2
1088
+ exit_code, payload = _run_json(capsys, root, "--recover")
1089
+
1090
+ assert exit_code == phase4_exit.EXIT_OK, payload
1091
+ assert payload["status"] == "recovered"
1092
+ assert payload["recovery"]["outcome"] == "quarantine-rolled-back"
1093
+ assert document.read_bytes() == original
1094
+ assert contract.load_manifest(docs_root)["total"] == 1
1095
+ assert _transaction_journals(docs_root) == []
1096
+
1097
+ repeat_code, repeat_payload = _run_json(capsys, root, "--recover")
1098
+ assert repeat_code == phase4_exit.EXIT_OK, repeat_payload
1099
+ assert repeat_payload["status"] == "no-pending-transaction"
1100
+
1101
+
1102
+ def test_recover_quarantine_metadata_gap_restores_claude_preimage(
1103
+ tmp_path: Path,
1104
+ capsys: pytest.CaptureFixture[str],
1105
+ monkeypatch: pytest.MonkeyPatch,
1106
+ ) -> None:
1107
+ root, docs_root, document = _eligible_project(tmp_path)
1108
+ claude_path = _write_supported_claude(root)
1109
+ claude_before = claude_path.read_bytes()
1110
+ _crash_at(monkeypatch, "metadata-preimage-detached")
1111
+
1112
+ with pytest.raises(_SimulatedCrash):
1113
+ phase4_exit.apply_quarantine(root)
1114
+
1115
+ assert not claude_path.exists()
1116
+ assert not document.exists()
1117
+ assert len(_transaction_journals(docs_root)) == 2
1118
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1119
+
1120
+ exit_code, payload = _run_json(capsys, root, "--recover")
1121
+
1122
+ assert exit_code == phase4_exit.EXIT_OK, payload
1123
+ assert payload["recovery"]["outcome"] == "quarantine-rolled-back"
1124
+ assert claude_path.read_bytes() == claude_before
1125
+ assert document.is_file()
1126
+ assert contract.load_manifest(docs_root)["total"] == 1
1127
+ assert _transaction_journals(docs_root) == []
1128
+
1129
+
1130
+ def test_recover_quarantine_after_manifest_finishes_cleanup(
1131
+ tmp_path: Path,
1132
+ capsys: pytest.CaptureFixture[str],
1133
+ monkeypatch: pytest.MonkeyPatch,
1134
+ ) -> None:
1135
+ root, docs_root, document = _eligible_project(tmp_path)
1136
+ _crash_at(monkeypatch, "quarantine-manifest-committed")
1137
+
1138
+ with pytest.raises(_SimulatedCrash):
1139
+ phase4_exit.apply_quarantine(root)
1140
+
1141
+ assert not document.exists()
1142
+ journal = _transaction_journals(docs_root)
1143
+ assert len(journal) == 2
1144
+ exit_code, payload = _run_json(capsys, root, "--recover")
1145
+
1146
+ assert exit_code == phase4_exit.EXIT_OK, payload
1147
+ assert payload["recovery"]["outcome"] == "quarantine-finalized"
1148
+ assert contract.load_manifest(docs_root)["total"] == 0
1149
+ assert _transaction_journals(docs_root) == []
1150
+
1151
+
1152
+ def test_recover_restore_copy_before_metadata_rolls_forward(
1153
+ tmp_path: Path,
1154
+ capsys: pytest.CaptureFixture[str],
1155
+ monkeypatch: pytest.MonkeyPatch,
1156
+ ) -> None:
1157
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1158
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1159
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
1160
+ payload_path = receipt_dir / receipt["quarantined_path"]
1161
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1162
+ _crash_at(monkeypatch, "restore-copy-complete")
1163
+
1164
+ with pytest.raises(_SimulatedCrash):
1165
+ phase4_exit.restore_receipt(root, receipt_id)
1166
+
1167
+ assert document.is_file()
1168
+ assert contract.sha256_file(document) == receipt["sha256"]
1169
+ assert not anchor_path.exists()
1170
+ assert phase4_exit._identity_from_stat(document.lstat()) != (
1171
+ phase4_exit._identity_from_stat(payload_path.lstat())
1172
+ )
1173
+ assert [path.name for path in _transaction_journals(docs_root)] == [
1174
+ phase4_exit._TRANSACTION_TARGET_FILENAME,
1175
+ phase4_exit._TRANSACTION_CANONICAL_FILENAME,
1176
+ ]
1177
+ exit_code, payload = _run_json(capsys, root, "--recover")
1178
+
1179
+ assert exit_code == phase4_exit.EXIT_OK, payload
1180
+ assert payload["recovery"]["outcome"] == "restore-finalized"
1181
+ assert contract.load_manifest(docs_root)["total"] == 1
1182
+ receipt_after = contract.read_json_strict(
1183
+ receipt_dir / phase4_exit.RECEIPT_FILENAME
1184
+ )
1185
+ assert receipt_after["state"] == "restored"
1186
+ assert not (receipt_dir / receipt["quarantined_path"]).exists()
1187
+ assert _transaction_journals(docs_root) == []
1188
+
1189
+
1190
+ def test_recover_prepared_restore_without_staged_target_cancels(
1191
+ tmp_path: Path,
1192
+ capsys: pytest.CaptureFixture[str],
1193
+ monkeypatch: pytest.MonkeyPatch,
1194
+ ) -> None:
1195
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1196
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1197
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
1198
+ receipt = contract.read_json_strict(receipt_path)
1199
+ payload_path = receipt_dir / receipt["quarantined_path"]
1200
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1201
+ _crash_at(monkeypatch, "restore-journal-created")
1202
+
1203
+ with pytest.raises(_SimulatedCrash):
1204
+ phase4_exit.restore_receipt(root, receipt_id)
1205
+
1206
+ assert not document.exists()
1207
+ assert not anchor_path.exists()
1208
+ assert payload_path.is_file()
1209
+ assert [path.name for path in _transaction_journals(docs_root)] == [
1210
+ phase4_exit._TRANSACTION_CANONICAL_FILENAME
1211
+ ]
1212
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1213
+ exit_code, payload = _run_json(capsys, root, "--recover")
1214
+
1215
+ assert exit_code == phase4_exit.EXIT_OK, payload
1216
+ assert payload["recovery"]["outcome"] == "restore-cancelled"
1217
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
1218
+ assert payload_path.is_file()
1219
+ assert not document.exists()
1220
+ assert contract.load_manifest(docs_root)["total"] == 0
1221
+ assert _transaction_journals(docs_root) == []
1222
+
1223
+
1224
+ def test_recover_prepared_restore_with_unrecorded_staged_target_refuses(
1225
+ tmp_path: Path,
1226
+ capsys: pytest.CaptureFixture[str],
1227
+ monkeypatch: pytest.MonkeyPatch,
1228
+ ) -> None:
1229
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1230
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1231
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
1232
+ payload_path = receipt_dir / receipt["quarantined_path"]
1233
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1234
+ _crash_at(monkeypatch, "restore-staged-target-created")
1235
+
1236
+ with pytest.raises(_SimulatedCrash):
1237
+ phase4_exit.restore_receipt(root, receipt_id)
1238
+
1239
+ staged_identity = phase4_exit._identity_from_stat(anchor_path.lstat())
1240
+ assert staged_identity != phase4_exit._identity_from_stat(payload_path.lstat())
1241
+ journals_before = _transaction_journals(docs_root)
1242
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1243
+ exit_code, payload = _run_json(capsys, root, "--recover")
1244
+
1245
+ assert exit_code == phase4_exit.EXIT_REFUSED
1246
+ assert payload["errors"][0]["code"] == "recovery-unowned-staged-target"
1247
+ assert not document.exists()
1248
+ assert phase4_exit._identity_from_stat(anchor_path.lstat()) == staged_identity
1249
+ assert payload_path.is_file()
1250
+ assert _transaction_journals(docs_root) == journals_before
1251
+
1252
+
1253
+ def test_recover_target_created_restore_publishes_persisted_staged_inode(
1254
+ tmp_path: Path,
1255
+ capsys: pytest.CaptureFixture[str],
1256
+ monkeypatch: pytest.MonkeyPatch,
1257
+ ) -> None:
1258
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1259
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1260
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
1261
+ payload_path = receipt_dir / receipt["quarantined_path"]
1262
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1263
+ _crash_at(monkeypatch, "restore-target-journal-created")
1264
+
1265
+ with pytest.raises(_SimulatedCrash):
1266
+ phase4_exit.restore_receipt(root, receipt_id)
1267
+
1268
+ staged_identity = phase4_exit._identity_from_stat(anchor_path.lstat())
1269
+ target_journal_path = receipt_dir.parent / phase4_exit._TRANSACTION_TARGET_FILENAME
1270
+ target_journal = contract.read_json_strict(target_journal_path)
1271
+ assert tuple(target_journal["restore"]["target_identity"]) == staged_identity
1272
+ assert staged_identity != phase4_exit._identity_from_stat(payload_path.lstat())
1273
+ assert not document.exists()
1274
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1275
+ exit_code, payload = _run_json(capsys, root, "--recover")
1276
+
1277
+ assert exit_code == phase4_exit.EXIT_OK, payload
1278
+ assert payload["recovery"]["outcome"] == "restore-finalized"
1279
+ assert not anchor_path.exists()
1280
+ assert phase4_exit._identity_from_stat(document.lstat()) == staged_identity
1281
+ assert not payload_path.exists()
1282
+ assert _transaction_journals(docs_root) == []
1283
+
1284
+
1285
+ @pytest.mark.parametrize("failure_point", ["verification", "fsync"])
1286
+ def test_recover_restore_rename_failure_retains_identity_for_retry(
1287
+ tmp_path: Path,
1288
+ capsys: pytest.CaptureFixture[str],
1289
+ monkeypatch: pytest.MonkeyPatch,
1290
+ failure_point: str,
1291
+ ) -> None:
1292
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1293
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1294
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
1295
+ payload_path = receipt_dir / receipt["quarantined_path"]
1296
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1297
+ target_journal_path = receipt_dir.parent / phase4_exit._TRANSACTION_TARGET_FILENAME
1298
+ _crash_at(monkeypatch, "restore-target-journal-created")
1299
+
1300
+ with pytest.raises(_SimulatedCrash):
1301
+ phase4_exit.restore_receipt(root, receipt_id)
1302
+
1303
+ expected_identity = tuple(
1304
+ contract.read_json_strict(target_journal_path)["restore"]["target_identity"]
1305
+ )
1306
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1307
+ if failure_point == "verification":
1308
+ real_capture = phase4_exit._capture_snapshot_with_identity
1309
+
1310
+ def fail_destination_capture(
1311
+ path: Path,
1312
+ base: Path,
1313
+ description: str,
1314
+ ) -> tuple[dict[str, object], tuple[int, int, int, int] | None]:
1315
+ if description == "exclusive restore destination":
1316
+ raise OSError("injected destination verification failure")
1317
+ return real_capture(path, base, description)
1318
+
1319
+ monkeypatch.setattr(
1320
+ phase4_exit,
1321
+ "_capture_snapshot_with_identity",
1322
+ fail_destination_capture,
1323
+ )
1324
+ else:
1325
+ real_fsync = phase4_exit._fsync_directory
1326
+
1327
+ def fail_destination_fsync(directory: Path) -> None:
1328
+ if Path(directory) == document.parent and document.exists():
1329
+ raise OSError("injected destination fsync failure")
1330
+ real_fsync(directory)
1331
+
1332
+ monkeypatch.setattr(phase4_exit, "_fsync_directory", fail_destination_fsync)
1333
+
1334
+ exit_code, payload = _run_json(capsys, root, "--recover")
1335
+
1336
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
1337
+ assert payload["errors"][0]["code"] == "recovery-write-failed"
1338
+ assert not anchor_path.exists()
1339
+ assert document.is_file()
1340
+ assert phase4_exit._identity_from_stat(document.lstat()) == expected_identity
1341
+ assert payload_path.is_file()
1342
+ assert len(_transaction_journals(docs_root)) == 2
1343
+
1344
+ if failure_point == "verification":
1345
+ monkeypatch.setattr(
1346
+ phase4_exit,
1347
+ "_capture_snapshot_with_identity",
1348
+ real_capture,
1349
+ )
1350
+ else:
1351
+ monkeypatch.setattr(phase4_exit, "_fsync_directory", real_fsync)
1352
+ retry_code, retried = _run_json(capsys, root, "--recover")
1353
+
1354
+ assert retry_code == phase4_exit.EXIT_OK, retried
1355
+ assert retried["recovery"]["outcome"] == "restore-finalized"
1356
+ assert phase4_exit._identity_from_stat(document.lstat()) == expected_identity
1357
+ assert not payload_path.exists()
1358
+ assert _transaction_journals(docs_root) == []
1359
+
1360
+
1361
+ @pytest.mark.parametrize("path_state", ["both", "neither"])
1362
+ def test_recover_target_created_restore_rejects_ambiguous_path_state(
1363
+ tmp_path: Path,
1364
+ capsys: pytest.CaptureFixture[str],
1365
+ monkeypatch: pytest.MonkeyPatch,
1366
+ path_state: str,
1367
+ ) -> None:
1368
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1369
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1370
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1371
+ _crash_at(monkeypatch, "restore-target-journal-created")
1372
+
1373
+ with pytest.raises(_SimulatedCrash):
1374
+ phase4_exit.restore_receipt(root, receipt_id)
1375
+
1376
+ if path_state == "both":
1377
+ document.write_bytes(anchor_path.read_bytes())
1378
+ else:
1379
+ anchor_path.unlink()
1380
+ journals_before = _transaction_journals(docs_root)
1381
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1382
+ exit_code, payload = _run_json(capsys, root, "--recover")
1383
+
1384
+ assert exit_code == phase4_exit.EXIT_REFUSED
1385
+ assert payload["errors"][0]["code"] == "recovery-conflict"
1386
+ assert document.exists() is (path_state == "both")
1387
+ assert anchor_path.exists() is (path_state == "both")
1388
+ assert _transaction_journals(docs_root) == journals_before
1389
+
1390
+
1391
+ def test_recover_ready_restore_requires_active_target_and_absent_staging_name(
1392
+ tmp_path: Path,
1393
+ capsys: pytest.CaptureFixture[str],
1394
+ monkeypatch: pytest.MonkeyPatch,
1395
+ ) -> None:
1396
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1397
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1398
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
1399
+ payload_path = receipt_dir / receipt["quarantined_path"]
1400
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
1401
+ _crash_at(monkeypatch, "restore-journal-ready")
1402
+
1403
+ with pytest.raises(_SimulatedCrash):
1404
+ phase4_exit.restore_receipt(root, receipt_id)
1405
+
1406
+ assert document.is_file()
1407
+ assert not anchor_path.exists()
1408
+ target_identity = phase4_exit._identity_from_stat(document.lstat())
1409
+ assert target_identity != phase4_exit._identity_from_stat(payload_path.lstat())
1410
+ assert {path.name for path in _transaction_journals(docs_root)} == {
1411
+ phase4_exit._TRANSACTION_CANONICAL_FILENAME,
1412
+ phase4_exit._TRANSACTION_TARGET_FILENAME,
1413
+ phase4_exit._TRANSACTION_READY_FILENAME,
1414
+ }
1415
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1416
+ exit_code, payload = _run_json(capsys, root, "--recover")
1417
+
1418
+ assert exit_code == phase4_exit.EXIT_OK, payload
1419
+ assert payload["recovery"]["outcome"] == "restore-finalized"
1420
+ assert phase4_exit._identity_from_stat(document.lstat()) == target_identity
1421
+ assert not payload_path.exists()
1422
+ assert _transaction_journals(docs_root) == []
1423
+
1424
+
1425
+ def test_recover_restore_metadata_gap_republishes_receipt_postimage(
1426
+ tmp_path: Path,
1427
+ capsys: pytest.CaptureFixture[str],
1428
+ monkeypatch: pytest.MonkeyPatch,
1429
+ ) -> None:
1430
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1431
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1432
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
1433
+ _crash_at(monkeypatch, "metadata-preimage-detached")
1434
+
1435
+ with pytest.raises(_SimulatedCrash):
1436
+ phase4_exit.restore_receipt(root, receipt_id)
1437
+
1438
+ assert document.is_file()
1439
+ assert not receipt_path.exists()
1440
+ assert len(_transaction_journals(docs_root)) == 3
1441
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1442
+
1443
+ exit_code, payload = _run_json(capsys, root, "--recover")
1444
+
1445
+ assert exit_code == phase4_exit.EXIT_OK, payload
1446
+ assert payload["recovery"]["outcome"] == "restore-finalized"
1447
+ assert contract.read_json_strict(receipt_path)["state"] == "restored"
1448
+ assert contract.load_manifest(docs_root)["total"] == 1
1449
+ assert _transaction_journals(docs_root) == []
1450
+
1451
+
1452
+ def test_recover_refuses_manifest_conflict_without_touching_journal(
1453
+ tmp_path: Path,
1454
+ capsys: pytest.CaptureFixture[str],
1455
+ monkeypatch: pytest.MonkeyPatch,
1456
+ ) -> None:
1457
+ root, docs_root, document = _eligible_project(tmp_path)
1458
+ _crash_at(monkeypatch, "quarantine-journal-ready")
1459
+
1460
+ with pytest.raises(_SimulatedCrash):
1461
+ phase4_exit.apply_quarantine(root)
1462
+
1463
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
1464
+ manifest_path.write_text('{"manual": true}\n', encoding="utf-8")
1465
+ journal_before = _transaction_journals(docs_root)
1466
+ exit_code, payload = _run_json(capsys, root, "--recover")
1467
+
1468
+ assert exit_code == phase4_exit.EXIT_REFUSED
1469
+ assert payload["errors"][0]["code"] == "recovery-conflict"
1470
+ assert not document.exists()
1471
+ assert _transaction_journals(docs_root) == journal_before
1472
+
1473
+
1474
+ def test_recover_refuses_tampered_restore_target_without_overwrite(
1475
+ tmp_path: Path,
1476
+ capsys: pytest.CaptureFixture[str],
1477
+ monkeypatch: pytest.MonkeyPatch,
1478
+ ) -> None:
1479
+ root, docs_root, document, apply_payload, _ = _apply_one(tmp_path, capsys)
1480
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1481
+ _crash_at(monkeypatch, "restore-copy-complete")
1482
+
1483
+ with pytest.raises(_SimulatedCrash):
1484
+ phase4_exit.restore_receipt(root, receipt_id)
1485
+
1486
+ document.write_text("manual recovery conflict\n", encoding="utf-8")
1487
+ journals_before = _transaction_journals(docs_root)
1488
+ exit_code, payload = _run_json(capsys, root, "--recover")
1489
+
1490
+ assert exit_code == phase4_exit.EXIT_REFUSED
1491
+ assert payload["errors"][0]["code"] == "recovery-conflict"
1492
+ assert document.read_text(encoding="utf-8") == "manual recovery conflict\n"
1493
+ assert _transaction_journals(docs_root) == journals_before
1494
+
1495
+
1496
+ def test_recover_quarantine_refuses_unexpected_active_document_before_rollback(
1497
+ tmp_path: Path,
1498
+ capsys: pytest.CaptureFixture[str],
1499
+ monkeypatch: pytest.MonkeyPatch,
1500
+ ) -> None:
1501
+ root, docs_root, document = _eligible_project(tmp_path)
1502
+ manifest_before = (docs_root / contract.MANIFEST_FILENAME).read_bytes()
1503
+ _crash_at(monkeypatch, "quarantine-journal-ready")
1504
+
1505
+ with pytest.raises(_SimulatedCrash):
1506
+ phase4_exit.apply_quarantine(root)
1507
+
1508
+ rogue = docs_root / "manual.md"
1509
+ _write_doc(rogue, title="并发新增文档")
1510
+ exit_code, payload = _run_json(capsys, root, "--recover")
1511
+
1512
+ assert exit_code == phase4_exit.EXIT_REFUSED
1513
+ assert payload["errors"][0]["code"] == "recovery-conflict"
1514
+ assert not document.exists()
1515
+ assert rogue.is_file()
1516
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == manifest_before
1517
+ assert len(_transaction_journals(docs_root)) == 2
1518
+
1519
+
1520
+ def test_recover_prepared_restore_refuses_unexpected_active_document(
1521
+ tmp_path: Path,
1522
+ capsys: pytest.CaptureFixture[str],
1523
+ monkeypatch: pytest.MonkeyPatch,
1524
+ ) -> None:
1525
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
1526
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1527
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
1528
+ receipt_before = receipt_path.read_bytes()
1529
+ manifest_before = (docs_root / contract.MANIFEST_FILENAME).read_bytes()
1530
+ _crash_at(monkeypatch, "restore-copy-complete")
1531
+
1532
+ with pytest.raises(_SimulatedCrash):
1533
+ phase4_exit.restore_receipt(root, receipt_id)
1534
+
1535
+ rogue = docs_root / "manual.md"
1536
+ _write_doc(rogue, title="并发新增文档")
1537
+ exit_code, payload = _run_json(capsys, root, "--recover")
1538
+
1539
+ assert exit_code == phase4_exit.EXIT_REFUSED
1540
+ assert payload["errors"][0]["code"] == "recovery-conflict"
1541
+ assert document.is_file()
1542
+ assert rogue.is_file()
1543
+ assert receipt_path.read_bytes() == receipt_before
1544
+ assert (docs_root / contract.MANIFEST_FILENAME).read_bytes() == manifest_before
1545
+ assert len(_transaction_journals(docs_root)) == 2
1546
+
1547
+
1548
+ @pytest.mark.parametrize(
1549
+ "crash_point",
1550
+ ["restore-copy-complete", "restore-journal-ready"],
1551
+ )
1552
+ def test_restore_recovery_preflights_receipt_closed_set_before_metadata_writes(
1553
+ tmp_path: Path,
1554
+ capsys: pytest.CaptureFixture[str],
1555
+ monkeypatch: pytest.MonkeyPatch,
1556
+ crash_point: str,
1557
+ ) -> None:
1558
+ root, docs_root, document = _eligible_project(tmp_path)
1559
+ claude_path = _write_supported_claude(root)
1560
+ apply_code, apply_payload = _run_json(capsys, root, "--apply")
1561
+ assert apply_code == phase4_exit.EXIT_OK, apply_payload
1562
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
1563
+ receipt_dir = docs_root / phase4_exit.QUARANTINE_DIRNAME / receipt_id
1564
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
1565
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
1566
+ _crash_at(monkeypatch, crash_point)
1567
+
1568
+ with pytest.raises(_SimulatedCrash):
1569
+ phase4_exit.restore_receipt(root, receipt_id)
1570
+
1571
+ manifest_before = manifest_path.read_bytes()
1572
+ receipt_before = receipt_path.read_bytes()
1573
+ claude_before = claude_path.read_bytes()
1574
+ foreign = receipt_dir / "manual.txt"
1575
+ foreign.write_bytes(b"manual owner\n")
1576
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
1577
+
1578
+ exit_code, payload = _run_json(capsys, root, "--recover")
1579
+
1580
+ assert exit_code == phase4_exit.EXIT_REFUSED
1581
+ assert payload["errors"][0]["code"] == "recovery-conflict"
1582
+ assert document.is_file()
1583
+ assert foreign.read_bytes() == b"manual owner\n"
1584
+ assert manifest_path.read_bytes() == manifest_before
1585
+ assert receipt_path.read_bytes() == receipt_before
1586
+ assert claude_path.read_bytes() == claude_before
1587
+ assert _transaction_journals(docs_root)
1588
+
1589
+
1590
+ def test_quarantine_rollback_never_overwrites_unknown_manifest(
1591
+ tmp_path: Path,
1592
+ capsys: pytest.CaptureFixture[str],
1593
+ monkeypatch: pytest.MonkeyPatch,
1594
+ ) -> None:
1595
+ root, docs_root, document = _eligible_project(tmp_path)
1596
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
1597
+ manual_manifest = '{"manual":true}\n'
1598
+
1599
+ def conflict_commit(
1600
+ path: Path,
1601
+ value: object,
1602
+ journal: phase4_exit.TransactionJournal,
1603
+ **kwargs: object,
1604
+ ) -> None:
1605
+ del value, journal, kwargs
1606
+ contract.atomic_write_utf8(path, manual_manifest)
1607
+ raise OSError("injected concurrent manifest replacement")
1608
+
1609
+ monkeypatch.setattr(phase4_exit, "_commit_manifest", conflict_commit)
1610
+ exit_code, payload = _run_json(capsys, root, "--apply")
1611
+
1612
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
1613
+ assert payload["errors"][-1]["code"] == "quarantine-rollback-failed"
1614
+ assert contract.read_utf8(manifest_path) == manual_manifest
1615
+ assert not document.exists()
1616
+ assert len(_transaction_journals(docs_root)) == 2
1617
+
1618
+
1619
+ def test_quarantine_rollback_preserves_unowned_staging_file(
1620
+ tmp_path: Path,
1621
+ capsys: pytest.CaptureFixture[str],
1622
+ monkeypatch: pytest.MonkeyPatch,
1623
+ ) -> None:
1624
+ root, docs_root, document = _eligible_project(tmp_path)
1625
+ real_write_snapshot = phase4_exit._write_exclusive_snapshot
1626
+ unowned: Path | None = None
1627
+
1628
+ def fail_receipt(
1629
+ path: Path,
1630
+ base: Path,
1631
+ description: str,
1632
+ snapshot: dict,
1633
+ *,
1634
+ staging_root: Path | None = None,
1635
+ staging_trusted_root: Path | None = None,
1636
+ ) -> phase4_exit.ExclusiveCopy:
1637
+ nonlocal unowned
1638
+ if description.startswith("quarantine receipt "):
1639
+ unowned = Path(path).parent / "manual.txt"
1640
+ unowned.write_text("manual\n", encoding="utf-8")
1641
+ raise OSError("injected receipt failure with unowned file")
1642
+ return real_write_snapshot(
1643
+ path,
1644
+ base,
1645
+ description,
1646
+ snapshot,
1647
+ staging_root=staging_root,
1648
+ staging_trusted_root=staging_trusted_root,
1649
+ )
1650
+
1651
+ monkeypatch.setattr(phase4_exit, "_write_exclusive_snapshot", fail_receipt)
1652
+ exit_code, payload = _run_json(capsys, root, "--apply")
1653
+
1654
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
1655
+ assert payload["errors"][-1]["code"] == "quarantine-rollback-failed"
1656
+ assert document.is_file()
1657
+ assert unowned is not None and unowned.read_text(encoding="utf-8") == "manual\n"
1658
+ assert len(_transaction_journals(docs_root)) == 1
1659
+
1660
+
1661
+ def test_recover_without_journal_is_successful_noop(
1662
+ tmp_path: Path,
1663
+ capsys: pytest.CaptureFixture[str],
1664
+ ) -> None:
1665
+ root, _, _ = _eligible_project(tmp_path)
1666
+
1667
+ exit_code, payload = _run_json(capsys, root, "--recover")
1668
+
1669
+ assert exit_code == phase4_exit.EXIT_OK, payload
1670
+ assert payload["status"] == "no-pending-transaction"
1671
+ assert payload["recovery"] == {"required": False, "recovered": False}
1672
+
1673
+
1674
+ @pytest.mark.parametrize(
1675
+ "residue_kind",
1676
+ ("prepared", "committed", "rolled_back", "temporary", "artifact-root"),
1677
+ )
1678
+ def test_recover_is_blocked_by_every_coordinator_pending_form(
1679
+ tmp_path: Path,
1680
+ capsys: pytest.CaptureFixture[str],
1681
+ residue_kind: str,
1682
+ ) -> None:
1683
+ root, _, _ = _eligible_project(tmp_path)
1684
+ slots = contract.coordinator_publish_journal_paths(root)
1685
+ if residue_kind in slots:
1686
+ residue = slots[residue_kind]
1687
+ residue.write_bytes(b"coordinator journal residue\n")
1688
+ elif residue_kind == "temporary":
1689
+ residue = slots["prepared"].with_name(
1690
+ f"{slots['prepared'].name}{contract.COORDINATOR_TEMP_MARKER}dead.tmp"
1691
+ )
1692
+ residue.write_bytes(b"coordinator temporary residue\n")
1693
+ else:
1694
+ residue = slots["prepared"].with_name(
1695
+ f"{slots['prepared'].stem}"
1696
+ f"{contract.COORDINATOR_ARTIFACT_ROOT_MARKER}dead"
1697
+ )
1698
+ residue.mkdir()
1699
+
1700
+ try:
1701
+ exit_code, payload = _run_json(capsys, root, "--recover")
1702
+
1703
+ assert exit_code == phase4_exit.EXIT_REFUSED
1704
+ assert payload["status"] == "coordinator-recovery-required"
1705
+ assert payload["errors"][0]["code"] == "coordinator-recovery-required"
1706
+ assert residue.exists()
1707
+ finally:
1708
+ if residue.is_dir():
1709
+ residue.rmdir()
1710
+ else:
1711
+ residue.unlink(missing_ok=True)
1712
+
1713
+
1714
+ def test_pending_journal_blocks_report_apply_and_restore(
1715
+ tmp_path: Path,
1716
+ capsys: pytest.CaptureFixture[str],
1717
+ monkeypatch: pytest.MonkeyPatch,
1718
+ ) -> None:
1719
+ root, docs_root, _ = _eligible_project(tmp_path)
1720
+ _crash_at(monkeypatch, "quarantine-journal-ready")
1721
+
1722
+ with pytest.raises(_SimulatedCrash):
1723
+ phase4_exit.apply_quarantine(root)
1724
+
1725
+ journal_data = contract.read_json_strict(_transaction_journals(docs_root)[0])
1726
+ receipt_id = journal_data["quarantine"]["moves"][0]["receipt_id"]
1727
+ for arguments in ((), ("--apply",), ("--restore", receipt_id)):
1728
+ exit_code, payload = _run_json(capsys, root, *arguments)
1729
+ assert exit_code == phase4_exit.EXIT_REFUSED
1730
+ assert payload["status"] == "phase4-recovery-required"
1731
+ assert payload["errors"][0]["code"] == "phase4-recovery-required"
1732
+
1733
+
1734
+ @pytest.mark.parametrize("winerror", (5, 32, 33))
1735
+ @pytest.mark.skipif(
1736
+ phase4_exit.os.name != "nt",
1737
+ reason="Windows os.rename no-replace path; POSIX uses renameat2",
1738
+ )
1739
+ def test_windows_staging_rename_retries_only_transient_locks(
1740
+ tmp_path: Path,
1741
+ monkeypatch: pytest.MonkeyPatch,
1742
+ winerror: int,
1743
+ ) -> None:
1744
+ staging = tmp_path / "staging"
1745
+ final = tmp_path / "final"
1746
+ staging.mkdir()
1747
+ (staging / "payload.txt").write_bytes(b"payload\n")
1748
+ real_rename = phase4_exit.os.rename
1749
+ attempts = 0
1750
+ pauses: list[float] = []
1751
+
1752
+ class WindowsBusyError(OSError):
1753
+ @property
1754
+ def winerror(self) -> int:
1755
+ return winerror
1756
+
1757
+ def flaky_rename(source: Path, destination: Path) -> None:
1758
+ nonlocal attempts
1759
+ attempts += 1
1760
+ if attempts < 3:
1761
+ raise WindowsBusyError("sharing violation")
1762
+ real_rename(source, destination)
1763
+
1764
+ monkeypatch.setattr(phase4_exit.os, "rename", flaky_rename)
1765
+ phase4_exit._rename_staged_quarantine_directory(
1766
+ staging,
1767
+ final,
1768
+ expected_files={
1769
+ "payload.txt": phase4_exit._text_snapshot("payload\n"),
1770
+ },
1771
+ is_windows=True,
1772
+ sleep_func=pauses.append,
1773
+ max_attempts=4,
1774
+ )
1775
+
1776
+ assert attempts == 3
1777
+ assert pauses == [0.01, 0.02]
1778
+ assert not staging.exists()
1779
+ assert (final / "payload.txt").read_text(encoding="utf-8") == "payload\n"
1780
+
1781
+
1782
+ @pytest.mark.skipif(
1783
+ phase4_exit.os.name != "nt",
1784
+ reason="Windows os.rename no-replace path; POSIX uses renameat2",
1785
+ )
1786
+ def test_windows_staging_rename_does_not_mask_permanent_error(
1787
+ tmp_path: Path,
1788
+ monkeypatch: pytest.MonkeyPatch,
1789
+ ) -> None:
1790
+ staging = tmp_path / "staging"
1791
+ final = tmp_path / "final"
1792
+ staging.mkdir()
1793
+ attempts = 0
1794
+
1795
+ def permanent_failure(source: Path, destination: Path) -> None:
1796
+ nonlocal attempts
1797
+ attempts += 1
1798
+ raise OSError("permanent rename failure")
1799
+
1800
+ monkeypatch.setattr(phase4_exit.os, "rename", permanent_failure)
1801
+ with pytest.raises(OSError, match="permanent rename failure"):
1802
+ phase4_exit._rename_staged_quarantine_directory(
1803
+ staging,
1804
+ final,
1805
+ expected_files={},
1806
+ is_windows=True,
1807
+ sleep_func=lambda _: None,
1808
+ max_attempts=4,
1809
+ )
1810
+ assert attempts == 1
1811
+
1812
+
1813
+ def test_initial_journal_partial_staging_never_becomes_canonical(
1814
+ tmp_path: Path,
1815
+ monkeypatch: pytest.MonkeyPatch,
1816
+ ) -> None:
1817
+ root, docs_root, document = _eligible_project(tmp_path)
1818
+ real_raw_write = phase4_exit._write_raw_exclusive_snapshot
1819
+
1820
+ def crash_during_staging_write(
1821
+ path: Path,
1822
+ base: Path,
1823
+ description: str,
1824
+ snapshot: dict,
1825
+ ) -> phase4_exit.ExclusiveCopy:
1826
+ if description == "transaction journal publication staging file":
1827
+ path.write_bytes(b'{"partial":')
1828
+ raise _SimulatedCrash("partial journal staging write")
1829
+ return real_raw_write(path, base, description, snapshot)
1830
+
1831
+ monkeypatch.setattr(
1832
+ phase4_exit,
1833
+ "_write_raw_exclusive_snapshot",
1834
+ crash_during_staging_write,
1835
+ )
1836
+ with pytest.raises(_SimulatedCrash):
1837
+ phase4_exit.apply_quarantine(root)
1838
+
1839
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
1840
+ assert document.is_file()
1841
+ assert _transaction_journals(docs_root) == []
1842
+ leftovers = [
1843
+ path for path in quarantine_root.iterdir() if path.name != ".phase4.lock"
1844
+ ]
1845
+ assert len(leftovers) == 1
1846
+ assert leftovers[0].name.endswith(".tmp")
1847
+ assert leftovers[0].read_bytes() == b'{"partial":'
1848
+
1849
+
1850
+ def test_hard_exit_during_generic_staging_never_exposes_partial_canonical(
1851
+ tmp_path: Path,
1852
+ ) -> None:
1853
+ base = tmp_path / "publication-root"
1854
+ destination = base / "receipt" / phase4_exit.RECEIPT_FILENAME
1855
+ base.mkdir()
1856
+ payload = '{"state":"ready"}\n'
1857
+ script = r"""
1858
+ import os
1859
+ from pathlib import Path
1860
+ import phase4_exit
1861
+
1862
+ base = Path(os.environ["PHASE4_TEST_BASE"])
1863
+ destination = base / "receipt" / phase4_exit.RECEIPT_FILENAME
1864
+
1865
+
1866
+ def crash(point: str) -> None:
1867
+ if point == "exclusive-staging-write-started":
1868
+ os._exit(91)
1869
+
1870
+
1871
+ phase4_exit._transaction_fault = crash
1872
+ phase4_exit._write_exclusive_snapshot(
1873
+ destination,
1874
+ base,
1875
+ "hard-exit receipt",
1876
+ phase4_exit._text_snapshot(os.environ["PHASE4_TEST_PAYLOAD"]),
1877
+ )
1878
+ """
1879
+ env = os.environ.copy()
1880
+ env.update(
1881
+ {
1882
+ "PHASE4_TEST_BASE": str(base),
1883
+ "PHASE4_TEST_PAYLOAD": payload,
1884
+ "PYTHONIOENCODING": "utf-8",
1885
+ "PYTHONPATH": str(Path(phase4_exit.__file__).parent),
1886
+ }
1887
+ )
1888
+
1889
+ completed = subprocess.run(
1890
+ [sys.executable, "-c", script],
1891
+ capture_output=True,
1892
+ text=True,
1893
+ encoding="utf-8",
1894
+ env=env,
1895
+ check=False,
1896
+ )
1897
+
1898
+ assert completed.returncode == 91, completed.stderr
1899
+ assert not destination.exists()
1900
+ assert list(destination.parent.iterdir()) == []
1901
+ leftovers = list(base.glob(f"{phase4_exit._ARCHIVE_PREFIX}*.tmp"))
1902
+ assert len(leftovers) == 1
1903
+
1904
+ phase4_exit._write_exclusive_snapshot(
1905
+ destination,
1906
+ base,
1907
+ "hard-exit receipt retry",
1908
+ phase4_exit._text_snapshot(payload),
1909
+ )
1910
+ assert destination.read_text(encoding="utf-8") == payload
1911
+
1912
+
1913
+ def test_initial_journal_publish_is_atomic_no_replace(
1914
+ tmp_path: Path,
1915
+ capsys: pytest.CaptureFixture[str],
1916
+ monkeypatch: pytest.MonkeyPatch,
1917
+ ) -> None:
1918
+ root, _, document = _eligible_project(tmp_path)
1919
+ real_rename = phase4_exit._rename_no_replace
1920
+ raced_path: Path | None = None
1921
+
1922
+ def racing_rename(source: Path, destination: Path) -> None:
1923
+ nonlocal raced_path
1924
+ destination = Path(destination)
1925
+ if destination.name == phase4_exit._TRANSACTION_CANONICAL_FILENAME:
1926
+ raced_path = destination
1927
+ destination.write_bytes(b"external journal owner\n")
1928
+ real_rename(source, destination)
1929
+
1930
+ monkeypatch.setattr(phase4_exit, "_rename_no_replace", racing_rename)
1931
+ exit_code, payload = _run_json(capsys, root, "--apply")
1932
+
1933
+ assert exit_code == phase4_exit.EXIT_REFUSED
1934
+ assert payload["errors"][-1]["code"] == "recovery-journal-conflict"
1935
+ assert document.is_file()
1936
+ assert raced_path is not None
1937
+ assert raced_path.read_bytes() == b"external journal owner\n"
1938
+
1939
+
1940
+ def test_final_quarantine_validation_detects_new_inbound_reference(
1941
+ tmp_path: Path,
1942
+ capsys: pytest.CaptureFixture[str],
1943
+ monkeypatch: pytest.MonkeyPatch,
1944
+ ) -> None:
1945
+ root, docs_root = _make_root(tmp_path)
1946
+ candidate = docs_root / "orphan.md"
1947
+ referrer = docs_root / "refs" / "source.md"
1948
+ _write_doc(candidate, title="退出候选")
1949
+ _write_doc(referrer, title="引用者")
1950
+ (root / "refs" / "source").mkdir(parents=True)
1951
+ _write_manifest(docs_root)
1952
+ referrer_before = referrer.read_bytes()
1953
+ real_build_inbound = phase4_exit._build_inbound_sources
1954
+ restore_after_scan = False
1955
+
1956
+ def inject_reference(point: str) -> None:
1957
+ nonlocal restore_after_scan
1958
+ if point == "quarantine-before-final-validation":
1959
+ referrer.write_bytes(referrer_before + b"\n[late](../orphan.md)\n")
1960
+ restore_after_scan = True
1961
+
1962
+ def scan_and_restore(
1963
+ active_paths: set[str],
1964
+ active_docs_root: Path,
1965
+ ) -> tuple[dict[str, set[str]], list[dict[str, str]]]:
1966
+ nonlocal restore_after_scan
1967
+ result = real_build_inbound(active_paths, active_docs_root)
1968
+ if restore_after_scan:
1969
+ referrer.write_bytes(referrer_before)
1970
+ restore_after_scan = False
1971
+ return result
1972
+
1973
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", inject_reference)
1974
+ monkeypatch.setattr(phase4_exit, "_build_inbound_sources", scan_and_restore)
1975
+ exit_code, payload = _run_json(capsys, root, "--apply")
1976
+
1977
+ assert exit_code == phase4_exit.EXIT_REFUSED
1978
+ assert payload["errors"][-1]["code"] == "candidate-has-inbound-references"
1979
+ assert candidate.is_file()
1980
+ assert referrer.read_bytes() == referrer_before
1981
+ assert _transaction_journals(docs_root) == []
1982
+
1983
+
1984
+ def _standalone_quarantine_move(tmp_path: Path) -> phase4_exit.QuarantineMove:
1985
+ source = tmp_path / "candidate.md"
1986
+ source.write_bytes(b"# candidate\n<!-- AUTO-GENERATED v3.0: folder-doc START -->\n")
1987
+ staging = tmp_path / "staging"
1988
+ staging_payload = staging / phase4_exit.PAYLOAD_DIRNAME / source.name
1989
+ staging_payload.parent.mkdir(parents=True)
1990
+ final_dir = tmp_path / "final"
1991
+ digest = contract.sha256_file(source)
1992
+ return phase4_exit.QuarantineMove(
1993
+ receipt={
1994
+ "original_path": source.name,
1995
+ "payload_identity": list(phase4_exit._identity_from_stat(source.lstat())),
1996
+ "sha256": digest,
1997
+ },
1998
+ source_path=source,
1999
+ staging_dir=staging,
2000
+ final_dir=final_dir,
2001
+ staging_payload=staging_payload,
2002
+ final_payload=final_dir / phase4_exit.PAYLOAD_DIRNAME / source.name,
2003
+ )
2004
+
2005
+
2006
+ def test_source_swap_to_symlink_is_refused_before_unlink(
2007
+ tmp_path: Path,
2008
+ monkeypatch: pytest.MonkeyPatch,
2009
+ ) -> None:
2010
+ move = _standalone_quarantine_move(tmp_path)
2011
+ outside = tmp_path / "outside.md"
2012
+ outside.write_bytes(move.source_path.read_bytes())
2013
+
2014
+ def swap_source(point: str) -> None:
2015
+ if point == "quarantine-before-source-link":
2016
+ move.source_path.unlink()
2017
+ try:
2018
+ move.source_path.symlink_to(outside)
2019
+ except (NotImplementedError, OSError) as exc:
2020
+ pytest.skip(f"symlink creation unavailable: {exc}")
2021
+
2022
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", swap_source)
2023
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
2024
+ phase4_exit._link_source_to_staging_no_replace(move)
2025
+
2026
+ assert caught.value.code == "candidate-path-changed"
2027
+ assert move.source_path.is_symlink()
2028
+ assert outside.is_file()
2029
+ assert not move.staging_payload.exists()
2030
+
2031
+
2032
+ def test_source_transfer_never_overwrites_racing_staging_target(
2033
+ tmp_path: Path,
2034
+ monkeypatch: pytest.MonkeyPatch,
2035
+ ) -> None:
2036
+ move = _standalone_quarantine_move(tmp_path)
2037
+
2038
+ def create_target(point: str) -> None:
2039
+ if point == "quarantine-before-source-link":
2040
+ move.staging_payload.write_bytes(b"concurrent owner\n")
2041
+
2042
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", create_target)
2043
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
2044
+ phase4_exit._link_source_to_staging_no_replace(move)
2045
+
2046
+ assert caught.value.code == "quarantine-staging-conflict"
2047
+ assert move.source_path.is_file()
2048
+ assert move.staging_payload.read_bytes() == b"concurrent owner\n"
2049
+
2050
+
2051
+ @pytest.mark.skipif(
2052
+ phase4_exit.os.name != "nt",
2053
+ reason="Windows os.rename no-replace path; POSIX uses renameat2",
2054
+ )
2055
+ def test_windows_rename_retry_revalidates_closed_directory(
2056
+ tmp_path: Path,
2057
+ monkeypatch: pytest.MonkeyPatch,
2058
+ ) -> None:
2059
+ staging = tmp_path / "staging"
2060
+ final = tmp_path / "final"
2061
+ staging.mkdir()
2062
+ payload = staging / "payload.txt"
2063
+ payload.write_bytes(b"payload\n")
2064
+ attempts = 0
2065
+
2066
+ class WindowsBusyError(OSError):
2067
+ @property
2068
+ def winerror(self) -> int:
2069
+ return 32
2070
+
2071
+ def add_unowned_file_then_fail(source: Path, destination: Path) -> None:
2072
+ nonlocal attempts
2073
+ del destination
2074
+ attempts += 1
2075
+ (Path(source) / "unowned.txt").write_bytes(b"manual\n")
2076
+ raise WindowsBusyError("sharing violation")
2077
+
2078
+ monkeypatch.setattr(phase4_exit.os, "rename", add_unowned_file_then_fail)
2079
+ with pytest.raises(phase4_exit.Phase4Refusal, match="unowned file"):
2080
+ phase4_exit._rename_staged_quarantine_directory(
2081
+ staging,
2082
+ final,
2083
+ expected_files={"payload.txt": phase4_exit._text_snapshot("payload\n")},
2084
+ is_windows=True,
2085
+ sleep_func=lambda _: None,
2086
+ max_attempts=4,
2087
+ )
2088
+
2089
+ assert attempts == 1
2090
+ assert staging.is_dir()
2091
+ assert not final.exists()
2092
+ assert (staging / "unowned.txt").read_bytes() == b"manual\n"
2093
+
2094
+
2095
+ def test_text_update_readback_failure_is_unknown_and_not_silently_rolled_back(
2096
+ tmp_path: Path,
2097
+ monkeypatch: pytest.MonkeyPatch,
2098
+ ) -> None:
2099
+ path = tmp_path / "metadata.txt"
2100
+ path.write_bytes(b"before\n")
2101
+ update = phase4_exit.TextUpdate(path=path, before="before\n", after="after\n")
2102
+ real_set_snapshot_state = phase4_exit._set_snapshot_state
2103
+ readback_blocked = False
2104
+
2105
+ def publish_then_fail(*args: object, **kwargs: object) -> None:
2106
+ nonlocal readback_blocked
2107
+ real_set_snapshot_state(*args, **kwargs)
2108
+ readback_blocked = True
2109
+ raise OSError("post-replace durability failure")
2110
+
2111
+ real_read_utf8 = phase4_exit.contract.read_utf8
2112
+
2113
+ def fail_readback(target: Path) -> str:
2114
+ if readback_blocked and Path(target) == path:
2115
+ raise OSError("readback unavailable")
2116
+ return real_read_utf8(target)
2117
+
2118
+ monkeypatch.setattr(phase4_exit, "_set_snapshot_state", publish_then_fail)
2119
+ monkeypatch.setattr(phase4_exit.contract, "read_utf8", fail_readback)
2120
+ with pytest.raises(OSError, match="durability failure"):
2121
+ phase4_exit._apply_text_update(update)
2122
+
2123
+ assert update.state is phase4_exit.TextUpdateState.UNKNOWN
2124
+ rollback_errors = phase4_exit._rollback_text_update(update)
2125
+ assert rollback_errors
2126
+ assert update.state is phase4_exit.TextUpdateState.UNKNOWN
2127
+ assert path.read_bytes() == b"after\n"
2128
+
2129
+
2130
+ def test_snapshot_update_refuses_replacement_after_identity_capture(
2131
+ tmp_path: Path,
2132
+ monkeypatch: pytest.MonkeyPatch,
2133
+ ) -> None:
2134
+ path = tmp_path / "metadata.txt"
2135
+ path.write_text("before\n", encoding="utf-8")
2136
+ desired = phase4_exit._text_snapshot("after\n")
2137
+ before = phase4_exit._capture_snapshot(path, tmp_path, "metadata")
2138
+ real_rename = phase4_exit._rename_no_replace
2139
+ foreign_identity: tuple[int, int, int, int] | None = None
2140
+ injected = False
2141
+
2142
+ def replace_then_rename(source: Path, destination: Path) -> None:
2143
+ nonlocal foreign_identity, injected
2144
+ if not injected and Path(source) == path:
2145
+ replacement = tmp_path / "foreign.tmp"
2146
+ replacement.write_text("before\n", encoding="utf-8")
2147
+ replacement.replace(path)
2148
+ foreign_identity = phase4_exit._identity_from_stat(path.lstat())
2149
+ injected = True
2150
+ real_rename(source, destination)
2151
+
2152
+ monkeypatch.setattr(phase4_exit, "_rename_no_replace", replace_then_rename)
2153
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
2154
+ phase4_exit._set_snapshot_state(
2155
+ path,
2156
+ tmp_path,
2157
+ "metadata",
2158
+ desired,
2159
+ [before],
2160
+ )
2161
+
2162
+ assert caught.value.code == "recovery-conflict"
2163
+ assert path.read_text(encoding="utf-8") == "before\n"
2164
+ assert foreign_identity is not None
2165
+ assert phase4_exit._identity_from_stat(path.lstat()) == foreign_identity
2166
+
2167
+
2168
+ def test_snapshot_update_preserves_foreign_commit_gap_writer(
2169
+ tmp_path: Path,
2170
+ monkeypatch: pytest.MonkeyPatch,
2171
+ ) -> None:
2172
+ path = tmp_path / "metadata.txt"
2173
+ path.write_text("before\n", encoding="utf-8")
2174
+ before = phase4_exit._capture_snapshot(path, tmp_path, "metadata")
2175
+
2176
+ def create_foreign_before_publish(point: str) -> None:
2177
+ if point == "metadata-preimage-detached":
2178
+ path.write_text("foreign\n", encoding="utf-8")
2179
+
2180
+ monkeypatch.setattr(
2181
+ phase4_exit,
2182
+ "_transaction_fault",
2183
+ create_foreign_before_publish,
2184
+ )
2185
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
2186
+ phase4_exit._set_snapshot_state(
2187
+ path,
2188
+ tmp_path,
2189
+ "metadata",
2190
+ phase4_exit._text_snapshot("after\n"),
2191
+ [before],
2192
+ )
2193
+
2194
+ assert caught.value.code == "recovery-conflict"
2195
+ assert path.read_text(encoding="utf-8") == "foreign\n"
2196
+
2197
+
2198
+ def test_restore_target_identity_swap_before_manifest_commit_is_refused(
2199
+ tmp_path: Path,
2200
+ capsys: pytest.CaptureFixture[str],
2201
+ monkeypatch: pytest.MonkeyPatch,
2202
+ ) -> None:
2203
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2204
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2205
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
2206
+ payload_path = (
2207
+ receipt_dir / contract.read_json_strict(receipt_path)["quarantined_path"]
2208
+ )
2209
+
2210
+ def replace_target(point: str) -> None:
2211
+ if point == "restore-before-final-validation":
2212
+ replacement = document.with_name("replacement.md.tmp")
2213
+ replacement.write_bytes(document.read_bytes())
2214
+ replacement.replace(document)
2215
+
2216
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", replace_target)
2217
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
2218
+
2219
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
2220
+ assert payload["errors"][-1]["code"] == "restore-rollback-failed"
2221
+ assert document.is_file()
2222
+ assert payload_path.is_file()
2223
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
2224
+ raw_manifest = contract.read_json_strict(docs_root / contract.MANIFEST_FILENAME)
2225
+ assert raw_manifest["total"] == 0
2226
+ assert len(_transaction_journals(docs_root)) == 3
2227
+
2228
+
2229
+ def test_restore_postcommit_target_swap_retains_payload_and_journal(
2230
+ tmp_path: Path,
2231
+ capsys: pytest.CaptureFixture[str],
2232
+ monkeypatch: pytest.MonkeyPatch,
2233
+ ) -> None:
2234
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2235
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2236
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
2237
+ receipt_before = contract.read_json_strict(receipt_path)
2238
+ payload_path = receipt_dir / receipt_before["quarantined_path"]
2239
+
2240
+ def replace_target(point: str) -> None:
2241
+ if point == "restore-before-payload-cleanup":
2242
+ replacement = document.with_name("replacement.md.tmp")
2243
+ replacement.write_bytes(document.read_bytes())
2244
+ replacement.replace(document)
2245
+
2246
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", replace_target)
2247
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
2248
+
2249
+ assert exit_code == phase4_exit.EXIT_OK, payload
2250
+ assert payload["warnings"]
2251
+ assert "retained its payload and journal" in payload["warnings"][-1]
2252
+ assert document.is_file()
2253
+ assert payload_path.is_file()
2254
+ assert contract.read_json_strict(receipt_path)["state"] == "restored"
2255
+ assert contract.load_manifest(docs_root)["total"] == 1
2256
+ assert len(_transaction_journals(docs_root)) == 3
2257
+
2258
+
2259
+ def test_quarantine_precommit_validator_detects_recreated_source(
2260
+ tmp_path: Path,
2261
+ capsys: pytest.CaptureFixture[str],
2262
+ monkeypatch: pytest.MonkeyPatch,
2263
+ ) -> None:
2264
+ root, docs_root, document = _eligible_project(tmp_path)
2265
+ source = root / document.stem
2266
+ real_commit = phase4_exit._commit_manifest
2267
+
2268
+ def recreate_source_then_commit(
2269
+ path: Path,
2270
+ value: Mapping[str, object],
2271
+ journal: phase4_exit.TransactionJournal,
2272
+ **kwargs: object,
2273
+ ) -> phase4_exit.ManifestCommitDisposition:
2274
+ source.mkdir()
2275
+ return real_commit(path, value, journal, **kwargs)
2276
+
2277
+ monkeypatch.setattr(phase4_exit, "_commit_manifest", recreate_source_then_commit)
2278
+ exit_code, payload = _run_json(capsys, root, "--apply")
2279
+
2280
+ assert exit_code == phase4_exit.EXIT_REFUSED
2281
+ assert payload["errors"][-1]["code"] == "source-no-longer-confirmed-missing"
2282
+ assert source.is_dir()
2283
+ assert document.is_file()
2284
+ assert contract.load_manifest(docs_root)["total"] == 1
2285
+ assert _transaction_journals(docs_root) == []
2286
+
2287
+
2288
+ def test_quarantine_postcommit_validator_retains_durable_state_on_source_race(
2289
+ tmp_path: Path,
2290
+ capsys: pytest.CaptureFixture[str],
2291
+ monkeypatch: pytest.MonkeyPatch,
2292
+ ) -> None:
2293
+ root, docs_root, document = _eligible_project(tmp_path)
2294
+ source = root / document.stem
2295
+ real_commit = phase4_exit._commit_manifest
2296
+
2297
+ def recreate_source_after_commit(
2298
+ path: Path,
2299
+ value: Mapping[str, object],
2300
+ journal: phase4_exit.TransactionJournal,
2301
+ **kwargs: object,
2302
+ ) -> phase4_exit.ManifestCommitDisposition:
2303
+ original_postcommit = kwargs.get("postcommit_validator")
2304
+ assert callable(original_postcommit)
2305
+
2306
+ def validate_after_race() -> None:
2307
+ source.mkdir()
2308
+ original_postcommit()
2309
+
2310
+ kwargs["postcommit_validator"] = validate_after_race
2311
+ return real_commit(path, value, journal, **kwargs)
2312
+
2313
+ monkeypatch.setattr(phase4_exit, "_commit_manifest", recreate_source_after_commit)
2314
+ exit_code, payload = _run_json(capsys, root, "--apply")
2315
+
2316
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
2317
+ assert payload["errors"][-1]["code"] == "manifest-postcommit-conflict"
2318
+ assert source.is_dir()
2319
+ assert not document.exists()
2320
+ assert contract.load_manifest(docs_root)["total"] == 0
2321
+ journals = _transaction_journals(docs_root)
2322
+ assert len(journals) == 2
2323
+ ready = contract.read_json_strict(
2324
+ next(
2325
+ path
2326
+ for path in journals
2327
+ if path.name == phase4_exit._TRANSACTION_READY_FILENAME
2328
+ )
2329
+ )
2330
+ receipt_id = ready["quarantine"]["moves"][0]["receipt_id"]
2331
+ receipt_dir = docs_root / phase4_exit.QUARANTINE_DIRNAME / receipt_id
2332
+ assert (receipt_dir / phase4_exit.RECEIPT_FILENAME).is_file()
2333
+
2334
+
2335
+ def test_restore_precommit_validator_detects_target_identity_race(
2336
+ tmp_path: Path,
2337
+ capsys: pytest.CaptureFixture[str],
2338
+ monkeypatch: pytest.MonkeyPatch,
2339
+ ) -> None:
2340
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2341
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2342
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
2343
+ payload_path = (
2344
+ receipt_dir / contract.read_json_strict(receipt_path)["quarantined_path"]
2345
+ )
2346
+ real_commit = phase4_exit._commit_manifest
2347
+ replacement_identity: tuple[int, int, int, int] | None = None
2348
+
2349
+ def replace_target_then_commit(
2350
+ path: Path,
2351
+ value: Mapping[str, object],
2352
+ journal: phase4_exit.TransactionJournal,
2353
+ **kwargs: object,
2354
+ ) -> phase4_exit.ManifestCommitDisposition:
2355
+ nonlocal replacement_identity
2356
+ replacement = document.with_name("replacement.md.tmp")
2357
+ replacement.write_bytes(document.read_bytes())
2358
+ replacement.replace(document)
2359
+ replacement_identity = phase4_exit._identity_from_stat(document.lstat())
2360
+ return real_commit(path, value, journal, **kwargs)
2361
+
2362
+ monkeypatch.setattr(phase4_exit, "_commit_manifest", replace_target_then_commit)
2363
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
2364
+
2365
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
2366
+ assert payload["errors"][-1]["code"] == "restore-rollback-failed"
2367
+ assert replacement_identity is not None
2368
+ assert phase4_exit._identity_from_stat(document.lstat()) == replacement_identity
2369
+ assert payload_path.is_file()
2370
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
2371
+ raw_manifest = contract.read_json_strict(docs_root / contract.MANIFEST_FILENAME)
2372
+ assert raw_manifest["total"] == 0
2373
+ assert len(_transaction_journals(docs_root)) == 3
2374
+
2375
+
2376
+ def test_restore_postcommit_validator_preserves_foreign_receipt_member(
2377
+ tmp_path: Path,
2378
+ capsys: pytest.CaptureFixture[str],
2379
+ monkeypatch: pytest.MonkeyPatch,
2380
+ ) -> None:
2381
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2382
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2383
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
2384
+ receipt_before = contract.read_json_strict(receipt_path)
2385
+ payload_path = receipt_dir / receipt_before["quarantined_path"]
2386
+ foreign = receipt_dir / "manual.txt"
2387
+ real_commit = phase4_exit._commit_manifest
2388
+
2389
+ def add_receipt_member_after_commit(
2390
+ path: Path,
2391
+ value: Mapping[str, object],
2392
+ journal: phase4_exit.TransactionJournal,
2393
+ **kwargs: object,
2394
+ ) -> phase4_exit.ManifestCommitDisposition:
2395
+ original_postcommit = kwargs.get("postcommit_validator")
2396
+ assert callable(original_postcommit)
2397
+
2398
+ def validate_after_race() -> None:
2399
+ foreign.write_bytes(b"manual owner\n")
2400
+ original_postcommit()
2401
+
2402
+ kwargs["postcommit_validator"] = validate_after_race
2403
+ return real_commit(path, value, journal, **kwargs)
2404
+
2405
+ monkeypatch.setattr(
2406
+ phase4_exit,
2407
+ "_commit_manifest",
2408
+ add_receipt_member_after_commit,
2409
+ )
2410
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
2411
+
2412
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
2413
+ assert payload["errors"][-1]["code"] == "manifest-postcommit-conflict"
2414
+ assert document.is_file()
2415
+ assert payload_path.is_file()
2416
+ assert foreign.read_bytes() == b"manual owner\n"
2417
+ assert contract.read_json_strict(receipt_path)["state"] == "restored"
2418
+ assert contract.load_manifest(docs_root)["total"] == 1
2419
+ assert len(_transaction_journals(docs_root)) == 3
2420
+
2421
+
2422
+ def test_new_transactions_use_fixed_singleton_journal_slot(
2423
+ tmp_path: Path,
2424
+ capsys: pytest.CaptureFixture[str],
2425
+ monkeypatch: pytest.MonkeyPatch,
2426
+ ) -> None:
2427
+ root, docs_root, document = _eligible_project(tmp_path)
2428
+ _crash_at(monkeypatch, "quarantine-journal-created")
2429
+
2430
+ with pytest.raises(_SimulatedCrash):
2431
+ phase4_exit.apply_quarantine(root)
2432
+
2433
+ journals = _transaction_journals(docs_root)
2434
+ assert [path.name for path in journals] == [
2435
+ phase4_exit._TRANSACTION_CANONICAL_FILENAME
2436
+ ]
2437
+ exit_code, payload = _run_json(capsys, root, "--recover")
2438
+ assert exit_code == phase4_exit.EXIT_OK, payload
2439
+ assert payload["recovery"]["outcome"] == "quarantine-rolled-back"
2440
+ assert document.is_file()
2441
+
2442
+
2443
+ def test_schema1_pending_journal_requires_audited_manual_recovery(
2444
+ tmp_path: Path,
2445
+ capsys: pytest.CaptureFixture[str],
2446
+ monkeypatch: pytest.MonkeyPatch,
2447
+ ) -> None:
2448
+ root, docs_root, document = _eligible_project(tmp_path)
2449
+ _crash_at(monkeypatch, "quarantine-journal-created")
2450
+
2451
+ with pytest.raises(_SimulatedCrash):
2452
+ phase4_exit.apply_quarantine(root)
2453
+
2454
+ journal_path = _transaction_journals(docs_root)[0]
2455
+ journal = contract.read_json_strict(journal_path)
2456
+ journal["schema_version"] = 1
2457
+ journal_path.write_text(
2458
+ contract.stable_json_dumps(journal),
2459
+ encoding="utf-8",
2460
+ )
2461
+ journal_bytes = journal_path.read_bytes()
2462
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2463
+ exit_code, payload = _run_json(capsys, root, "--recover")
2464
+
2465
+ assert exit_code == phase4_exit.EXIT_REFUSED
2466
+ assert payload["errors"][0]["code"] == "recovery-journal-legacy-schema"
2467
+ assert "audited manual recovery" in payload["errors"][0]["message"]
2468
+ assert document.is_file()
2469
+ assert journal_path.read_bytes() == journal_bytes
2470
+
2471
+
2472
+ def test_legacy_random_journal_remains_recoverable(
2473
+ tmp_path: Path,
2474
+ capsys: pytest.CaptureFixture[str],
2475
+ monkeypatch: pytest.MonkeyPatch,
2476
+ ) -> None:
2477
+ root, docs_root, document = _eligible_project(tmp_path)
2478
+ _crash_at(monkeypatch, "quarantine-journal-ready")
2479
+
2480
+ with pytest.raises(_SimulatedCrash):
2481
+ phase4_exit.apply_quarantine(root)
2482
+
2483
+ journals = _transaction_journals(docs_root)
2484
+ prepared = next(
2485
+ path
2486
+ for path in journals
2487
+ if path.name == phase4_exit._TRANSACTION_CANONICAL_FILENAME
2488
+ )
2489
+ ready = next(
2490
+ path
2491
+ for path in journals
2492
+ if path.name == phase4_exit._TRANSACTION_READY_FILENAME
2493
+ )
2494
+ data = contract.read_json_strict(ready)
2495
+ legacy = ready.with_name(
2496
+ phase4_exit._legacy_journal_filename(data["transaction_id"])
2497
+ )
2498
+ prepared.unlink()
2499
+ ready.rename(legacy)
2500
+ exit_code, payload = _run_json(capsys, root, "--recover")
2501
+
2502
+ assert exit_code == phase4_exit.EXIT_OK, payload
2503
+ assert payload["recovery"]["outcome"] == "quarantine-rolled-back"
2504
+ assert document.is_file()
2505
+ assert _transaction_journals(docs_root) == []
2506
+
2507
+
2508
+ def test_legacy_prepared_restore_companion_is_removed_after_recovery(
2509
+ tmp_path: Path,
2510
+ capsys: pytest.CaptureFixture[str],
2511
+ monkeypatch: pytest.MonkeyPatch,
2512
+ ) -> None:
2513
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(
2514
+ tmp_path,
2515
+ capsys,
2516
+ )
2517
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2518
+ _crash_at(monkeypatch, "restore-copy-complete")
2519
+
2520
+ with pytest.raises(_SimulatedCrash):
2521
+ phase4_exit.restore_receipt(root, receipt_id)
2522
+
2523
+ prepared = next(
2524
+ path
2525
+ for path in _transaction_journals(docs_root)
2526
+ if path.name == phase4_exit._TRANSACTION_CANONICAL_FILENAME
2527
+ )
2528
+ data = contract.read_json_strict(prepared)
2529
+ legacy = prepared.with_name(
2530
+ phase4_exit._legacy_journal_filename(data["transaction_id"])
2531
+ )
2532
+ prepared.rename(legacy)
2533
+
2534
+ exit_code, payload = _run_json(capsys, root, "--recover")
2535
+
2536
+ assert exit_code == phase4_exit.EXIT_OK, payload
2537
+ assert payload["recovery"]["outcome"] == "restore-finalized"
2538
+ assert document.is_file()
2539
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
2540
+ assert receipt["state"] == "restored"
2541
+ assert _transaction_journals(docs_root) == []
2542
+
2543
+
2544
+ def test_fixed_ready_alone_precommit_state_rolls_back(
2545
+ tmp_path: Path,
2546
+ capsys: pytest.CaptureFixture[str],
2547
+ monkeypatch: pytest.MonkeyPatch,
2548
+ ) -> None:
2549
+ root, docs_root, document = _eligible_project(tmp_path)
2550
+ _crash_at(monkeypatch, "quarantine-journal-ready")
2551
+
2552
+ with pytest.raises(_SimulatedCrash):
2553
+ phase4_exit.apply_quarantine(root)
2554
+
2555
+ journals = _transaction_journals(docs_root)
2556
+ prepared = next(
2557
+ path
2558
+ for path in journals
2559
+ if path.name == phase4_exit._TRANSACTION_CANONICAL_FILENAME
2560
+ )
2561
+ ready = next(
2562
+ path
2563
+ for path in journals
2564
+ if path.name == phase4_exit._TRANSACTION_READY_FILENAME
2565
+ )
2566
+ prepared.unlink()
2567
+
2568
+ exit_code, payload = _run_json(capsys, root, "--recover")
2569
+
2570
+ assert exit_code == phase4_exit.EXIT_OK, payload
2571
+ assert payload["recovery"]["outcome"] == "quarantine-rolled-back"
2572
+ assert document.is_file()
2573
+ assert not ready.exists()
2574
+ assert _transaction_journals(docs_root) == []
2575
+
2576
+
2577
+ def test_valid_publication_temp_blocks_then_promotes_on_recover(
2578
+ tmp_path: Path,
2579
+ capsys: pytest.CaptureFixture[str],
2580
+ monkeypatch: pytest.MonkeyPatch,
2581
+ ) -> None:
2582
+ root, docs_root, document = _eligible_project(tmp_path)
2583
+ _crash_at(monkeypatch, "quarantine-journal-created")
2584
+
2585
+ with pytest.raises(_SimulatedCrash):
2586
+ phase4_exit.apply_quarantine(root)
2587
+
2588
+ canonical = _transaction_journals(docs_root)[0]
2589
+ temporary = canonical.with_name(f".{canonical.name}.publish-{'a' * 32}.tmp")
2590
+ canonical.rename(temporary)
2591
+ report_code, report = _run_json(capsys, root)
2592
+ assert report_code == phase4_exit.EXIT_REFUSED
2593
+ assert report["status"] == "phase4-recovery-required"
2594
+ assert temporary.is_file()
2595
+
2596
+ recover_code, recovered = _run_json(capsys, root, "--recover")
2597
+ assert recover_code == phase4_exit.EXIT_OK, recovered
2598
+ assert recovered["recovery"]["outcome"] == "quarantine-rolled-back"
2599
+ assert document.is_file()
2600
+ assert not temporary.exists()
2601
+ assert _transaction_journals(docs_root) == []
2602
+
2603
+
2604
+ def test_partial_publication_temp_is_retained_and_blocks_all_runs(
2605
+ tmp_path: Path,
2606
+ capsys: pytest.CaptureFixture[str],
2607
+ ) -> None:
2608
+ root, docs_root, _ = _eligible_project(tmp_path)
2609
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
2610
+ quarantine_root.mkdir()
2611
+ temporary = quarantine_root / (
2612
+ f".{phase4_exit._TRANSACTION_CANONICAL_FILENAME}" f".publish-{'b' * 32}.tmp"
2613
+ )
2614
+ temporary.write_bytes(b'{"partial":')
2615
+
2616
+ report_code, report = _run_json(capsys, root)
2617
+ recover_code, recovered = _run_json(capsys, root, "--recover")
2618
+
2619
+ assert report_code == phase4_exit.EXIT_REFUSED
2620
+ assert report["status"] == "phase4-recovery-required"
2621
+ assert recover_code == phase4_exit.EXIT_REFUSED
2622
+ assert recovered["errors"][0]["code"] == "recovery-journal-invalid"
2623
+ assert temporary.read_bytes() == b'{"partial":'
2624
+
2625
+
2626
+ def test_closed_directory_validation_catches_member_added_after_walk(
2627
+ tmp_path: Path,
2628
+ monkeypatch: pytest.MonkeyPatch,
2629
+ ) -> None:
2630
+ quarantine_root = tmp_path / "quarantine"
2631
+ receipt_dir = quarantine_root / "receipt"
2632
+ receipt_dir.mkdir(parents=True)
2633
+ payload = receipt_dir / "payload.md"
2634
+ payload.write_bytes(b"owned\n")
2635
+ snapshot = phase4_exit._capture_snapshot(payload, receipt_dir, "payload")
2636
+ foreign = receipt_dir / "manual.txt"
2637
+ real_walk = phase4_exit.os.walk
2638
+ injected = False
2639
+
2640
+ def late_injecting_walk(*args: object, **kwargs: object):
2641
+ nonlocal injected
2642
+ yield from real_walk(*args, **kwargs)
2643
+ if not injected:
2644
+ injected = True
2645
+ foreign.write_bytes(b"manual owner\n")
2646
+
2647
+ monkeypatch.setattr(phase4_exit.os, "walk", late_injecting_walk)
2648
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
2649
+ phase4_exit._require_closed_transaction_directory(
2650
+ receipt_dir,
2651
+ quarantine_root,
2652
+ {"payload.md": snapshot},
2653
+ )
2654
+
2655
+ assert caught.value.code == "recovery-conflict"
2656
+ assert foreign.read_bytes() == b"manual owner\n"
2657
+ assert payload.read_bytes() == b"owned\n"
2658
+
2659
+
2660
+ def test_foreign_receipt_member_blocks_restore_without_deletion(
2661
+ tmp_path: Path,
2662
+ capsys: pytest.CaptureFixture[str],
2663
+ ) -> None:
2664
+ root, _, _, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2665
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2666
+ foreign = receipt_dir / "manual.txt"
2667
+ foreign.write_bytes(b"manual owner\n")
2668
+
2669
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
2670
+
2671
+ assert exit_code == phase4_exit.EXIT_REFUSED
2672
+ assert payload["errors"][-1]["code"] == "recovery-conflict"
2673
+ assert foreign.read_bytes() == b"manual owner\n"
2674
+
2675
+
2676
+ def test_quarantine_commit_rejects_same_bytes_replacement_payload_identity(
2677
+ tmp_path: Path,
2678
+ capsys: pytest.CaptureFixture[str],
2679
+ monkeypatch: pytest.MonkeyPatch,
2680
+ ) -> None:
2681
+ root, docs_root, document = _eligible_project(tmp_path)
2682
+ replacement_identity: tuple[int, int, int, int] | None = None
2683
+ replacement_path: Path | None = None
2684
+
2685
+ def replace_payload_before_final_validation(point: str) -> None:
2686
+ nonlocal replacement_identity, replacement_path
2687
+ if point != "quarantine-before-final-validation":
2688
+ return
2689
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
2690
+ receipt_dirs = [path for path in quarantine_root.iterdir() if path.is_dir()]
2691
+ assert len(receipt_dirs) == 1
2692
+ replacement_path = receipt_dirs[0] / phase4_exit.PAYLOAD_DIRNAME / document.name
2693
+ temporary = replacement_path.with_name("same-bytes-payload.tmp")
2694
+ temporary.write_bytes(replacement_path.read_bytes())
2695
+ temporary.replace(replacement_path)
2696
+ replacement_identity = phase4_exit._identity_from_stat(replacement_path.lstat())
2697
+
2698
+ monkeypatch.setattr(
2699
+ phase4_exit,
2700
+ "_transaction_fault",
2701
+ replace_payload_before_final_validation,
2702
+ )
2703
+
2704
+ exit_code, payload = _run_json(capsys, root, "--apply")
2705
+
2706
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
2707
+ assert payload["errors"][-1]["code"] == "quarantine-rollback-failed"
2708
+ assert not document.exists()
2709
+ assert (
2710
+ contract.read_json_strict(docs_root / contract.MANIFEST_FILENAME)["total"] == 1
2711
+ )
2712
+ assert replacement_path is not None and replacement_path.is_file()
2713
+ assert replacement_identity is not None
2714
+ assert (
2715
+ phase4_exit._identity_from_stat(replacement_path.lstat())
2716
+ == replacement_identity
2717
+ )
2718
+ assert _transaction_journals(docs_root)
2719
+
2720
+
2721
+ def test_postcommit_recovery_rejects_foreign_receipt_member(
2722
+ tmp_path: Path,
2723
+ capsys: pytest.CaptureFixture[str],
2724
+ monkeypatch: pytest.MonkeyPatch,
2725
+ ) -> None:
2726
+ root, docs_root, _ = _eligible_project(tmp_path)
2727
+ _crash_at(monkeypatch, "quarantine-manifest-committed")
2728
+
2729
+ with pytest.raises(_SimulatedCrash):
2730
+ phase4_exit.apply_quarantine(root)
2731
+
2732
+ journal_path = _transaction_journals(docs_root)[0]
2733
+ journal = contract.read_json_strict(journal_path)
2734
+ receipt_id = journal["quarantine"]["moves"][0]["receipt_id"]
2735
+ foreign = docs_root / phase4_exit.QUARANTINE_DIRNAME / receipt_id / "manual.txt"
2736
+ foreign.write_bytes(b"manual owner\n")
2737
+ exit_code, payload = _run_json(capsys, root, "--recover")
2738
+
2739
+ assert exit_code == phase4_exit.EXIT_REFUSED
2740
+ assert payload["errors"][0]["code"] == "recovery-conflict"
2741
+ assert foreign.read_bytes() == b"manual owner\n"
2742
+ assert journal_path.is_file()
2743
+
2744
+
2745
+ def test_postcommit_recovery_rejects_same_bytes_payload_identity_replacement(
2746
+ tmp_path: Path,
2747
+ capsys: pytest.CaptureFixture[str],
2748
+ monkeypatch: pytest.MonkeyPatch,
2749
+ ) -> None:
2750
+ root, docs_root, document = _eligible_project(tmp_path)
2751
+ _crash_at(monkeypatch, "quarantine-manifest-committed")
2752
+
2753
+ with pytest.raises(_SimulatedCrash):
2754
+ phase4_exit.apply_quarantine(root)
2755
+
2756
+ journal_path = _transaction_journals(docs_root)[0]
2757
+ journal = contract.read_json_strict(journal_path)
2758
+ move = journal["quarantine"]["moves"][0]
2759
+ payload_path = (
2760
+ docs_root
2761
+ / phase4_exit.QUARANTINE_DIRNAME
2762
+ / move["receipt_id"]
2763
+ / phase4_exit.PAYLOAD_DIRNAME
2764
+ / move["original_path"]
2765
+ )
2766
+ temporary = payload_path.with_name("same-bytes-payload.tmp")
2767
+ temporary.write_bytes(payload_path.read_bytes())
2768
+ temporary.replace(payload_path)
2769
+ replacement_identity = phase4_exit._identity_from_stat(payload_path.lstat())
2770
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2771
+
2772
+ exit_code, payload = _run_json(capsys, root, "--recover")
2773
+
2774
+ assert exit_code == phase4_exit.EXIT_REFUSED
2775
+ assert payload["errors"][0]["code"] == "recovery-conflict"
2776
+ assert not document.exists()
2777
+ assert payload_path.is_file()
2778
+ assert phase4_exit._identity_from_stat(payload_path.lstat()) == replacement_identity
2779
+ assert (
2780
+ contract.read_json_strict(docs_root / contract.MANIFEST_FILENAME)["total"] == 0
2781
+ )
2782
+ assert _transaction_journals(docs_root)
2783
+
2784
+
2785
+ def test_postcommit_recovery_never_populates_foreign_receipt_directory(
2786
+ tmp_path: Path,
2787
+ capsys: pytest.CaptureFixture[str],
2788
+ monkeypatch: pytest.MonkeyPatch,
2789
+ ) -> None:
2790
+ root, docs_root, _ = _eligible_project(tmp_path)
2791
+ _crash_at(monkeypatch, "quarantine-manifest-committed")
2792
+
2793
+ with pytest.raises(_SimulatedCrash):
2794
+ phase4_exit.apply_quarantine(root)
2795
+
2796
+ journal_path = _transaction_journals(docs_root)[0]
2797
+ journal = contract.read_json_strict(journal_path)
2798
+ receipt_id = journal["quarantine"]["moves"][0]["receipt_id"]
2799
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
2800
+ receipt_dir = quarantine_root / receipt_id
2801
+ displaced = quarantine_root / f"{receipt_id}.owned"
2802
+ receipt_dir.rename(displaced)
2803
+ receipt_dir.mkdir()
2804
+ foreign = receipt_dir / "manual.txt"
2805
+ foreign.write_bytes(b"manual owner\n")
2806
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2807
+
2808
+ exit_code, payload = _run_json(capsys, root, "--recover")
2809
+
2810
+ assert exit_code == phase4_exit.EXIT_REFUSED
2811
+ assert payload["errors"][-1]["code"] == "recovery-conflict"
2812
+ assert sorted(path.name for path in receipt_dir.iterdir()) == ["manual.txt"]
2813
+ assert foreign.read_bytes() == b"manual owner\n"
2814
+ assert (displaced / phase4_exit.RECEIPT_FILENAME).is_file()
2815
+ assert journal_path.is_file()
2816
+
2817
+
2818
+ def test_visible_manifest_with_unknown_durability_retains_journal(
2819
+ tmp_path: Path,
2820
+ capsys: pytest.CaptureFixture[str],
2821
+ monkeypatch: pytest.MonkeyPatch,
2822
+ ) -> None:
2823
+ root, docs_root, document = _eligible_project(tmp_path)
2824
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
2825
+ _fail_at(
2826
+ monkeypatch,
2827
+ "manifest-candidate-installed",
2828
+ OSError("injected manifest parent fsync failure"),
2829
+ )
2830
+
2831
+ exit_code, payload = _run_json(capsys, root, "--apply")
2832
+
2833
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
2834
+ assert payload["errors"][-1]["code"] == "manifest-durability-unknown"
2835
+ assert not document.exists()
2836
+ assert contract.read_json_strict(manifest_path)["total"] == 0
2837
+ assert len(_transaction_journals(docs_root)) == 2
2838
+
2839
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2840
+ recover_code, recovered = _run_json(capsys, root, "--recover")
2841
+ assert recover_code == phase4_exit.EXIT_OK, recovered
2842
+ assert recovered["recovery"]["outcome"] == "quarantine-finalized"
2843
+ assert _transaction_journals(docs_root) == []
2844
+
2845
+
2846
+ def test_recovery_rejects_same_path_journal_generation_replacement(
2847
+ tmp_path: Path,
2848
+ capsys: pytest.CaptureFixture[str],
2849
+ monkeypatch: pytest.MonkeyPatch,
2850
+ ) -> None:
2851
+ root, docs_root, _ = _eligible_project(tmp_path)
2852
+ _crash_at(monkeypatch, "quarantine-manifest-committed")
2853
+
2854
+ with pytest.raises(_SimulatedCrash):
2855
+ phase4_exit.apply_quarantine(root)
2856
+
2857
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2858
+ selected = phase4_exit._pending_transaction(root)
2859
+ assert selected is not None
2860
+ original_identity = phase4_exit._identity_from_stat(selected.path.lstat())
2861
+ original_bytes = selected.path.read_bytes()
2862
+ real_recover = phase4_exit._recover_quarantine_transaction
2863
+
2864
+ def replace_selected_generation(
2865
+ journal: phase4_exit.TransactionJournal,
2866
+ project_root: Path,
2867
+ project_docs: Path,
2868
+ ) -> str:
2869
+ outcome = real_recover(journal, project_root, project_docs)
2870
+ replacement = journal.path.with_name(f"{journal.path.name}.foreign")
2871
+ replacement.write_bytes(original_bytes)
2872
+ replacement.replace(journal.path)
2873
+ return outcome
2874
+
2875
+ monkeypatch.setattr(
2876
+ phase4_exit,
2877
+ "_recover_quarantine_transaction",
2878
+ replace_selected_generation,
2879
+ )
2880
+ exit_code, payload = _run_json(capsys, root, "--recover")
2881
+
2882
+ assert exit_code == phase4_exit.EXIT_REFUSED
2883
+ assert payload["errors"][-1]["code"] == "recovery-journal-conflict"
2884
+ assert selected.path.read_bytes() == original_bytes
2885
+ assert phase4_exit._identity_from_stat(selected.path.lstat()) != original_identity
2886
+ assert len(_transaction_journals(docs_root)) == 2
2887
+
2888
+
2889
+ def test_recovery_refuses_deleted_committed_manifest_without_after_artifact(
2890
+ tmp_path: Path,
2891
+ capsys: pytest.CaptureFixture[str],
2892
+ monkeypatch: pytest.MonkeyPatch,
2893
+ ) -> None:
2894
+ root, docs_root, document = _eligible_project(tmp_path)
2895
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
2896
+ _crash_at(monkeypatch, "manifest-candidate-installed")
2897
+
2898
+ with pytest.raises(_SimulatedCrash):
2899
+ phase4_exit.apply_quarantine(root)
2900
+
2901
+ assert not document.exists()
2902
+ assert contract.read_json_strict(manifest_path)["total"] == 0
2903
+ assert len(_transaction_journals(docs_root)) == 2
2904
+ manifest_path.unlink()
2905
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2906
+
2907
+ exit_code, payload = _run_json(capsys, root, "--recover")
2908
+
2909
+ assert exit_code == phase4_exit.EXIT_REFUSED
2910
+ assert payload["errors"][-1]["code"] == "recovery-conflict"
2911
+ assert not manifest_path.exists()
2912
+ assert not document.exists()
2913
+ assert len(_transaction_journals(docs_root)) == 2
2914
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
2915
+ receipt_dirs = [
2916
+ path
2917
+ for path in quarantine_root.iterdir()
2918
+ if path.is_dir() and not path.name.startswith(phase4_exit._ARCHIVE_PREFIX)
2919
+ ]
2920
+ assert len(receipt_dirs) == 1
2921
+
2922
+
2923
+ def test_recovery_rejects_same_bytes_with_different_restore_identity(
2924
+ tmp_path: Path,
2925
+ capsys: pytest.CaptureFixture[str],
2926
+ monkeypatch: pytest.MonkeyPatch,
2927
+ ) -> None:
2928
+ root, docs_root, document, apply_payload, _ = _apply_one(tmp_path, capsys)
2929
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2930
+ _crash_at(monkeypatch, "restore-copy-complete")
2931
+
2932
+ with pytest.raises(_SimulatedCrash):
2933
+ phase4_exit.restore_receipt(root, receipt_id)
2934
+
2935
+ replacement = document.with_name("same-bytes-replacement.tmp")
2936
+ replacement.write_bytes(document.read_bytes())
2937
+ replacement.replace(document)
2938
+ journal_path = _transaction_journals(docs_root)[0]
2939
+ exit_code, payload = _run_json(capsys, root, "--recover")
2940
+
2941
+ assert exit_code == phase4_exit.EXIT_REFUSED
2942
+ assert payload["errors"][0]["code"] == "recovery-conflict"
2943
+ assert document.is_file()
2944
+ assert journal_path.is_file()
2945
+
2946
+
2947
+ def test_recovery_rejects_same_bytes_with_different_payload_identity(
2948
+ tmp_path: Path,
2949
+ capsys: pytest.CaptureFixture[str],
2950
+ monkeypatch: pytest.MonkeyPatch,
2951
+ ) -> None:
2952
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2953
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2954
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
2955
+ payload_path = receipt_dir / receipt["quarantined_path"]
2956
+ _crash_at(monkeypatch, "restore-manifest-committed")
2957
+
2958
+ with pytest.raises(_SimulatedCrash):
2959
+ phase4_exit.restore_receipt(root, receipt_id)
2960
+
2961
+ replacement = payload_path.with_name("same-bytes-payload.tmp")
2962
+ replacement.write_bytes(payload_path.read_bytes())
2963
+ replacement.replace(payload_path)
2964
+ replacement_identity = phase4_exit._identity_from_stat(payload_path.lstat())
2965
+ journal_paths = _transaction_journals(docs_root)
2966
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
2967
+
2968
+ exit_code, payload = _run_json(capsys, root, "--recover")
2969
+
2970
+ assert exit_code == phase4_exit.EXIT_REFUSED
2971
+ assert payload["errors"][0]["code"] == "recovery-conflict"
2972
+ assert document.is_file()
2973
+ assert payload_path.is_file()
2974
+ assert phase4_exit._identity_from_stat(payload_path.lstat()) == replacement_identity
2975
+ assert _transaction_journals(docs_root) == journal_paths
2976
+
2977
+
2978
+ def test_restore_journal_cleanup_failure_retains_payload_without_staged_anchor(
2979
+ tmp_path: Path,
2980
+ capsys: pytest.CaptureFixture[str],
2981
+ monkeypatch: pytest.MonkeyPatch,
2982
+ ) -> None:
2983
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
2984
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
2985
+ receipt = contract.read_json_strict(receipt_dir / phase4_exit.RECEIPT_FILENAME)
2986
+ payload_path = receipt_dir / receipt["quarantined_path"]
2987
+ anchor_path = phase4_exit._restore_anchor_path(receipt_dir.parent, receipt_id)
2988
+
2989
+ def fail_cleanup(journal: phase4_exit.TransactionJournal) -> None:
2990
+ del journal
2991
+ raise phase4_exit.Phase4OperationalError(
2992
+ "recovery-journal-cleanup-failed",
2993
+ "injected journal cleanup failure",
2994
+ )
2995
+
2996
+ monkeypatch.setattr(phase4_exit, "_clear_transaction_journal", fail_cleanup)
2997
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
2998
+
2999
+ assert exit_code == phase4_exit.EXIT_OK, payload
3000
+ assert payload["warnings"]
3001
+ assert document.is_file()
3002
+ assert payload_path.is_file()
3003
+ assert not anchor_path.exists()
3004
+ target_identity = phase4_exit._identity_from_stat(document.lstat())
3005
+ payload_identity = phase4_exit._identity_from_stat(payload_path.lstat())
3006
+ assert target_identity != payload_identity
3007
+ if phase4_exit.os.name != "nt":
3008
+ retained_archives = [
3009
+ path
3010
+ for path in receipt_dir.parent.glob(f"{phase4_exit._ARCHIVE_PREFIX}*")
3011
+ if path.is_file()
3012
+ ]
3013
+ assert retained_archives
3014
+ assert all(
3015
+ phase4_exit._identity_from_stat(path.lstat()) != target_identity
3016
+ for path in retained_archives
3017
+ )
3018
+ assert len(_transaction_journals(docs_root)) == 3
3019
+
3020
+
3021
+ @pytest.mark.skipif(
3022
+ phase4_exit.os.name != "nt",
3023
+ reason="monkeypatches os.rename, which the POSIX renameat2 path never calls",
3024
+ )
3025
+ def test_tombstone_removal_never_unlinks_racing_foreign_replacement(
3026
+ tmp_path: Path,
3027
+ monkeypatch: pytest.MonkeyPatch,
3028
+ ) -> None:
3029
+ owned = tmp_path / "owned.txt"
3030
+ owned.write_bytes(b"owned\n")
3031
+ expected = phase4_exit._capture_snapshot(owned, tmp_path, "owned file")
3032
+ real_rename = phase4_exit.os.rename
3033
+
3034
+ def swap_before_detach(source: Path, destination: Path) -> None:
3035
+ source = Path(source)
3036
+ if source == owned:
3037
+ source.unlink()
3038
+ source.write_bytes(b"foreign\n")
3039
+ real_rename(source, destination)
3040
+
3041
+ monkeypatch.setattr(phase4_exit.os, "rename", swap_before_detach)
3042
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
3043
+ phase4_exit._remove_snapshot_file(
3044
+ owned,
3045
+ tmp_path,
3046
+ "owned file",
3047
+ expected,
3048
+ )
3049
+
3050
+ assert caught.value.code == "recovery-conflict"
3051
+ assert owned.read_bytes() == b"foreign\n"
3052
+ assert not list(tmp_path.glob(f"{phase4_exit._DETACHED_PREFIX}*"))
3053
+
3054
+
3055
+ def test_handle_bound_snapshot_rejects_pathname_aba_content_mix(
3056
+ tmp_path: Path,
3057
+ monkeypatch: pytest.MonkeyPatch,
3058
+ ) -> None:
3059
+ target = tmp_path / "target.txt"
3060
+ displaced = tmp_path / "displaced.txt"
3061
+ replacement = tmp_path / "replacement.txt"
3062
+ target.write_bytes(b"owned\n")
3063
+ replacement.write_bytes(b"foreign\n")
3064
+ real_read = phase4_exit._read_stable_regular_fd
3065
+
3066
+ def pathname_aba(fd: int, path: Path) -> tuple[bytes, os.stat_result]:
3067
+ target.rename(displaced)
3068
+ replacement.rename(target)
3069
+ try:
3070
+ return real_read(fd, path)
3071
+ finally:
3072
+ target.rename(replacement)
3073
+ displaced.rename(target)
3074
+
3075
+ monkeypatch.setattr(phase4_exit, "_read_stable_regular_fd", pathname_aba)
3076
+ snapshot, identity = phase4_exit._capture_snapshot_with_identity(
3077
+ target,
3078
+ tmp_path,
3079
+ "ABA target",
3080
+ )
3081
+
3082
+ assert snapshot == phase4_exit._text_snapshot("owned\n")
3083
+ assert identity == phase4_exit._identity_from_stat(target.lstat())
3084
+ assert replacement.read_bytes() == b"foreign\n"
3085
+
3086
+
3087
+ def test_identity_bound_detach_rejects_in_place_content_change(
3088
+ tmp_path: Path,
3089
+ monkeypatch: pytest.MonkeyPatch,
3090
+ ) -> None:
3091
+ owned = tmp_path / "owned.txt"
3092
+ owned.write_bytes(b"owned\n")
3093
+ expected = phase4_exit._capture_snapshot(owned, tmp_path, "owned file")
3094
+ real_rename = phase4_exit._rename_no_replace
3095
+
3096
+ def mutate_before_detach(source: Path, destination: Path) -> None:
3097
+ if Path(source) == owned:
3098
+ owned.write_bytes(b"foreign in-place edit\n")
3099
+ real_rename(source, destination)
3100
+
3101
+ monkeypatch.setattr(phase4_exit, "_rename_no_replace", mutate_before_detach)
3102
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
3103
+ phase4_exit._remove_snapshot_file(
3104
+ owned,
3105
+ tmp_path,
3106
+ "owned file",
3107
+ expected,
3108
+ )
3109
+
3110
+ assert caught.value.code == "recovery-conflict"
3111
+ assert owned.read_bytes() == b"foreign in-place edit\n"
3112
+ assert not list(tmp_path.glob(f"{phase4_exit._DETACHED_PREFIX}*"))
3113
+
3114
+
3115
+ def test_restore_in_place_target_write_preserves_quarantine_payload(
3116
+ tmp_path: Path,
3117
+ capsys: pytest.CaptureFixture[str],
3118
+ monkeypatch: pytest.MonkeyPatch,
3119
+ ) -> None:
3120
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
3121
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
3122
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
3123
+ receipt = contract.read_json_strict(receipt_path)
3124
+ payload_path = receipt_dir / receipt["quarantined_path"]
3125
+ payload_before = payload_path.read_bytes()
3126
+
3127
+ def mutate_target(point: str) -> None:
3128
+ if point == "restore-before-final-validation":
3129
+ document.write_text("concurrent in-place edit\n", encoding="utf-8")
3130
+
3131
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", mutate_target)
3132
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
3133
+
3134
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
3135
+ assert payload["errors"][-1]["code"] == "restore-rollback-failed"
3136
+ assert document.read_text(encoding="utf-8") == "concurrent in-place edit\n"
3137
+ assert payload_path.read_bytes() == payload_before
3138
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
3139
+ assert (
3140
+ contract.read_json_strict(docs_root / contract.MANIFEST_FILENAME)["total"] == 0
3141
+ )
3142
+ assert _transaction_journals(docs_root)
3143
+
3144
+ recover_code, recover_payload = _run_json(capsys, root, "--recover")
3145
+ assert recover_code == phase4_exit.EXIT_REFUSED
3146
+ assert recover_payload["errors"][-1]["code"] == "recovery-conflict"
3147
+ assert document.read_text(encoding="utf-8") == "concurrent in-place edit\n"
3148
+ assert payload_path.read_bytes() == payload_before
3149
+ assert _transaction_journals(docs_root)
3150
+
3151
+
3152
+ def test_ready_companion_race_is_never_overwritten(
3153
+ tmp_path: Path,
3154
+ capsys: pytest.CaptureFixture[str],
3155
+ monkeypatch: pytest.MonkeyPatch,
3156
+ ) -> None:
3157
+ root, docs_root, document = _eligible_project(tmp_path)
3158
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3159
+ ready_path = quarantine_root / phase4_exit._TRANSACTION_READY_FILENAME
3160
+ foreign = b'{"foreign":true}\n'
3161
+ real_publish = phase4_exit._publish_exclusive_snapshot
3162
+
3163
+ def race_ready_publication(
3164
+ path: Path,
3165
+ base: Path,
3166
+ description: str,
3167
+ snapshot: object,
3168
+ *,
3169
+ validator: object | None = None,
3170
+ staging_root: Path | None = None,
3171
+ staging_trusted_root: Path | None = None,
3172
+ ) -> phase4_exit.ExclusiveCopy:
3173
+ if description == "transaction journal ready companion":
3174
+ path.write_bytes(foreign)
3175
+ return real_publish(
3176
+ path,
3177
+ base,
3178
+ description,
3179
+ snapshot,
3180
+ validator=validator,
3181
+ staging_root=staging_root,
3182
+ staging_trusted_root=staging_trusted_root,
3183
+ )
3184
+
3185
+ monkeypatch.setattr(
3186
+ phase4_exit,
3187
+ "_publish_exclusive_snapshot",
3188
+ race_ready_publication,
3189
+ )
3190
+ exit_code, payload = _run_json(capsys, root, "--apply")
3191
+
3192
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
3193
+ assert payload["errors"][-1]["code"] == "quarantine-rollback-failed"
3194
+ assert document.is_file()
3195
+ assert ready_path.read_bytes() == foreign
3196
+ assert len(_transaction_journals(docs_root)) == 2
3197
+
3198
+
3199
+ def test_manifest_gap_race_preserves_foreign_canonical(
3200
+ tmp_path: Path,
3201
+ capsys: pytest.CaptureFixture[str],
3202
+ monkeypatch: pytest.MonkeyPatch,
3203
+ ) -> None:
3204
+ root, docs_root, document = _eligible_project(tmp_path)
3205
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
3206
+ foreign = '{"manual":true}\n'
3207
+
3208
+ def fill_manifest_gap(point: str) -> None:
3209
+ if point == "manifest-before-detached":
3210
+ manifest_path.write_text(foreign, encoding="utf-8")
3211
+
3212
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", fill_manifest_gap)
3213
+ exit_code, payload = _run_json(capsys, root, "--apply")
3214
+
3215
+ assert exit_code == phase4_exit.EXIT_OPERATIONAL_FAILURE
3216
+ assert payload["errors"][-1]["code"] == "quarantine-rollback-failed"
3217
+ assert manifest_path.read_text(encoding="utf-8") == foreign
3218
+ assert not document.exists()
3219
+ assert len(_transaction_journals(docs_root)) == 2
3220
+
3221
+
3222
+ @pytest.mark.parametrize(
3223
+ ("fault_point", "expected_outcome", "document_restored"),
3224
+ [
3225
+ ("manifest-before-anchor-staged", "quarantine-rolled-back", True),
3226
+ ("manifest-candidate-staged", "quarantine-rolled-back", True),
3227
+ ("manifest-before-detached", "quarantine-rolled-back", True),
3228
+ ("manifest-candidate-installed", "quarantine-finalized", False),
3229
+ ],
3230
+ )
3231
+ def test_manifest_cas_crash_points_are_recoverable(
3232
+ tmp_path: Path,
3233
+ capsys: pytest.CaptureFixture[str],
3234
+ monkeypatch: pytest.MonkeyPatch,
3235
+ fault_point: str,
3236
+ expected_outcome: str,
3237
+ document_restored: bool,
3238
+ ) -> None:
3239
+ root, docs_root, document = _eligible_project(tmp_path)
3240
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
3241
+ _crash_at(monkeypatch, fault_point)
3242
+
3243
+ with pytest.raises(_SimulatedCrash):
3244
+ phase4_exit.apply_quarantine(root)
3245
+
3246
+ assert len(_transaction_journals(docs_root)) == 2
3247
+ if fault_point == "manifest-before-detached":
3248
+ assert not manifest_path.exists()
3249
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
3250
+
3251
+ exit_code, payload = _run_json(capsys, root, "--recover")
3252
+
3253
+ assert exit_code == phase4_exit.EXIT_OK, payload
3254
+ assert payload["recovery"]["outcome"] == expected_outcome
3255
+ assert document.exists() is document_restored
3256
+ assert contract.load_manifest(docs_root)["total"] == int(document_restored)
3257
+ assert _transaction_journals(docs_root) == []
3258
+ assert not list(docs_root.glob(".phase4-manifest-*.tmp"))
3259
+
3260
+ second_code, second_payload = _run_json(capsys, root, "--recover")
3261
+ assert second_code == phase4_exit.EXIT_OK
3262
+ assert second_payload["status"] == "no-pending-transaction"
3263
+ assert second_payload["recovery"] == {"required": False, "recovered": False}
3264
+
3265
+
3266
+ def test_ready_alone_cleanup_residue_recovers_quarantine(
3267
+ tmp_path: Path,
3268
+ capsys: pytest.CaptureFixture[str],
3269
+ monkeypatch: pytest.MonkeyPatch,
3270
+ ) -> None:
3271
+ root, docs_root, document = _eligible_project(tmp_path)
3272
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3273
+ prepared_path = quarantine_root / phase4_exit._TRANSACTION_CANONICAL_FILENAME
3274
+ ready_path = quarantine_root / phase4_exit._TRANSACTION_READY_FILENAME
3275
+ _crash_at(monkeypatch, "journal-prepared-removed")
3276
+
3277
+ with pytest.raises(_SimulatedCrash):
3278
+ phase4_exit.apply_quarantine(root)
3279
+
3280
+ assert not prepared_path.exists()
3281
+ assert ready_path.is_file()
3282
+ assert not document.exists()
3283
+ assert contract.load_manifest(docs_root)["total"] == 0
3284
+
3285
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
3286
+ exit_code, payload = _run_json(capsys, root, "--recover")
3287
+
3288
+ assert exit_code == phase4_exit.EXIT_OK, payload
3289
+ assert payload["recovery"]["outcome"] == "quarantine-finalized"
3290
+ assert not ready_path.exists()
3291
+ assert _transaction_journals(docs_root) == []
3292
+
3293
+
3294
+ def test_ready_alone_cleanup_residue_recovers_restore(
3295
+ tmp_path: Path,
3296
+ capsys: pytest.CaptureFixture[str],
3297
+ monkeypatch: pytest.MonkeyPatch,
3298
+ ) -> None:
3299
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(
3300
+ tmp_path,
3301
+ capsys,
3302
+ )
3303
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
3304
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
3305
+ receipt = contract.read_json_strict(receipt_path)
3306
+ payload_path = receipt_dir / receipt["quarantined_path"]
3307
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3308
+ prepared_path = quarantine_root / phase4_exit._TRANSACTION_CANONICAL_FILENAME
3309
+ target_path = quarantine_root / phase4_exit._TRANSACTION_TARGET_FILENAME
3310
+ ready_path = quarantine_root / phase4_exit._TRANSACTION_READY_FILENAME
3311
+ anchor_path = phase4_exit._restore_anchor_path(quarantine_root, receipt_id)
3312
+ _crash_at(monkeypatch, "journal-prepared-removed")
3313
+
3314
+ with pytest.raises(_SimulatedCrash):
3315
+ phase4_exit.restore_receipt(root, receipt_id)
3316
+
3317
+ assert not prepared_path.exists()
3318
+ assert target_path.is_file()
3319
+ assert ready_path.is_file()
3320
+ assert document.is_file()
3321
+ assert payload_path.is_file()
3322
+ assert not anchor_path.exists()
3323
+ assert contract.load_manifest(docs_root)["total"] == 1
3324
+
3325
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
3326
+ exit_code, payload = _run_json(capsys, root, "--recover")
3327
+
3328
+ assert exit_code == phase4_exit.EXIT_OK, payload
3329
+ assert payload["recovery"]["outcome"] == "restore-finalized"
3330
+ assert contract.read_json_strict(receipt_path)["state"] == "restored"
3331
+ assert document.is_file()
3332
+ assert not payload_path.exists()
3333
+ assert not anchor_path.exists()
3334
+ assert not target_path.exists()
3335
+ assert not ready_path.exists()
3336
+ assert _transaction_journals(docs_root) == []
3337
+
3338
+
3339
+ def test_final_restore_validation_rejects_foreign_receipt_member(
3340
+ tmp_path: Path,
3341
+ capsys: pytest.CaptureFixture[str],
3342
+ monkeypatch: pytest.MonkeyPatch,
3343
+ ) -> None:
3344
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
3345
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
3346
+ receipt_path = receipt_dir / phase4_exit.RECEIPT_FILENAME
3347
+ receipt = contract.read_json_strict(receipt_path)
3348
+ payload_path = receipt_dir / receipt["quarantined_path"]
3349
+ foreign = receipt_dir / "manual.txt"
3350
+
3351
+ def add_foreign_member(point: str) -> None:
3352
+ if point == "restore-before-final-validation":
3353
+ foreign.write_bytes(b"manual owner\n")
3354
+
3355
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", add_foreign_member)
3356
+ exit_code, payload = _run_json(capsys, root, "--restore", receipt_id)
3357
+
3358
+ assert exit_code == phase4_exit.EXIT_REFUSED
3359
+ assert payload["errors"][-1]["code"] == "recovery-conflict"
3360
+ assert not document.exists()
3361
+ assert foreign.read_bytes() == b"manual owner\n"
3362
+ assert payload_path.is_file()
3363
+ assert contract.read_json_strict(receipt_path)["state"] == "quarantined"
3364
+ assert contract.load_manifest(docs_root)["total"] == 0
3365
+ assert _transaction_journals(docs_root) == []
3366
+
3367
+
3368
+ @pytest.mark.skipif(phase4_exit.os.name != "nt", reason="Windows directory API")
3369
+ def test_windows_directory_fsync_success_and_failure(
3370
+ tmp_path: Path,
3371
+ monkeypatch: pytest.MonkeyPatch,
3372
+ ) -> None:
3373
+ phase4_exit._fsync_directory(tmp_path)
3374
+ expected_identity = phase4_exit._identity_from_stat(tmp_path.lstat())
3375
+ calls: list[tuple[Path, tuple[int, int, int, int]]] = []
3376
+
3377
+ def fail_flush(
3378
+ directory: Path,
3379
+ identity: tuple[int, int, int, int],
3380
+ ) -> None:
3381
+ calls.append((Path(directory), identity))
3382
+ raise OSError("injected directory flush failure")
3383
+
3384
+ monkeypatch.setattr(phase4_exit, "_fsync_directory_windows", fail_flush)
3385
+ with pytest.raises(OSError, match="injected directory flush failure"):
3386
+ phase4_exit._fsync_directory(tmp_path)
3387
+
3388
+ assert calls == [(tmp_path, expected_identity)]
3389
+
3390
+
3391
+ @pytest.mark.skipif(phase4_exit.os.name != "nt", reason="Windows handle deletion")
3392
+ def test_handle_bound_delete_never_deletes_tombstone_replacement(
3393
+ tmp_path: Path,
3394
+ monkeypatch: pytest.MonkeyPatch,
3395
+ ) -> None:
3396
+ owned = tmp_path / "owned.txt"
3397
+ owned.write_bytes(b"owned\n")
3398
+ expected = phase4_exit._capture_snapshot(owned, tmp_path, "owned file")
3399
+ real_delete = phase4_exit._delete_regular_file_by_handle_windows
3400
+ replacements: list[tuple[Path, Path]] = []
3401
+
3402
+ def swap_detached_file(
3403
+ path: Path,
3404
+ identity: tuple[int, int, int, int],
3405
+ snapshot: Mapping[str, object],
3406
+ ) -> None:
3407
+ archived = path.with_name(f"{path.name}.owned")
3408
+ phase4_exit._rename_no_replace(path, archived)
3409
+ path.write_bytes(b"foreign\n")
3410
+ replacements.append((path, archived))
3411
+ real_delete(path, identity, snapshot)
3412
+
3413
+ monkeypatch.setattr(
3414
+ phase4_exit,
3415
+ "_delete_regular_file_by_handle_windows",
3416
+ swap_detached_file,
3417
+ )
3418
+ with pytest.raises(phase4_exit.Phase4OperationalError):
3419
+ phase4_exit._remove_snapshot_file(
3420
+ owned,
3421
+ tmp_path,
3422
+ "owned file",
3423
+ expected,
3424
+ )
3425
+
3426
+ foreign_path, archived_path = replacements[0]
3427
+ assert foreign_path.read_bytes() == b"foreign\n"
3428
+ assert archived_path.read_bytes() == b"owned\n"
3429
+ assert not owned.exists()
3430
+
3431
+
3432
+ @pytest.mark.skipif(phase4_exit.os.name != "nt", reason="Windows handle deletion")
3433
+ def test_handle_delete_rechecks_content_on_deletion_handle(
3434
+ tmp_path: Path,
3435
+ monkeypatch: pytest.MonkeyPatch,
3436
+ ) -> None:
3437
+ owned = tmp_path / "owned.txt"
3438
+ owned.write_bytes(b"owned\n")
3439
+ expected = phase4_exit._capture_snapshot(owned, tmp_path, "owned file")
3440
+ real_delete = phase4_exit._delete_regular_file_by_handle_windows
3441
+ tombstones: list[Path] = []
3442
+
3443
+ def mutate_detached_inode(
3444
+ path: Path,
3445
+ identity: tuple[int, int, int, int],
3446
+ snapshot: Mapping[str, object],
3447
+ ) -> None:
3448
+ path.write_bytes(b"foreign in-place edit\n")
3449
+ tombstones.append(path)
3450
+ real_delete(path, identity, snapshot)
3451
+
3452
+ monkeypatch.setattr(
3453
+ phase4_exit,
3454
+ "_delete_regular_file_by_handle_windows",
3455
+ mutate_detached_inode,
3456
+ )
3457
+ with pytest.raises(phase4_exit.Phase4OperationalError):
3458
+ phase4_exit._remove_snapshot_file(
3459
+ owned,
3460
+ tmp_path,
3461
+ "owned file",
3462
+ expected,
3463
+ )
3464
+
3465
+ assert not owned.exists()
3466
+ assert len(tombstones) == 1
3467
+ assert tombstones[0].read_bytes() == b"foreign in-place edit\n"
3468
+
3469
+
3470
+ @pytest.mark.skipif(phase4_exit.os.name != "nt", reason="Windows handle deletion")
3471
+ def test_detached_journal_cleanup_failure_blocks_later_runs(
3472
+ tmp_path: Path,
3473
+ capsys: pytest.CaptureFixture[str],
3474
+ monkeypatch: pytest.MonkeyPatch,
3475
+ ) -> None:
3476
+ root, docs_root, _ = _eligible_project(tmp_path)
3477
+ _crash_at(monkeypatch, "quarantine-journal-created")
3478
+ with pytest.raises(_SimulatedCrash):
3479
+ phase4_exit.apply_quarantine(root)
3480
+ journal = phase4_exit._pending_transaction(root)
3481
+ assert journal is not None
3482
+
3483
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
3484
+
3485
+ def fail_delete(
3486
+ path: Path,
3487
+ identity: tuple[int, int, int, int],
3488
+ snapshot: Mapping[str, object],
3489
+ ) -> None:
3490
+ del path, identity, snapshot
3491
+ raise OSError("injected handle deletion failure")
3492
+
3493
+ monkeypatch.setattr(
3494
+ phase4_exit,
3495
+ "_delete_regular_file_by_handle_windows",
3496
+ fail_delete,
3497
+ )
3498
+ with pytest.raises(phase4_exit.Phase4OperationalError):
3499
+ phase4_exit._clear_transaction_journal(journal)
3500
+
3501
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3502
+ detached = list(quarantine_root.glob(f"{phase4_exit._DETACHED_PREFIX}*"))
3503
+ assert len(detached) == 1
3504
+ exit_code, payload = _run_json(capsys, root)
3505
+ assert exit_code == phase4_exit.EXIT_REFUSED
3506
+ assert payload["status"] == "phase4-recovery-required"
3507
+ assert detached[0].is_file()
3508
+
3509
+
3510
+ @pytest.mark.skipif(phase4_exit.os.name != "nt", reason="Windows handle deletion")
3511
+ def test_handle_bound_directory_delete_retains_foreign_replacement(
3512
+ tmp_path: Path,
3513
+ monkeypatch: pytest.MonkeyPatch,
3514
+ ) -> None:
3515
+ quarantine_root = tmp_path / "quarantine"
3516
+ receipt_dir = quarantine_root / "receipt"
3517
+ payload_dir = receipt_dir / "document"
3518
+ payload_dir.mkdir(parents=True)
3519
+ payload = payload_dir / "orphan.md"
3520
+ payload.write_text("owned\n", encoding="utf-8")
3521
+ snapshot = phase4_exit._capture_snapshot(payload, receipt_dir, "payload")
3522
+ real_delete = phase4_exit._delete_empty_directory_by_handle_windows
3523
+ replacements: list[tuple[Path, Path]] = []
3524
+
3525
+ def swap_directory(
3526
+ path: Path,
3527
+ identity: tuple[int, int, int, int],
3528
+ ) -> None:
3529
+ if path.name == "document":
3530
+ archived = path.with_name("document.owned")
3531
+ phase4_exit._rename_no_replace(path, archived)
3532
+ path.mkdir()
3533
+ replacements.append((path, archived))
3534
+ real_delete(path, identity)
3535
+
3536
+ monkeypatch.setattr(
3537
+ phase4_exit,
3538
+ "_delete_empty_directory_by_handle_windows",
3539
+ swap_directory,
3540
+ )
3541
+ with pytest.raises(phase4_exit.Phase4Refusal) as caught:
3542
+ phase4_exit._safe_remove_transaction_directory(
3543
+ receipt_dir,
3544
+ quarantine_root,
3545
+ {"document/orphan.md": snapshot},
3546
+ )
3547
+
3548
+ assert caught.value.code == "recovery-conflict"
3549
+ foreign_path, archived_path = replacements[0]
3550
+ assert foreign_path.is_dir()
3551
+ assert archived_path.is_dir()
3552
+ assert not receipt_dir.exists()
3553
+
3554
+
3555
+ def test_posix_file_archive_is_moved_outside_receipt_closed_set(
3556
+ tmp_path: Path,
3557
+ ) -> None:
3558
+ quarantine_root = tmp_path / "quarantine"
3559
+ payload_dir = quarantine_root / "receipt" / phase4_exit.PAYLOAD_DIRNAME
3560
+ payload_dir.mkdir(parents=True)
3561
+ payload = payload_dir / "orphan.md"
3562
+ payload.write_text("owned\n", encoding="utf-8")
3563
+ identity = phase4_exit._identity_from_stat(payload.lstat())
3564
+
3565
+ phase4_exit._detach_and_remove_regular_file(
3566
+ payload,
3567
+ identity,
3568
+ "restored duplicate payload",
3569
+ archive_root=quarantine_root,
3570
+ is_windows=False,
3571
+ )
3572
+
3573
+ assert not payload.exists()
3574
+ assert list(payload_dir.glob(f"{phase4_exit._ARCHIVE_PREFIX}*")) == []
3575
+ archives = list(quarantine_root.glob(f"{phase4_exit._ARCHIVE_PREFIX}*.tmp"))
3576
+ assert len(archives) == 1
3577
+ assert archives[0].read_text(encoding="utf-8") == "owned\n"
3578
+
3579
+
3580
+ def test_restore_target_is_independent_from_payload_and_retained_archive(
3581
+ tmp_path: Path,
3582
+ ) -> None:
3583
+ docs_root = tmp_path / "project_docs"
3584
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3585
+ receipt_dir = quarantine_root / "receipt"
3586
+ receipt_dir.mkdir(parents=True)
3587
+ payload = receipt_dir / "orphan.md"
3588
+ payload.write_text("owned restore bytes\n", encoding="utf-8")
3589
+ payload_snapshot, payload_identity = phase4_exit._capture_snapshot_with_identity(
3590
+ payload,
3591
+ docs_root,
3592
+ "restore payload",
3593
+ )
3594
+ assert payload_identity is not None
3595
+
3596
+ anchor = quarantine_root / f"{phase4_exit._RESTORE_ANCHOR_PREFIX}test.tmp"
3597
+ staged = phase4_exit._write_exclusive_snapshot(
3598
+ anchor,
3599
+ quarantine_root,
3600
+ "restore staged target",
3601
+ payload_snapshot,
3602
+ )
3603
+ assert staged.identity != payload_identity
3604
+ target = docs_root / "orphan.md"
3605
+ created = phase4_exit._exclusive_copy_file(
3606
+ anchor,
3607
+ target,
3608
+ payload_snapshot["sha256"],
3609
+ staged.identity,
3610
+ archive_root=quarantine_root,
3611
+ archive_trusted_root=docs_root,
3612
+ )
3613
+
3614
+ target_identity = phase4_exit._identity_from_stat(target.lstat())
3615
+ assert created.identity == target_identity
3616
+ assert target_identity != payload_identity
3617
+ assert not anchor.exists()
3618
+ target_bytes = target.read_bytes()
3619
+ target_digest = contract.sha256_file(target)
3620
+
3621
+ phase4_exit._detach_and_remove_regular_file(
3622
+ payload,
3623
+ payload_identity,
3624
+ "restored duplicate payload",
3625
+ expected_snapshot=payload_snapshot,
3626
+ archive_root=quarantine_root,
3627
+ archive_trusted_root=docs_root,
3628
+ is_windows=False,
3629
+ )
3630
+
3631
+ archives = list(quarantine_root.glob(f"{phase4_exit._ARCHIVE_PREFIX}*.tmp"))
3632
+ assert len(archives) == 1
3633
+ assert phase4_exit._identity_from_stat(archives[0].lstat()) == payload_identity
3634
+ assert phase4_exit._identity_from_stat(archives[0].lstat()) != target_identity
3635
+ archives[0].write_bytes(b"mutated retained archive\n")
3636
+ assert target.read_bytes() == target_bytes
3637
+ assert contract.sha256_file(target) == target_digest
3638
+
3639
+
3640
+ def test_report_rejects_retained_archive_aliasing_active_manifest_document(
3641
+ tmp_path: Path,
3642
+ capsys: pytest.CaptureFixture[str],
3643
+ ) -> None:
3644
+ root, docs_root, document = _eligible_project(tmp_path)
3645
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3646
+ quarantine_root.mkdir()
3647
+ archive = quarantine_root / f"{phase4_exit._ARCHIVE_PREFIX}legacy.tmp"
3648
+ try:
3649
+ os.link(document, archive)
3650
+ except OSError as exc:
3651
+ pytest.skip(f"hard links are unavailable: {exc}")
3652
+
3653
+ exit_code, payload = _run_json(capsys, root)
3654
+
3655
+ assert exit_code == phase4_exit.EXIT_REFUSED
3656
+ assert payload["errors"][0]["code"] == "phase4-archive-active-alias"
3657
+ assert document.is_file()
3658
+ assert archive.is_file()
3659
+ assert phase4_exit._identity_from_stat(document.lstat())[:2] == (
3660
+ phase4_exit._identity_from_stat(archive.lstat())[:2]
3661
+ )
3662
+
3663
+
3664
+ def test_recovery_rejects_retained_archive_aliasing_restore_target(
3665
+ tmp_path: Path,
3666
+ capsys: pytest.CaptureFixture[str],
3667
+ monkeypatch: pytest.MonkeyPatch,
3668
+ ) -> None:
3669
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(tmp_path, capsys)
3670
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
3671
+ quarantine_root = receipt_dir.parent
3672
+ _crash_at(monkeypatch, "restore-copy-complete")
3673
+
3674
+ with pytest.raises(_SimulatedCrash):
3675
+ phase4_exit.restore_receipt(root, receipt_id)
3676
+
3677
+ archive = quarantine_root / f"{phase4_exit._ARCHIVE_PREFIX}legacy-target.tmp"
3678
+ try:
3679
+ os.link(document, archive)
3680
+ except OSError as exc:
3681
+ pytest.skip(f"hard links are unavailable: {exc}")
3682
+ journals_before = _transaction_journals(docs_root)
3683
+ monkeypatch.setattr(phase4_exit, "_transaction_fault", lambda point: None)
3684
+ exit_code, payload = _run_json(capsys, root, "--recover")
3685
+
3686
+ assert exit_code == phase4_exit.EXIT_REFUSED
3687
+ assert payload["errors"][0]["code"] == "phase4-archive-active-alias"
3688
+ assert document.is_file()
3689
+ assert archive.is_file()
3690
+ assert _transaction_journals(docs_root) == journals_before
3691
+
3692
+
3693
+ def test_posix_archive_accepts_sibling_source_under_shared_trusted_root(
3694
+ tmp_path: Path,
3695
+ ) -> None:
3696
+ docs_root = tmp_path / "project_docs"
3697
+ source_dir = docs_root / "subsystem"
3698
+ quarantine_root = docs_root / phase4_exit.QUARANTINE_DIRNAME
3699
+ source_dir.mkdir(parents=True)
3700
+ quarantine_root.mkdir()
3701
+ source = source_dir / "orphan.md"
3702
+ source.write_text("owned\n", encoding="utf-8")
3703
+ identity = phase4_exit._identity_from_stat(source.lstat())
3704
+
3705
+ phase4_exit._detach_and_remove_regular_file(
3706
+ source,
3707
+ identity,
3708
+ "quarantine source",
3709
+ archive_root=quarantine_root,
3710
+ archive_trusted_root=docs_root,
3711
+ is_windows=False,
3712
+ )
3713
+
3714
+ assert not source.exists()
3715
+ archives = list(quarantine_root.glob(f"{phase4_exit._ARCHIVE_PREFIX}*.tmp"))
3716
+ assert len(archives) == 1
3717
+ assert archives[0].read_text(encoding="utf-8") == "owned\n"
3718
+
3719
+
3720
+ @pytest.mark.skipif(
3721
+ phase4_exit.sys.platform not in ("linux", "darwin"),
3722
+ reason="POSIX no-replace archive policy",
3723
+ )
3724
+ def test_posix_apply_restore_and_repeat_restore_are_idempotent(
3725
+ tmp_path: Path,
3726
+ capsys: pytest.CaptureFixture[str],
3727
+ ) -> None:
3728
+ root, docs_root, document, apply_payload, receipt_dir = _apply_one(
3729
+ tmp_path,
3730
+ capsys,
3731
+ )
3732
+ receipt_id = apply_payload["quarantined"][0]["receipt_id"]
3733
+ receipt_before = contract.read_json_strict(
3734
+ receipt_dir / phase4_exit.RECEIPT_FILENAME
3735
+ )
3736
+
3737
+ restore_code, restored = _run_json(capsys, root, "--restore", receipt_id)
3738
+ repeat_code, repeated = _run_json(capsys, root, "--restore", receipt_id)
3739
+
3740
+ assert restore_code == phase4_exit.EXIT_OK, restored
3741
+ assert repeat_code == phase4_exit.EXIT_OK, repeated
3742
+ assert repeated["restored"]["no_op"] is True
3743
+ assert document.is_file()
3744
+ assert contract.sha256_file(document) == receipt_before["sha256"]
3745
+ assert not (receipt_dir / receipt_before["quarantined_path"]).exists()
3746
+ assert _transaction_journals(docs_root) == []
3747
+ assert list(receipt_dir.rglob(f"{phase4_exit._ARCHIVE_PREFIX}*")) == []
3748
+ assert list(
3749
+ (docs_root / phase4_exit.QUARANTINE_DIRNAME).glob(
3750
+ f"{phase4_exit._ARCHIVE_PREFIX}*"
3751
+ )
3752
+ )
3753
+
3754
+
3755
+ @pytest.mark.skipif(
3756
+ phase4_exit.sys.platform not in ("linux", "darwin"),
3757
+ reason="POSIX no-replace archive policy",
3758
+ )
3759
+ def test_posix_transaction_directory_cleanup_retains_closed_archive(
3760
+ tmp_path: Path,
3761
+ ) -> None:
3762
+ quarantine_root = tmp_path / "quarantine"
3763
+ receipt_dir = quarantine_root / "receipt"
3764
+ payload_dir = receipt_dir / "document"
3765
+ payload_dir.mkdir(parents=True)
3766
+ payload = payload_dir / "orphan.md"
3767
+ payload.write_text("owned\n", encoding="utf-8")
3768
+ snapshot = phase4_exit._capture_snapshot(payload, receipt_dir, "payload")
3769
+
3770
+ phase4_exit._safe_remove_transaction_directory(
3771
+ receipt_dir,
3772
+ quarantine_root,
3773
+ {"document/orphan.md": snapshot},
3774
+ )
3775
+
3776
+ assert not receipt_dir.exists()
3777
+ archives = list(quarantine_root.glob(f"{phase4_exit._ARCHIVE_PREFIX}*.dir"))
3778
+ assert len(archives) == 1
3779
+ assert (archives[0] / "document" / "orphan.md").read_text(
3780
+ encoding="utf-8"
3781
+ ) == "owned\n"
3782
+
3783
+
3784
+ def test_rename_no_replace_never_replaces_existing_destination(
3785
+ tmp_path: Path,
3786
+ ) -> None:
3787
+ source = tmp_path / "source.txt"
3788
+ destination = tmp_path / "destination.txt"
3789
+ source.write_text("source\n", encoding="utf-8")
3790
+ destination.write_text("destination\n", encoding="utf-8")
3791
+
3792
+ with pytest.raises(FileExistsError):
3793
+ phase4_exit._rename_no_replace(source, destination)
3794
+
3795
+ assert source.read_text(encoding="utf-8") == "source\n"
3796
+ assert destination.read_text(encoding="utf-8") == "destination\n"
3797
+
3798
+
3799
+ @pytest.mark.parametrize(
3800
+ "unsupported_errno",
3801
+ (
3802
+ phase4_exit.errno.ENOSYS,
3803
+ phase4_exit.errno.EINVAL,
3804
+ phase4_exit.errno.ENOTSUP,
3805
+ getattr(phase4_exit.errno, "EOPNOTSUPP", phase4_exit.errno.ENOTSUP),
3806
+ ),
3807
+ )
3808
+ def test_rename_errno_maps_unsupported_filesystem_to_typed_error(
3809
+ tmp_path: Path,
3810
+ unsupported_errno: int,
3811
+ ) -> None:
3812
+ destination = tmp_path / "destination.txt"
3813
+
3814
+ with pytest.raises(phase4_exit.NoReplaceRenameUnsupported) as caught:
3815
+ phase4_exit._raise_rename_errno(unsupported_errno, destination)
3816
+
3817
+ message = str(caught.value)
3818
+ assert "refusing to fall back to a replacing rename" in message
3819
+ assert caught.value.errno == phase4_exit.errno.ENOTSUP
3820
+
3821
+
3822
+ def test_rename_errno_keeps_conflict_and_plain_failures_distinct(
3823
+ tmp_path: Path,
3824
+ ) -> None:
3825
+ destination = tmp_path / "destination.txt"
3826
+
3827
+ with pytest.raises(FileExistsError):
3828
+ phase4_exit._raise_rename_errno(phase4_exit.errno.EEXIST, destination)
3829
+
3830
+ with pytest.raises(OSError) as caught:
3831
+ phase4_exit._raise_rename_errno(phase4_exit.errno.EACCES, destination)
3832
+
3833
+ assert not isinstance(caught.value, phase4_exit.NoReplaceRenameUnsupported)
3834
+
3835
+
3836
+ @pytest.mark.skipif(
3837
+ phase4_exit.os.name != "posix",
3838
+ reason="POSIX directory fsync branch",
3839
+ )
3840
+ def test_posix_directory_fsync_degrades_when_filesystem_refuses(
3841
+ tmp_path: Path,
3842
+ monkeypatch: pytest.MonkeyPatch,
3843
+ ) -> None:
3844
+ directory = tmp_path / "flushed"
3845
+ directory.mkdir()
3846
+ monkeypatch.setattr(phase4_exit, "_DEGRADED_DIRECTORY_FSYNC", [])
3847
+
3848
+ def refuse(fd: int) -> None:
3849
+ del fd
3850
+ raise OSError(phase4_exit.errno.EINVAL, "Invalid argument")
3851
+
3852
+ monkeypatch.setattr(phase4_exit.os, "fsync", refuse)
3853
+
3854
+ with pytest.warns(RuntimeWarning, match="durability is degraded"):
3855
+ phase4_exit._fsync_directory(directory)
3856
+
3857
+ degraded = phase4_exit.directory_fsync_degraded()
3858
+ assert len(degraded) == 1
3859
+ assert str(directory) in degraded[0]
3860
+
3861
+
3862
+ @pytest.mark.skipif(
3863
+ phase4_exit.os.name != "posix",
3864
+ reason="POSIX directory fsync branch",
3865
+ )
3866
+ def test_posix_directory_fsync_propagates_real_io_errors(
3867
+ tmp_path: Path,
3868
+ monkeypatch: pytest.MonkeyPatch,
3869
+ ) -> None:
3870
+ directory = tmp_path / "flushed"
3871
+ directory.mkdir()
3872
+ monkeypatch.setattr(phase4_exit, "_DEGRADED_DIRECTORY_FSYNC", [])
3873
+
3874
+ def fail(fd: int) -> None:
3875
+ del fd
3876
+ raise OSError(phase4_exit.errno.EIO, "Input/output error")
3877
+
3878
+ monkeypatch.setattr(phase4_exit.os, "fsync", fail)
3879
+
3880
+ with pytest.raises(OSError) as caught:
3881
+ phase4_exit._fsync_directory(directory)
3882
+
3883
+ assert caught.value.errno == phase4_exit.errno.EIO
3884
+ assert phase4_exit.directory_fsync_degraded() == ()
3885
+
3886
+
3887
+ @pytest.mark.skipif(
3888
+ phase4_exit.os.name != "posix",
3889
+ reason="POSIX directory fsync branch",
3890
+ )
3891
+ def test_posix_directory_fsync_success_path_is_silent(tmp_path: Path) -> None:
3892
+ directory = tmp_path / "flushed"
3893
+ directory.mkdir()
3894
+
3895
+ phase4_exit._fsync_directory(directory)