@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,3639 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Deterministic coordinator for the ``proj-doc-builder`` publish transaction.
3
+
4
+ The coordinator does not generate prose. It stages the current document tree,
5
+ mechanically normalizes only known marker corruption, runs all safety gates, and
6
+ publishes marker/CLAUDE/manifest/scan-state changes in a defined order. Dry-run
7
+ is the default; project files are changed only when ``--apply`` is explicit.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import base64
14
+ import concurrent.futures
15
+ import copy
16
+ import os
17
+ import posixpath
18
+ import shutil
19
+ import stat
20
+ import sys
21
+ import tempfile
22
+ import uuid
23
+ import warnings
24
+ from contextlib import contextmanager
25
+ from dataclasses import dataclass
26
+ from datetime import datetime, timezone
27
+ from enum import Enum
28
+ from pathlib import Path, PurePosixPath
29
+ from typing import Any, Mapping, Sequence
30
+
31
+ # Standalone CLI execution must not create project-local bytecode while loading
32
+ # sibling tools. This must be set before the first sibling import below.
33
+ sys.dont_write_bytecode = True
34
+
35
+ import claude_doc_index
36
+ import link_check
37
+ import normalize_markers
38
+ import phase4_exit
39
+ import project_docs_contract as contract
40
+ import scan_dirs
41
+ import validate_doc
42
+
43
+ RESULT_SCHEMA_VERSION = 1
44
+ EXIT_OK = 0
45
+ EXIT_GATE_FAILED = 1
46
+ EXIT_INPUT_ERROR = 2
47
+ EXIT_PUBLISH_FAILED = 3
48
+ SCAN_STATE_FILENAME = "_scan_state.json"
49
+ PUBLISH_JOURNAL_SCHEMA_VERSION = 2
50
+ PUBLISH_JOURNAL_KIND = "proj-doc-builder-publish-transaction"
51
+ _PUBLISH_JOURNAL_TEMP_MARKER = contract.COORDINATOR_TEMP_MARKER
52
+ _PUBLISH_ARTIFACT_ROOT_MARKER = contract.COORDINATOR_ARTIFACT_ROOT_MARKER
53
+ _PUBLISH_RETAINED_ARTIFACT_MARKER = contract.COORDINATOR_RETAINED_ARTIFACT_MARKER
54
+ _PUBLISH_HISTORY_MARKER = contract.COORDINATOR_HISTORY_MARKER
55
+
56
+
57
+ class SyncCoordinatorError(RuntimeError):
58
+ """Base class for stable coordinator failures."""
59
+
60
+
61
+ class SyncInputError(SyncCoordinatorError):
62
+ """The project or persisted input is unsafe, malformed, or incomplete."""
63
+
64
+
65
+ class PublishDisposition(str, Enum):
66
+ """Mutually exclusive durable disposition for a publication unit."""
67
+
68
+ NOT_ATTEMPTED = "not-attempted"
69
+ UNCHANGED = "unchanged"
70
+ INSTALLED = "installed"
71
+ NOT_INSTALLED = "not-installed"
72
+ PARTIALLY_INSTALLED = "partially-installed"
73
+ UNKNOWN = "unknown"
74
+
75
+
76
+ _PARTIAL_DISPOSITIONS = {
77
+ PublishDisposition.PARTIALLY_INSTALLED,
78
+ PublishDisposition.UNKNOWN,
79
+ }
80
+
81
+
82
+ def _set_component_disposition(
83
+ publish: dict[str, Any],
84
+ component: str,
85
+ disposition: PublishDisposition,
86
+ ) -> None:
87
+ """Set one component verdict and derive its legacy compatibility flags."""
88
+
89
+ if component not in {"manifest", "scan_state"}:
90
+ raise ValueError(f"unsupported publish component: {component}")
91
+ publish[f"{component}_disposition"] = disposition.value
92
+ if component == "manifest":
93
+ publish["manifest_commit_point"] = disposition is PublishDisposition.INSTALLED
94
+ publish["manifest_commit_ambiguous"] = disposition is PublishDisposition.UNKNOWN
95
+ else:
96
+ publish["scan_state_committed"] = disposition is PublishDisposition.INSTALLED
97
+ publish["scan_state_commit_ambiguous"] = (
98
+ disposition is PublishDisposition.UNKNOWN
99
+ )
100
+
101
+
102
+ def _set_transaction_disposition(
103
+ publish: dict[str, Any],
104
+ disposition: PublishDisposition,
105
+ ) -> None:
106
+ """Set the transaction verdict and derive the legacy partial flag."""
107
+
108
+ publish["disposition"] = disposition.value
109
+ publish["partial_commit"] = disposition in _PARTIAL_DISPOSITIONS
110
+
111
+
112
+ class SyncPublishError(SyncCoordinatorError):
113
+ """The publish transaction failed; ``result`` describes commit state."""
114
+
115
+ def __init__(self, message: str, result: dict[str, Any]) -> None:
116
+ super().__init__(message)
117
+ self.result = result
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class ProjectPaths:
122
+ root: Path
123
+ docs_root: Path
124
+ claude_path: Path
125
+ manifest_path: Path
126
+ scan_state_path: Path
127
+ root_identity: tuple[int, int]
128
+ docs_root_identity: tuple[int, int]
129
+
130
+
131
+ @dataclass
132
+ class PreparedSync:
133
+ paths: ProjectPaths
134
+ stage_docs: Path
135
+ run_timestamp: str
136
+ force_full: bool
137
+ original_documents: dict[str, str]
138
+ marker_contents: dict[str, str]
139
+ marker_details: list[dict[str, Any]]
140
+ original_claude: str
141
+ original_manifest_bytes: bytes | None
142
+ original_scan_state_bytes: bytes | None
143
+ previous_scan_state: dict[str, Any] | None
144
+ scan_candidate: dict[str, Any]
145
+ scan_commit_needed: bool
146
+ manifest: dict[str, Any]
147
+ manifest_changed: bool
148
+ current_manifest_generation: str | None
149
+ current_manifest_schema: int | None
150
+ claude_candidate: str
151
+ claude_changed: bool
152
+ validation: dict[str, Any]
153
+ links: dict[str, Any]
154
+ phase4: dict[str, Any]
155
+ warnings: list[Any]
156
+ errors: list[dict[str, str]]
157
+
158
+ @property
159
+ def gates_passed(self) -> bool:
160
+ return not self.errors
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class PublishArtifact:
165
+ path: Path
166
+ original: str
167
+ candidate: str
168
+ kind: str
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class LoadedPublishJournal:
173
+ journal: dict[str, Any]
174
+ raw: bytes
175
+ phase: str
176
+ path: Path
177
+
178
+
179
+ def _utc_now() -> str:
180
+ return datetime.now(timezone.utc).isoformat()
181
+
182
+
183
+ def _configure_stdio() -> None:
184
+ for stream in (sys.stdout, sys.stderr):
185
+ reconfigure = getattr(stream, "reconfigure", None)
186
+ if callable(reconfigure):
187
+ try:
188
+ reconfigure(encoding="utf-8", errors="strict")
189
+ except (AttributeError, OSError, ValueError):
190
+ pass
191
+
192
+
193
+ def _is_reparse(path: Path) -> bool:
194
+ try:
195
+ info = path.lstat()
196
+ except FileNotFoundError:
197
+ return False
198
+ except OSError as exc:
199
+ raise SyncInputError(f"cannot inspect path identity: {path}: {exc}") from exc
200
+ attributes = getattr(info, "st_file_attributes", 0)
201
+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
202
+ is_junction = getattr(path, "is_junction", None)
203
+ try:
204
+ junction = bool(callable(is_junction) and is_junction())
205
+ except OSError as exc:
206
+ raise SyncInputError(f"cannot inspect junction state: {path}: {exc}") from exc
207
+ return path.is_symlink() or junction or bool(attributes & reparse_flag)
208
+
209
+
210
+ def _stable_identity(info: os.stat_result, label: str) -> tuple[int, int]:
211
+ identity = (int(getattr(info, "st_dev", 0)), int(getattr(info, "st_ino", 0)))
212
+ if identity == (0, 0):
213
+ raise SyncInputError(f"{label} does not expose a stable filesystem identity")
214
+ return identity
215
+
216
+
217
+ def _require_regular_file(path: Path, label: str) -> None:
218
+ if _is_reparse(path):
219
+ raise SyncInputError(
220
+ f"{label} must not be a symlink, junction, or reparse point: {path}"
221
+ )
222
+ try:
223
+ resolved = path.resolve(strict=True)
224
+ except (OSError, RuntimeError) as exc:
225
+ raise SyncInputError(f"{label} cannot be resolved: {path}: {exc}") from exc
226
+ if not resolved.is_file():
227
+ raise SyncInputError(f"{label} is not a regular file: {path}")
228
+
229
+
230
+ def _project_paths(root_value: str | os.PathLike[str]) -> ProjectPaths:
231
+ supplied = Path(root_value)
232
+ lexical_root = Path(os.path.abspath(supplied))
233
+ try:
234
+ root_state = lexical_root.lstat()
235
+ root = lexical_root.resolve(strict=True)
236
+ except (OSError, RuntimeError) as exc:
237
+ raise SyncInputError(
238
+ f"project root cannot be resolved: {supplied}: {exc}"
239
+ ) from exc
240
+ if (
241
+ _is_reparse(lexical_root)
242
+ or not stat.S_ISDIR(root_state.st_mode)
243
+ or os.path.normcase(os.path.normpath(str(lexical_root)))
244
+ != os.path.normcase(os.path.normpath(str(root)))
245
+ ):
246
+ raise SyncInputError(
247
+ f"project root must be a direct real directory: {supplied}"
248
+ )
249
+ root_identity = _stable_identity(root_state, "project root")
250
+
251
+ lexical_docs = root / "project_docs"
252
+ try:
253
+ docs_state = lexical_docs.lstat()
254
+ docs_root = lexical_docs.resolve(strict=True)
255
+ except (OSError, RuntimeError) as exc:
256
+ raise SyncInputError(
257
+ f"project_docs cannot be resolved: {lexical_docs}: {exc}"
258
+ ) from exc
259
+ if (
260
+ _is_reparse(lexical_docs)
261
+ or not stat.S_ISDIR(docs_state.st_mode)
262
+ or docs_root.parent != root
263
+ or os.path.normcase(os.path.normpath(str(lexical_docs)))
264
+ != os.path.normcase(os.path.normpath(str(docs_root)))
265
+ ):
266
+ raise SyncInputError(
267
+ "project_docs must be a direct real directory under project root"
268
+ )
269
+ docs_root_identity = _stable_identity(docs_state, "project_docs")
270
+
271
+ claude_path = root / "CLAUDE.md"
272
+ _require_regular_file(claude_path, "root CLAUDE.md")
273
+ manifest_path = docs_root / contract.MANIFEST_FILENAME
274
+ scan_state_path = docs_root / SCAN_STATE_FILENAME
275
+ for optional_path, label in (
276
+ (manifest_path, "manifest"),
277
+ (scan_state_path, "scan state"),
278
+ ):
279
+ if os.path.lexists(optional_path) and _is_reparse(optional_path):
280
+ raise SyncInputError(
281
+ f"{label} must not be a link or reparse point: {optional_path}"
282
+ )
283
+ return ProjectPaths(
284
+ root,
285
+ docs_root,
286
+ claude_path,
287
+ manifest_path,
288
+ scan_state_path,
289
+ root_identity,
290
+ docs_root_identity,
291
+ )
292
+
293
+
294
+ def _optional_bytes_with_identity(
295
+ path: Path,
296
+ *,
297
+ label: str = "optional file",
298
+ require_single_link: bool = False,
299
+ ) -> tuple[bytes | None, tuple[int, int, int, int] | None]:
300
+ """Read one optional no-follow file and return its stable identity."""
301
+
302
+ try:
303
+ before = path.lstat()
304
+ except FileNotFoundError:
305
+ return None, None
306
+ except OSError as exc:
307
+ raise SyncInputError(f"cannot inspect {label} {path}: {exc}") from exc
308
+ if _is_reparse(path) or not stat.S_ISREG(before.st_mode):
309
+ raise SyncInputError(f"{label} must be direct and regular: {path}")
310
+
311
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
312
+ descriptor: int | None = None
313
+ try:
314
+ descriptor = os.open(path, flags)
315
+ opened = os.fstat(descriptor)
316
+ if not stat.S_ISREG(opened.st_mode):
317
+ raise SyncInputError(f"opened {label} is not a regular file: {path}")
318
+ before_identity = phase4_exit._identity_from_stat(before)
319
+ opened_identity = phase4_exit._identity_from_stat(opened)
320
+ if opened_identity != before_identity:
321
+ raise SyncInputError(f"{label} changed before open: {path}")
322
+ if require_single_link and (
323
+ int(getattr(before, "st_nlink", 1)) != 1
324
+ or int(getattr(opened, "st_nlink", 1)) != 1
325
+ ):
326
+ raise SyncInputError(f"{label} must have exactly one filesystem link: {path}")
327
+ chunks: list[bytes] = []
328
+ while True:
329
+ chunk = os.read(descriptor, 1024 * 1024)
330
+ if not chunk:
331
+ break
332
+ chunks.append(chunk)
333
+ final_opened = os.fstat(descriptor)
334
+ after = path.lstat()
335
+ except FileNotFoundError as exc:
336
+ raise SyncInputError(f"{label} disappeared while being read: {path}") from exc
337
+ except OSError as exc:
338
+ raise SyncInputError(f"cannot safely read {label} {path}: {exc}") from exc
339
+ finally:
340
+ if descriptor is not None:
341
+ os.close(descriptor)
342
+
343
+ final_identity = phase4_exit._identity_from_stat(final_opened)
344
+ after_identity = phase4_exit._identity_from_stat(after)
345
+ if (
346
+ opened_identity != final_identity
347
+ or opened_identity != after_identity
348
+ or opened.st_size != final_opened.st_size
349
+ or opened.st_size != after.st_size
350
+ or getattr(opened, "st_mtime_ns", None)
351
+ != getattr(final_opened, "st_mtime_ns", None)
352
+ or getattr(opened, "st_mtime_ns", None) != getattr(after, "st_mtime_ns", None)
353
+ or (
354
+ require_single_link
355
+ and (
356
+ int(getattr(final_opened, "st_nlink", 1)) != 1
357
+ or int(getattr(after, "st_nlink", 1)) != 1
358
+ )
359
+ )
360
+ ):
361
+ raise SyncInputError(f"{label} changed while being read: {path}")
362
+ raw = b"".join(chunks)
363
+ if len(raw) != opened.st_size:
364
+ raise SyncInputError(f"{label} size changed while being read: {path}")
365
+ return raw, opened_identity
366
+
367
+
368
+ def _optional_bytes(path: Path) -> bytes | None:
369
+ """Read an optional regular file without accepting path replacement."""
370
+
371
+ raw, _ = _optional_bytes_with_identity(path)
372
+ return raw
373
+
374
+
375
+ def _normalized_marker_files(
376
+ docs_root: Path,
377
+ ) -> tuple[dict[str, str], dict[str, str], list[dict[str, Any]]]:
378
+ changes = normalize_markers.collect_marker_changes(docs_root)
379
+ contents: dict[str, str] = {}
380
+ originals: dict[str, str] = {}
381
+ details: list[dict[str, Any]] = []
382
+ for change in changes:
383
+ prior = contents.get(change.path)
384
+ if prior is not None and prior != change.normalized_content:
385
+ raise SyncInputError(
386
+ f"inconsistent marker normalization candidates: {change.path}"
387
+ )
388
+ prior_original = originals.get(change.path)
389
+ if prior_original is not None and prior_original != change.original_content:
390
+ raise SyncInputError(f"inconsistent marker source snapshots: {change.path}")
391
+ contents[change.path] = change.normalized_content
392
+ originals[change.path] = change.original_content
393
+ details.append(
394
+ {
395
+ "path": change.path,
396
+ "line": change.line,
397
+ "before": change.before,
398
+ "after": change.after,
399
+ }
400
+ )
401
+ details.sort(key=lambda item: (item["path"], item["line"]))
402
+ return contents, originals, details
403
+
404
+
405
+ def _stage_documents(
406
+ docs_root: Path,
407
+ stage_docs: Path,
408
+ captured_docs: Path,
409
+ marker_contents: Mapping[str, str],
410
+ marker_originals: Mapping[str, str],
411
+ ) -> dict[str, str]:
412
+ if set(marker_contents) != set(marker_originals):
413
+ raise SyncInputError("marker candidate/source path sets are inconsistent")
414
+
415
+ original_documents: dict[str, str] = {}
416
+ discovered = link_check.discover_documents(docs_root)
417
+ for relative, _ in discovered:
418
+ content = contract.read_project_document(docs_root, relative)
419
+ marker_original = marker_originals.get(relative)
420
+ if marker_original is not None and content != marker_original:
421
+ raise SyncInputError(
422
+ f"marker source changed between collection and staging: {relative}"
423
+ )
424
+ original_documents[relative] = content
425
+ parts = PurePosixPath(relative).parts
426
+ captured_destination = captured_docs.joinpath(*parts)
427
+ captured_destination.parent.mkdir(parents=True, exist_ok=True)
428
+ captured_destination.write_bytes(content.encode("utf-8"))
429
+ staged = marker_contents.get(relative, content)
430
+ destination = stage_docs.joinpath(*parts)
431
+ destination.parent.mkdir(parents=True, exist_ok=True)
432
+ destination.write_bytes(staged.encode("utf-8"))
433
+
434
+ missing_candidates = set(marker_contents) - set(original_documents)
435
+ if missing_candidates:
436
+ raise SyncInputError(
437
+ f"marker candidate documents disappeared during staging: {sorted(missing_candidates)}"
438
+ )
439
+ return original_documents
440
+
441
+
442
+ def _load_current_manifest(
443
+ paths: ProjectPaths,
444
+ captured_bytes: bytes | None,
445
+ captured_docs: Path,
446
+ ) -> tuple[dict[str, Any] | None, list[str]]:
447
+ if captured_bytes is None:
448
+ return None, ["existing manifest is missing; apply will create schema v2"]
449
+ captured: list[str] = []
450
+ try:
451
+ try:
452
+ text = captured_bytes.decode("utf-8", errors="strict")
453
+ except UnicodeDecodeError as exc:
454
+ raise contract.StrictUtf8Error(
455
+ f"existing manifest is not strict UTF-8: {exc}"
456
+ ) from exc
457
+ value = contract.parse_json_strict(
458
+ text,
459
+ source=str(paths.manifest_path),
460
+ )
461
+ if not isinstance(value, Mapping):
462
+ raise contract.ManifestSchemaError("manifest JSON root must be an object")
463
+ with warnings.catch_warnings(record=True) as caught:
464
+ warnings.simplefilter("always")
465
+ manifest = contract.validate_manifest(
466
+ value,
467
+ captured_docs,
468
+ verify_files=True,
469
+ verify_complete_set=True,
470
+ )
471
+ captured.extend(str(item.message) for item in caught)
472
+ return manifest, captured
473
+ except contract.ManifestSchemaError as exc:
474
+ if "unsupported manifest schema_version" in str(exc):
475
+ raise SyncInputError(
476
+ f"existing manifest uses an unknown schema: {exc}"
477
+ ) from exc
478
+ captured.append(
479
+ f"existing manifest is invalid and will be rebuilt on apply: {exc}"
480
+ )
481
+ return None, captured
482
+ except contract.ProjectDocsContractError as exc:
483
+ captured.append(
484
+ f"existing manifest is invalid and will be rebuilt on apply: {exc}"
485
+ )
486
+ return None, captured
487
+
488
+
489
+ def _select_manifest(
490
+ paths: ProjectPaths,
491
+ stage_docs: Path,
492
+ run_timestamp: str,
493
+ current_manifest: Mapping[str, Any] | None,
494
+ current_manifest_bytes: bytes | None,
495
+ ) -> tuple[dict[str, Any], bool, str | None, int | None]:
496
+ candidate = contract.build_manifest(
497
+ stage_docs,
498
+ last_synced=run_timestamp,
499
+ docs_root_label=paths.docs_root.name,
500
+ )
501
+ current_generation: str | None = None
502
+ current_schema: int | None = None
503
+ if current_manifest is not None:
504
+ schema_value = current_manifest.get("schema_version")
505
+ current_schema = schema_value if type(schema_value) is int else None
506
+ if current_schema == contract.MANIFEST_SCHEMA_VERSION:
507
+ generation_value = current_manifest.get("generation_id")
508
+ current_generation = (
509
+ generation_value if isinstance(generation_value, str) else None
510
+ )
511
+ if current_generation == candidate["generation_id"]:
512
+ # Keep the prior non-volatile snapshot byte-for-byte. In particular,
513
+ # do not refresh last_synced on a zero-change run.
514
+ candidate = copy.deepcopy(dict(current_manifest))
515
+
516
+ candidate_bytes = contract.stable_json_dumps(candidate).encode("utf-8")
517
+ manifest_changed = current_manifest_bytes != candidate_bytes
518
+ contract.atomic_write_json(stage_docs / contract.MANIFEST_FILENAME, candidate)
519
+ contract.validate_manifest_v2(candidate, stage_docs, verify_files=True)
520
+ return candidate, manifest_changed, current_generation, current_schema
521
+
522
+
523
+ def _scan_candidate(
524
+ paths: ProjectPaths,
525
+ captured_scan_state_bytes: bytes | None,
526
+ *,
527
+ force_full: bool,
528
+ manifest_generation_id: str,
529
+ ) -> tuple[dict[str, Any] | None, dict[str, Any], bool]:
530
+ try:
531
+ previous = scan_dirs.parse_previous_state_bytes(
532
+ captured_scan_state_bytes,
533
+ source=str(paths.scan_state_path),
534
+ )
535
+ baseline_precondition = scan_dirs.baseline_precondition_from_bytes(
536
+ captured_scan_state_bytes,
537
+ source=str(paths.scan_state_path),
538
+ )
539
+ except (OSError, ValueError, contract.ProjectDocsContractError) as exc:
540
+ raise SyncInputError(f"committed scan state is invalid: {exc}") from exc
541
+ candidate = scan_dirs.build_candidate_state(
542
+ paths.root,
543
+ previous,
544
+ incremental=not force_full,
545
+ force_full=force_full,
546
+ baseline_precondition=baseline_precondition,
547
+ )
548
+ counts = candidate["change_counts"]
549
+ changed = (
550
+ previous is None
551
+ or previous.get("schema_version") != scan_dirs.SCAN_STATE_SCHEMA_VERSION
552
+ )
553
+ changed = changed or any(
554
+ counts[name] for name in ("new", "modified", "deleted", "unknown")
555
+ )
556
+ changed = changed or (
557
+ previous is None
558
+ or previous.get("manifest_generation_id") != manifest_generation_id
559
+ )
560
+ return previous, candidate, bool(changed)
561
+
562
+
563
+ def _strict_document_paths(scan_candidate: Mapping[str, Any]) -> set[str]:
564
+ baseline = scan_candidate.get("baseline", {})
565
+ if not isinstance(baseline, Mapping) or baseline.get("schema_version") != 2:
566
+ return set()
567
+ changes = scan_candidate.get("changes", {})
568
+ paths: set[str] = set()
569
+ if isinstance(changes, Mapping):
570
+ for name in ("new", "modified"):
571
+ values = changes.get(name, [])
572
+ if isinstance(values, list):
573
+ paths.update(
574
+ (f"{value}.md" if value else "index.md").casefold()
575
+ for value in values
576
+ if isinstance(value, str)
577
+ )
578
+ return paths
579
+
580
+
581
+ def _snapshot_directory_records(
582
+ scan_candidate: Mapping[str, Any],
583
+ ) -> list[dict[str, Any]]:
584
+ snapshot = scan_candidate.get("snapshot")
585
+ if not isinstance(snapshot, Mapping):
586
+ raise SyncInputError("scan candidate snapshot is missing")
587
+ records = snapshot.get("directories")
588
+ if not isinstance(records, list) or any(
589
+ not isinstance(item, Mapping) for item in records
590
+ ):
591
+ raise SyncInputError("scan candidate directory snapshot is malformed")
592
+ return [dict(item) for item in records]
593
+
594
+
595
+ def _stage_source_snapshot(
596
+ stage_root: Path,
597
+ scan_candidate: Mapping[str, Any],
598
+ ) -> set[str]:
599
+ """Materialize only names/inventories captured by the stable source scan."""
600
+
601
+ known_paths: set[str] = set()
602
+ for record in _snapshot_directory_records(scan_candidate):
603
+ relative = str(record["path"])
604
+ source_dir = stage_root.joinpath(*PurePosixPath(relative).parts)
605
+ source_dir.mkdir(parents=True, exist_ok=True)
606
+ known_paths.add(relative.casefold())
607
+ snapshot = record.get("snapshot")
608
+ if not isinstance(snapshot, Mapping):
609
+ raise SyncInputError(f"source snapshot is malformed: {relative}")
610
+ children = snapshot.get("child_directories", [])
611
+ files = snapshot.get("files", [])
612
+ if not isinstance(children, list) or not isinstance(files, list):
613
+ raise SyncInputError(f"source inventory is malformed: {relative}")
614
+ for child in children:
615
+ if not isinstance(child, str):
616
+ raise SyncInputError(f"source child name is malformed: {relative}")
617
+ (source_dir / child).mkdir(exist_ok=True)
618
+ for file_info in files:
619
+ if not isinstance(file_info, Mapping) or not isinstance(
620
+ file_info.get("name"), str
621
+ ):
622
+ raise SyncInputError(f"source file snapshot is malformed: {relative}")
623
+ source_file = source_dir / str(file_info["name"])
624
+ if source_file.exists() and source_file.is_dir():
625
+ raise SyncInputError(
626
+ f"source snapshot has a file/directory collision: {relative}"
627
+ )
628
+ source_file.write_bytes(b"")
629
+ return known_paths
630
+
631
+
632
+ def _phase4_source_inventory(
633
+ scan_candidate: Mapping[str, Any],
634
+ ) -> phase4_exit.SourceInventory:
635
+ records = _snapshot_directory_records(scan_candidate)
636
+ directories = {str(record["path"]) for record in records}
637
+ boundaries = {
638
+ str(record["path"]) for record in records if record.get("is_boundary") is True
639
+ }
640
+ snapshot = scan_candidate.get("snapshot")
641
+ unknown_value = (
642
+ snapshot.get("unknown_scopes", []) if isinstance(snapshot, Mapping) else []
643
+ )
644
+ if not isinstance(unknown_value, list) or any(
645
+ not isinstance(item, Mapping) for item in unknown_value
646
+ ):
647
+ raise SyncInputError("scan candidate unknown scopes are malformed")
648
+ unknown_scopes = tuple(dict(item) for item in unknown_value)
649
+ return phase4_exit.SourceInventory(
650
+ directories=directories,
651
+ boundaries=boundaries,
652
+ unknown_scopes=unknown_scopes,
653
+ frozen=True,
654
+ )
655
+
656
+
657
+ def _compact_failed_checks(result: Mapping[str, Any]) -> list[dict[str, Any]]:
658
+ checks = result.get("checks", [])
659
+ if not isinstance(checks, list):
660
+ return []
661
+ return [
662
+ {
663
+ "id": check.get("id"),
664
+ "name": check.get("name"),
665
+ "severity": check.get("severity"),
666
+ "detail": check.get("detail"),
667
+ }
668
+ for check in checks
669
+ if isinstance(check, Mapping) and check.get("result") == "FAIL"
670
+ ]
671
+
672
+
673
+ def _validate_documents(
674
+ source_snapshot_root: Path,
675
+ known_source_paths: set[str],
676
+ stage_docs: Path,
677
+ manifest: Mapping[str, Any],
678
+ scan_candidate: Mapping[str, Any],
679
+ ) -> tuple[dict[str, Any], list[dict[str, str]]]:
680
+ entries = [dict(entry) for entry in manifest["files"]]
681
+ by_folded_path = {entry["path"].casefold(): entry for entry in entries}
682
+ strict_paths = _strict_document_paths(scan_candidate)
683
+ blocking: list[dict[str, Any]] = []
684
+ audit_failures: list[dict[str, Any]] = []
685
+ skipped_missing_source: list[str] = []
686
+
687
+ for strict_path in sorted(strict_paths):
688
+ if strict_path not in by_folded_path:
689
+ blocking.append(
690
+ {
691
+ "path": strict_path,
692
+ "error_code": "changed-directory-document-missing",
693
+ "failed_checks": [],
694
+ }
695
+ )
696
+
697
+ def _validate_one(
698
+ entry: dict[str, Any],
699
+ ) -> tuple[str, bool, dict[str, Any] | None]:
700
+ relative = entry["path"]
701
+ source_relative = "" if relative.casefold() == "index.md" else relative[:-3]
702
+ if source_relative.casefold() not in known_source_paths:
703
+ return relative, True, None
704
+ source_dir = source_snapshot_root.joinpath(
705
+ *PurePosixPath(source_relative).parts
706
+ )
707
+ if not source_dir.is_dir():
708
+ raise SyncInputError(
709
+ f"frozen source snapshot is missing a known directory: {source_relative}"
710
+ )
711
+ staged_doc = stage_docs.joinpath(*PurePosixPath(relative).parts)
712
+ result = validate_doc.validate_doc(
713
+ staged_doc,
714
+ source_dir,
715
+ project_docs_dir=stage_docs,
716
+ project_root=source_snapshot_root,
717
+ )
718
+ summary = None
719
+ if result["failed"] or result["error_code"] is not None:
720
+ summary = {
721
+ "path": relative,
722
+ "profile": result["profile"],
723
+ "failed": result["failed"],
724
+ "critical_failed": result["critical_failed"],
725
+ "error_code": result["error_code"],
726
+ "error": result["error"],
727
+ "failed_checks": _compact_failed_checks(result),
728
+ }
729
+ return relative, False, summary
730
+
731
+ if len(entries) > 1:
732
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
733
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
734
+ validation_results = list(executor.map(_validate_one, entries))
735
+ else:
736
+ validation_results = [_validate_one(entry) for entry in entries]
737
+
738
+ for relative, is_skipped, summary in validation_results:
739
+ if is_skipped:
740
+ skipped_missing_source.append(relative)
741
+ continue
742
+ if summary is not None:
743
+ audit_failures.append(summary)
744
+ if relative.casefold() in strict_paths:
745
+ blocking.append(summary)
746
+
747
+ audit_failures.sort(key=lambda item: item["path"])
748
+ blocking.sort(key=lambda item: item["path"])
749
+ skipped_missing_source.sort()
750
+ report = {
751
+ "strict_mode_enabled": bool(strict_paths),
752
+ "strict_paths": sorted(strict_paths),
753
+ "checked": len(entries) - len(skipped_missing_source),
754
+ "audit_failure_count": len(audit_failures),
755
+ "audit_failures": audit_failures,
756
+ "blocking_failure_count": len(blocking),
757
+ "blocking_failures": blocking,
758
+ "skipped_missing_source": skipped_missing_source,
759
+ }
760
+ errors = [
761
+ {
762
+ "code": "changed-document-validation-failed",
763
+ "message": f"{item['path']} failed strict changed-document validation",
764
+ }
765
+ for item in blocking
766
+ ]
767
+ return report, errors
768
+
769
+
770
+ def _phase4_report(
771
+ source_snapshot_root: Path,
772
+ stage_docs: Path,
773
+ manifest: Mapping[str, Any],
774
+ source_inventory: phase4_exit.SourceInventory,
775
+ ) -> tuple[dict[str, Any], list[dict[str, str]], list[dict[str, str]]]:
776
+ # Bind Phase 4 to the same stable scanner inventory used by changed-document
777
+ # validation. It must not independently observe a transient live source tree.
778
+ analysis = phase4_exit.analyze_snapshot(
779
+ source_snapshot_root,
780
+ stage_docs,
781
+ dict(manifest),
782
+ source_inventory=source_inventory,
783
+ )
784
+ result = phase4_exit.analysis_result(analysis, action="report", mode="report-only")
785
+ errors = [dict(item) for item in result.get("errors", [])]
786
+ warnings: list[dict[str, str]] = []
787
+ counts = result.get("counts", {})
788
+ candidate_count = counts.get("candidates", 0) if isinstance(counts, Mapping) else 0
789
+ if type(candidate_count) is int and candidate_count > 0:
790
+ # Pending candidates must not deadlock the quarantine workflow: the
791
+ # reference-clearing document edits need a published manifest before
792
+ # ``phase4_exit --apply`` accepts the transaction. Documents, the
793
+ # CLAUDE index, and the manifest may still publish; only the scan
794
+ # baseline stays frozen until quarantine completes.
795
+ warnings.append(
796
+ {
797
+ "code": "phase4-candidates-pending",
798
+ "severity": "warning",
799
+ "message": (
800
+ f"{candidate_count} Phase 4 candidate(s) require a separate, "
801
+ "explicit quarantine decision before the scan baseline can advance"
802
+ ),
803
+ }
804
+ )
805
+ return result, errors, warnings
806
+
807
+
808
+ def _documents_unchanged(prepared: PreparedSync) -> None:
809
+ discovered = link_check.discover_documents(prepared.paths.docs_root)
810
+ current_paths = {relative for relative, _ in discovered}
811
+ expected_paths = set(prepared.original_documents)
812
+ if current_paths != expected_paths:
813
+ raise SyncInputError(
814
+ "document inventory changed during staging: "
815
+ f"added={sorted(current_paths - expected_paths)}, "
816
+ f"removed={sorted(expected_paths - current_paths)}"
817
+ )
818
+ for relative in sorted(expected_paths):
819
+ current = contract.read_project_document(prepared.paths.docs_root, relative)
820
+ if current != prepared.original_documents[relative]:
821
+ raise SyncInputError(f"document changed during staging: {relative}")
822
+
823
+
824
+ def _documents_match_candidate(prepared: PreparedSync) -> None:
825
+ discovered = link_check.discover_documents(prepared.paths.docs_root)
826
+ current_paths = {relative for relative, _ in discovered}
827
+ expected_paths = set(prepared.original_documents)
828
+ if current_paths != expected_paths:
829
+ raise SyncInputError(
830
+ "document inventory changed before manifest commit: "
831
+ f"added={sorted(current_paths - expected_paths)}, "
832
+ f"removed={sorted(expected_paths - current_paths)}"
833
+ )
834
+ for relative in sorted(expected_paths):
835
+ expected = prepared.marker_contents.get(
836
+ relative,
837
+ prepared.original_documents[relative],
838
+ )
839
+ current = contract.read_project_document(prepared.paths.docs_root, relative)
840
+ if current != expected:
841
+ raise SyncInputError(f"document changed before manifest commit: {relative}")
842
+
843
+
844
+ def _verify_committed_manifest(prepared: PreparedSync) -> None:
845
+ expected = contract.stable_json_dumps(prepared.manifest).encode("utf-8")
846
+ if _optional_bytes(prepared.paths.manifest_path) != expected:
847
+ raise SyncInputError(
848
+ "manifest commit point does not contain the prepared bytes"
849
+ )
850
+ loaded = contract.load_manifest(
851
+ prepared.paths.manifest_path,
852
+ docs_root=prepared.paths.docs_root,
853
+ verify_files=True,
854
+ verify_complete_set=True,
855
+ )
856
+ if loaded.get("generation_id") != prepared.manifest.get("generation_id"):
857
+ raise SyncInputError("manifest generation changed during commit verification")
858
+
859
+
860
+ def _source_snapshot_unchanged(prepared: PreparedSync) -> None:
861
+ fresh = scan_dirs.build_candidate_state(
862
+ prepared.paths.root,
863
+ prepared.previous_scan_state,
864
+ incremental=not prepared.force_full,
865
+ force_full=prepared.force_full,
866
+ )
867
+ if fresh["snapshot_fingerprint"] != prepared.scan_candidate["snapshot_fingerprint"]:
868
+ raise SyncInputError("source directory snapshot changed during staging")
869
+
870
+
871
+ def _require_directory_identity(
872
+ path: Path,
873
+ expected: tuple[int, int],
874
+ label: str,
875
+ ) -> None:
876
+ try:
877
+ info = path.lstat()
878
+ resolved = path.resolve(strict=True)
879
+ except (OSError, RuntimeError) as exc:
880
+ raise SyncInputError(f"cannot revalidate {label}: {path}: {exc}") from exc
881
+ if (
882
+ _is_reparse(path)
883
+ or not stat.S_ISDIR(info.st_mode)
884
+ or os.path.normcase(os.path.normpath(str(path)))
885
+ != os.path.normcase(os.path.normpath(str(resolved)))
886
+ or _stable_identity(info, label) != expected
887
+ ):
888
+ raise SyncInputError(f"{label} changed identity or became indirect: {path}")
889
+
890
+
891
+ def _revalidate_project_path_identities(paths: ProjectPaths) -> None:
892
+ _require_directory_identity(paths.root, paths.root_identity, "project root")
893
+ _require_directory_identity(
894
+ paths.docs_root,
895
+ paths.docs_root_identity,
896
+ "project_docs",
897
+ )
898
+ if paths.docs_root.parent != paths.root:
899
+ raise SyncInputError("project_docs parent changed during synchronization")
900
+
901
+
902
+ def _revalidate_persistent_path_types(paths: ProjectPaths) -> None:
903
+ _revalidate_project_path_identities(paths)
904
+ _require_regular_file(paths.claude_path, "root CLAUDE.md")
905
+ for optional_path, label in (
906
+ (paths.manifest_path, "manifest"),
907
+ (paths.scan_state_path, "scan state"),
908
+ ):
909
+ if not os.path.lexists(optional_path):
910
+ continue
911
+ if _is_reparse(optional_path):
912
+ raise SyncInputError(
913
+ f"{label} must not be a link or reparse point: {optional_path}"
914
+ )
915
+ try:
916
+ info = optional_path.lstat()
917
+ except OSError as exc:
918
+ raise SyncInputError(
919
+ f"cannot inspect {label}: {optional_path}: {exc}"
920
+ ) from exc
921
+ if not stat.S_ISREG(info.st_mode):
922
+ raise SyncInputError(f"{label} is not a regular file: {optional_path}")
923
+
924
+
925
+ def _persistent_inputs_unchanged(prepared: PreparedSync) -> None:
926
+ _revalidate_persistent_path_types(prepared.paths)
927
+ if contract.read_utf8(prepared.paths.claude_path) != prepared.original_claude:
928
+ raise SyncInputError("CLAUDE.md changed during staging")
929
+ if (
930
+ _optional_bytes(prepared.paths.manifest_path)
931
+ != prepared.original_manifest_bytes
932
+ ):
933
+ raise SyncInputError("manifest changed during staging")
934
+ if (
935
+ _optional_bytes(prepared.paths.scan_state_path)
936
+ != prepared.original_scan_state_bytes
937
+ ):
938
+ raise SyncInputError("scan state changed during staging")
939
+ _source_snapshot_unchanged(prepared)
940
+
941
+
942
+ def _atomic_text(path: Path, content: str) -> None:
943
+ contract.atomic_write_utf8(path, content)
944
+
945
+
946
+ def _atomic_json(path: Path, value: Mapping[str, Any]) -> None:
947
+ contract.atomic_write_json(path, dict(value))
948
+
949
+
950
+ def _publish_fault(point: str) -> None:
951
+ """测试故障注入点;生产运行不执行任何操作。"""
952
+
953
+ return None
954
+
955
+
956
+ @contextmanager
957
+ def _project_lock_preserving_primary(
958
+ root: Path,
959
+ *,
960
+ timeout: float,
961
+ secondary_errors: list[dict[str, str]] | None = None,
962
+ ) -> Any:
963
+ """Never let lock-release failure replace an in-flight publish failure."""
964
+
965
+ manager = contract.project_sync_lock(root, timeout=timeout)
966
+ manager.__enter__()
967
+ try:
968
+ yield
969
+ except BaseException as primary:
970
+ try:
971
+ manager.__exit__(type(primary), primary, primary.__traceback__)
972
+ except BaseException as release_exc:
973
+ if secondary_errors is not None:
974
+ secondary_errors.append(
975
+ {
976
+ "stage": "project-lock-release",
977
+ "error": str(release_exc),
978
+ }
979
+ )
980
+ add_note = getattr(primary, "add_note", None)
981
+ if callable(add_note):
982
+ add_note(f"project lock release also failed: {release_exc}")
983
+ raise
984
+ else:
985
+ manager.__exit__(None, None, None)
986
+
987
+
988
+ def _build_committed_scan_state(
989
+ candidate: Mapping[str, Any],
990
+ state_path: Path,
991
+ manifest_generation_id: str,
992
+ ) -> dict[str, Any]:
993
+ committed = copy.deepcopy(dict(candidate))
994
+ committed["state_role"] = "committed"
995
+ committed["committed_at"] = _utc_now()
996
+ committed["directories"] = copy.deepcopy(committed["snapshot"]["directories"])
997
+ committed["total"] = committed["full_total"]
998
+ committed.pop("candidate_path", None)
999
+ committed["state_path"] = state_path.name
1000
+ committed["manifest_generation_id"] = manifest_generation_id
1001
+ return scan_dirs.validate_scan_state_v2(committed)
1002
+
1003
+
1004
+ def _serialized_identity(
1005
+ identity: tuple[int, int, int, int],
1006
+ ) -> list[int]:
1007
+ return [int(component) for component in identity]
1008
+
1009
+
1010
+ def _decode_serialized_identity(
1011
+ value: Any,
1012
+ label: str,
1013
+ *,
1014
+ expected_file_type: int,
1015
+ ) -> tuple[int, int, int, int]:
1016
+ if (
1017
+ not isinstance(value, list)
1018
+ or len(value) != 4
1019
+ or any(type(component) is not int for component in value)
1020
+ ):
1021
+ raise SyncInputError(f"{label} must be a four-integer filesystem identity")
1022
+ identity = tuple(int(component) for component in value)
1023
+ if identity[0] < 0 or identity[1] <= 0:
1024
+ raise SyncInputError(f"{label} has no stable device/inode identity")
1025
+ if identity[2] != expected_file_type:
1026
+ raise SyncInputError(f"{label} has an unexpected filesystem object type")
1027
+ return identity
1028
+
1029
+
1030
+ def _bytes_snapshot(value: bytes | None) -> dict[str, Any]:
1031
+ return {
1032
+ "exists": value is not None,
1033
+ "sha256": contract.sha256_bytes(value) if value is not None else None,
1034
+ "base64": (
1035
+ base64.b64encode(value).decode("ascii") if value is not None else None
1036
+ ),
1037
+ }
1038
+
1039
+
1040
+ def _decode_bytes_snapshot(value: Any, label: str) -> bytes | None:
1041
+ if not isinstance(value, Mapping) or set(value) != {"exists", "sha256", "base64"}:
1042
+ raise SyncInputError(f"{label} snapshot has an invalid schema")
1043
+ exists = value.get("exists")
1044
+ digest = value.get("sha256")
1045
+ encoded = value.get("base64")
1046
+ if type(exists) is not bool:
1047
+ raise SyncInputError(f"{label}.exists must be a boolean")
1048
+ if not exists:
1049
+ if digest is not None or encoded is not None:
1050
+ raise SyncInputError(f"absent {label} snapshot cannot carry bytes")
1051
+ return None
1052
+ if not isinstance(digest, str) or len(digest) != 64:
1053
+ raise SyncInputError(f"{label}.sha256 is invalid")
1054
+ if not isinstance(encoded, str):
1055
+ raise SyncInputError(f"{label}.base64 is invalid")
1056
+ try:
1057
+ raw = base64.b64decode(encoded.encode("ascii"), validate=True)
1058
+ except (UnicodeEncodeError, ValueError) as exc:
1059
+ raise SyncInputError(f"{label}.base64 is invalid") from exc
1060
+ if contract.sha256_bytes(raw) != digest:
1061
+ raise SyncInputError(f"{label} snapshot hash does not match its bytes")
1062
+ return raw
1063
+
1064
+
1065
+ def _publish_journal_path(paths: ProjectPaths) -> Path:
1066
+ return contract.coordinator_publish_journal_paths(paths.root)["prepared"]
1067
+
1068
+
1069
+ def _publish_artifact_root_name(journal_path: Path, transaction_id: str) -> str:
1070
+ return f"{journal_path.stem}{_PUBLISH_ARTIFACT_ROOT_MARKER}{transaction_id}"
1071
+
1072
+
1073
+ def _publish_artifact_root(
1074
+ paths: ProjectPaths,
1075
+ journal: Mapping[str, Any],
1076
+ ) -> Path:
1077
+ transaction_id = journal.get("transaction_id")
1078
+ root_name = journal.get("artifact_root")
1079
+ if not isinstance(transaction_id, str) or not isinstance(root_name, str):
1080
+ raise SyncInputError("publish recovery journal has no artifact-root binding")
1081
+ expected = _publish_artifact_root_name(_publish_journal_path(paths), transaction_id)
1082
+ if root_name != expected or Path(root_name).name != root_name:
1083
+ raise SyncInputError("publish recovery journal artifact root is invalid")
1084
+ return _publish_journal_path(paths).parent / root_name
1085
+
1086
+
1087
+ def _filesystem_anchor(path: Path) -> Path:
1088
+ anchor = Path(path.anchor)
1089
+ if not anchor.is_dir():
1090
+ raise SyncInputError(f"filesystem anchor is unavailable: {anchor}")
1091
+ return anchor
1092
+
1093
+
1094
+ def _create_publish_artifact_root(
1095
+ paths: ProjectPaths,
1096
+ transaction_id: str,
1097
+ ) -> tuple[Path, tuple[int, int, int, int]]:
1098
+ """Create the CAS directory before publishing its immutable identity binding."""
1099
+
1100
+ journal_path = _publish_journal_path(paths)
1101
+ artifact_root = journal_path.parent / _publish_artifact_root_name(
1102
+ journal_path,
1103
+ transaction_id,
1104
+ )
1105
+ trusted_root = _filesystem_anchor(paths.root)
1106
+ try:
1107
+ parent_state = artifact_root.parent.lstat()
1108
+ root_state = paths.root.lstat()
1109
+ phase4_exit._validate_existing_components(
1110
+ trusted_root,
1111
+ artifact_root.parent,
1112
+ "coordinator journal directory",
1113
+ )
1114
+ if int(parent_state.st_dev) != int(root_state.st_dev):
1115
+ raise SyncInputError(
1116
+ "coordinator journal storage and project root must share a filesystem "
1117
+ "for identity-preserving publication"
1118
+ )
1119
+ artifact_root.mkdir(mode=0o700)
1120
+ phase4_exit._validate_existing_components(
1121
+ trusted_root,
1122
+ artifact_root,
1123
+ "coordinator artifact root",
1124
+ )
1125
+ info = artifact_root.lstat()
1126
+ except FileExistsError as exc:
1127
+ raise SyncInputError(
1128
+ f"coordinator artifact root already exists: {artifact_root}"
1129
+ ) from exc
1130
+ except (OSError, phase4_exit.Phase4Refusal) as exc:
1131
+ detail = exc.message if isinstance(exc, phase4_exit.Phase4Refusal) else str(exc)
1132
+ raise SyncInputError(
1133
+ f"cannot create coordinator artifact root: {detail}"
1134
+ ) from exc
1135
+ if _is_reparse(artifact_root) or not stat.S_ISDIR(info.st_mode):
1136
+ raise SyncInputError(
1137
+ f"coordinator artifact root is not a direct directory: {artifact_root}"
1138
+ )
1139
+ identity = phase4_exit._identity_from_stat(info)
1140
+ if identity[0] != int(root_state.st_dev) or identity[1] <= 0:
1141
+ raise SyncInputError(
1142
+ "coordinator artifact root has no stable same-filesystem identity"
1143
+ )
1144
+ _fsync_parent_directory(artifact_root.parent)
1145
+ return artifact_root, identity
1146
+
1147
+
1148
+ def _publish_artifact_root_expected_identity(
1149
+ journal: Mapping[str, Any],
1150
+ ) -> tuple[int, int, int, int]:
1151
+ return _decode_serialized_identity(
1152
+ journal.get("artifact_root_identity"),
1153
+ "publish recovery journal artifact_root_identity",
1154
+ expected_file_type=stat.S_IFDIR,
1155
+ )
1156
+
1157
+
1158
+ def _ensure_publish_artifact_root(
1159
+ paths: ProjectPaths,
1160
+ journal: Mapping[str, Any],
1161
+ ) -> Path:
1162
+ """Revalidate the exact transaction-owned CAS artifact directory."""
1163
+
1164
+ artifact_root = _publish_artifact_root(paths, journal)
1165
+ expected_identity = _publish_artifact_root_expected_identity(journal)
1166
+ trusted_root = _filesystem_anchor(paths.root)
1167
+ try:
1168
+ phase4_exit._validate_existing_components(
1169
+ trusted_root,
1170
+ artifact_root,
1171
+ "coordinator artifact root",
1172
+ )
1173
+ info = artifact_root.lstat()
1174
+ except (OSError, phase4_exit.Phase4Refusal) as exc:
1175
+ detail = exc.message if isinstance(exc, phase4_exit.Phase4Refusal) else str(exc)
1176
+ raise SyncInputError(
1177
+ f"cannot validate coordinator artifact root: {detail}"
1178
+ ) from exc
1179
+ if (
1180
+ _is_reparse(artifact_root)
1181
+ or not stat.S_ISDIR(info.st_mode)
1182
+ or phase4_exit._identity_from_stat(info) != expected_identity
1183
+ ):
1184
+ raise SyncInputError(
1185
+ f"coordinator artifact root identity changed: {artifact_root}"
1186
+ )
1187
+ return artifact_root
1188
+
1189
+
1190
+ def _phase4_text_snapshot(raw: bytes | None, label: str) -> dict[str, Any]:
1191
+ if raw is None:
1192
+ return phase4_exit._absent_snapshot()
1193
+ try:
1194
+ text = raw.decode("utf-8", errors="strict")
1195
+ except UnicodeDecodeError as exc:
1196
+ raise SyncInputError(f"{label} is not strict UTF-8") from exc
1197
+ return phase4_exit._text_snapshot(text)
1198
+
1199
+
1200
+ def _set_publish_path_state(
1201
+ path: Path,
1202
+ before: bytes | None,
1203
+ after: bytes | None,
1204
+ *,
1205
+ desired_after: bool,
1206
+ allow_both: bool,
1207
+ label: str,
1208
+ paths: ProjectPaths,
1209
+ artifact_root: Path,
1210
+ artifact_root_identity: tuple[int, int, int, int],
1211
+ ) -> None:
1212
+ """Publish or recover one exact snapshot through detach/no-replace CAS."""
1213
+
1214
+ before_snapshot = _phase4_text_snapshot(before, f"{label} preimage")
1215
+ after_snapshot = _phase4_text_snapshot(after, f"{label} postimage")
1216
+ desired = after_snapshot if desired_after else before_snapshot
1217
+ allowed = [before_snapshot, after_snapshot] if allow_both else [before_snapshot]
1218
+ try:
1219
+ phase4_exit._set_snapshot_state(
1220
+ path,
1221
+ paths.root,
1222
+ label,
1223
+ desired,
1224
+ allowed,
1225
+ archive_root=artifact_root,
1226
+ archive_trusted_root=_filesystem_anchor(paths.root),
1227
+ archive_root_expected_identity=artifact_root_identity,
1228
+ )
1229
+ except (phase4_exit.Phase4Refusal, phase4_exit.Phase4OperationalError) as exc:
1230
+ raise SyncInputError(f"{label} CAS refused [{exc.code}]: {exc.message}") from exc
1231
+ current = _optional_bytes(path)
1232
+ expected = after if desired_after else before
1233
+ if current != expected:
1234
+ raise SyncInputError(f"{label} CAS failed exact readback")
1235
+
1236
+
1237
+ def _read_publish_journal_bytes(path: Path) -> bytes | None:
1238
+ try:
1239
+ raw, _ = _optional_bytes_with_identity(
1240
+ path,
1241
+ label="publish journal",
1242
+ require_single_link=True,
1243
+ )
1244
+ return raw
1245
+ except SyncInputError as exc:
1246
+ raise SyncInputError(
1247
+ f"cannot safely read publish journal {path}: {exc}"
1248
+ ) from exc
1249
+
1250
+
1251
+ def _fsync_parent_directory(path: Path) -> None:
1252
+ """Persist directory namespace after mutation, identity-bound on all platforms."""
1253
+
1254
+ phase4_exit._fsync_directory(path)
1255
+
1256
+
1257
+ def _cleanup_publish_journal_temps(journal_path: Path) -> None:
1258
+ prefix = f"{journal_path.name}{_PUBLISH_JOURNAL_TEMP_MARKER}"
1259
+ try:
1260
+ entries = list(journal_path.parent.iterdir())
1261
+ except OSError as exc:
1262
+ raise SyncInputError(
1263
+ f"cannot inspect publish journal directory: {exc}"
1264
+ ) from exc
1265
+ residues: list[str] = []
1266
+ for entry in entries:
1267
+ if not entry.name.startswith(prefix) or not entry.name.endswith(".tmp"):
1268
+ continue
1269
+ if _is_reparse(entry):
1270
+ raise SyncInputError(f"publish journal temporary path is indirect: {entry}")
1271
+ try:
1272
+ info = entry.lstat()
1273
+ except OSError as exc:
1274
+ raise SyncInputError(
1275
+ f"cannot inspect publish journal temporary file: {entry}"
1276
+ ) from exc
1277
+ if not stat.S_ISREG(info.st_mode):
1278
+ raise SyncInputError(
1279
+ f"publish journal temporary path is not a file: {entry}"
1280
+ )
1281
+ residues.append(entry.name)
1282
+ if residues:
1283
+ raise SyncInputError(
1284
+ "unowned publish journal temporary residue requires audited recovery: "
1285
+ f"{sorted(residues)}"
1286
+ )
1287
+
1288
+
1289
+ def _publish_journal_exclusive(
1290
+ path: Path,
1291
+ value: Mapping[str, Any],
1292
+ ) -> tuple[dict[str, Any], bytes]:
1293
+ if _read_publish_journal_bytes(path) is not None:
1294
+ raise SyncInputError(f"a publish recovery journal already exists: {path}")
1295
+ _cleanup_publish_journal_temps(path)
1296
+ if "journal_identity" in value:
1297
+ raise SyncInputError("publish journal draft already contains journal_identity")
1298
+ temporary = path.with_name(
1299
+ f"{path.name}{_PUBLISH_JOURNAL_TEMP_MARKER}{uuid.uuid4().hex}.tmp"
1300
+ )
1301
+ flags = (
1302
+ os.O_WRONLY
1303
+ | os.O_CREAT
1304
+ | os.O_EXCL
1305
+ | getattr(os, "O_BINARY", 0)
1306
+ | getattr(os, "O_NOFOLLOW", 0)
1307
+ )
1308
+ descriptor: int | None = None
1309
+ try:
1310
+ descriptor = os.open(temporary, flags, 0o600)
1311
+ opened = os.fstat(descriptor)
1312
+ identity = phase4_exit._identity_from_stat(opened)
1313
+ if (
1314
+ identity[1] <= 0
1315
+ or identity[2] != stat.S_IFREG
1316
+ or int(getattr(opened, "st_nlink", 1)) != 1
1317
+ ):
1318
+ raise SyncInputError(
1319
+ "publish journal temporary file has no exclusive stable identity"
1320
+ )
1321
+ journal = dict(value)
1322
+ journal["journal_identity"] = _serialized_identity(identity)
1323
+ expected = contract.stable_json_dumps(journal).encode("utf-8")
1324
+ offset = 0
1325
+ while offset < len(expected):
1326
+ written = os.write(descriptor, expected[offset:])
1327
+ if written <= 0:
1328
+ raise OSError("short publish journal write")
1329
+ offset += written
1330
+ os.fsync(descriptor)
1331
+ final_opened = os.fstat(descriptor)
1332
+ if (
1333
+ phase4_exit._identity_from_stat(final_opened) != identity
1334
+ or int(getattr(final_opened, "st_nlink", 1)) != 1
1335
+ ):
1336
+ raise SyncInputError("publish journal temporary identity changed during write")
1337
+ os.close(descriptor)
1338
+ descriptor = None
1339
+ temporary_raw, temporary_identity = _optional_bytes_with_identity(
1340
+ temporary,
1341
+ label="publish journal temporary file",
1342
+ require_single_link=True,
1343
+ )
1344
+ if temporary_raw != expected or temporary_identity != identity:
1345
+ raise SyncInputError("publish journal temporary snapshot failed readback")
1346
+ try:
1347
+ phase4_exit._rename_no_replace(temporary, path)
1348
+ except FileExistsError as exc:
1349
+ raise SyncInputError(
1350
+ f"a concurrent publish recovery journal already exists: {path}"
1351
+ ) from exc
1352
+ except OSError as exc:
1353
+ raise SyncInputError(
1354
+ f"cannot publish coordinator journal without replacement: {exc}"
1355
+ ) from exc
1356
+ canonical_raw, canonical_identity = _optional_bytes_with_identity(
1357
+ path,
1358
+ label="canonical publish journal",
1359
+ require_single_link=True,
1360
+ )
1361
+ if canonical_raw != expected or canonical_identity != identity:
1362
+ raise SyncInputError("canonical publish journal failed exact readback")
1363
+ _fsync_parent_directory(path.parent)
1364
+ return journal, expected
1365
+ finally:
1366
+ if descriptor is not None:
1367
+ os.close(descriptor)
1368
+ if os.path.lexists(temporary):
1369
+ # Unknown/replaced residues are deliberately retained for audited
1370
+ # recovery. Remove only the exact inode this invocation created.
1371
+ try:
1372
+ current_raw, current_identity = _optional_bytes_with_identity(
1373
+ temporary,
1374
+ label="publish journal temporary cleanup",
1375
+ require_single_link=True,
1376
+ )
1377
+ if current_identity == locals().get("identity"):
1378
+ expected_snapshot = _phase4_text_snapshot(
1379
+ current_raw,
1380
+ "publish journal temporary cleanup",
1381
+ )
1382
+ phase4_exit._remove_snapshot_file(
1383
+ temporary,
1384
+ _filesystem_anchor(path),
1385
+ "publish journal temporary cleanup",
1386
+ expected_snapshot,
1387
+ expected_identity=current_identity,
1388
+ archive_root=temporary.parent,
1389
+ archive_trusted_root=_filesystem_anchor(path),
1390
+ )
1391
+ except BaseException:
1392
+ pass
1393
+
1394
+
1395
+ def _retained_publish_artifact_root(
1396
+ paths: ProjectPaths,
1397
+ journal: Mapping[str, Any],
1398
+ ) -> Path:
1399
+ transaction_id = str(journal["transaction_id"])
1400
+ prepared = contract.coordinator_publish_journal_paths(paths.root)["prepared"]
1401
+ return prepared.parent / (
1402
+ f"{prepared.stem}{_PUBLISH_RETAINED_ARTIFACT_MARKER}{transaction_id}"
1403
+ )
1404
+
1405
+
1406
+ def _publish_history_path(
1407
+ paths: ProjectPaths,
1408
+ journal: Mapping[str, Any],
1409
+ phase: str,
1410
+ ) -> Path:
1411
+ if phase not in {"committed", "rolled_back"}:
1412
+ raise SyncInputError(f"unsupported publish finalization phase: {phase}")
1413
+ transaction_id = str(journal["transaction_id"])
1414
+ prepared = contract.coordinator_publish_journal_paths(paths.root)["prepared"]
1415
+ return prepared.parent / (
1416
+ f"{prepared.stem}{_PUBLISH_HISTORY_MARKER}{transaction_id}-{phase}.json"
1417
+ )
1418
+
1419
+
1420
+ def _journal_expected_identity(
1421
+ journal: Mapping[str, Any],
1422
+ ) -> tuple[int, int, int, int]:
1423
+ return _decode_serialized_identity(
1424
+ journal.get("journal_identity"),
1425
+ "publish recovery journal journal_identity",
1426
+ expected_file_type=stat.S_IFREG,
1427
+ )
1428
+
1429
+
1430
+ def _capture_exact_publish_journal(
1431
+ path: Path,
1432
+ journal: Mapping[str, Any],
1433
+ expected: bytes,
1434
+ ) -> tuple[int, int, int, int]:
1435
+ raw, identity = _optional_bytes_with_identity(
1436
+ path,
1437
+ label="publish journal",
1438
+ require_single_link=True,
1439
+ )
1440
+ if raw != expected or identity is None:
1441
+ raise SyncInputError(f"publish journal changed before finalization: {path}")
1442
+ expected_identity = _journal_expected_identity(journal)
1443
+ if identity != expected_identity:
1444
+ raise SyncInputError(
1445
+ f"publish journal identity changed before finalization: {path}"
1446
+ )
1447
+ return identity
1448
+
1449
+
1450
+ def _transition_publish_journal(
1451
+ paths: ProjectPaths,
1452
+ journal: Mapping[str, Any],
1453
+ expected: bytes,
1454
+ phase: str,
1455
+ ) -> LoadedPublishJournal:
1456
+ """Atomically move prepared intent into an immutable outcome slot."""
1457
+
1458
+ slots = contract.coordinator_publish_journal_paths(paths.root)
1459
+ if phase not in {"committed", "rolled_back"}:
1460
+ raise SyncInputError(f"unsupported publish finalization phase: {phase}")
1461
+ source = slots["prepared"]
1462
+ destination = slots[phase]
1463
+ for other_phase, other_path in slots.items():
1464
+ if other_phase != "prepared" and os.path.lexists(other_path):
1465
+ raise SyncInputError(
1466
+ f"publish finalization slot is already occupied: {other_path}"
1467
+ )
1468
+ expected_identity = _capture_exact_publish_journal(source, journal, expected)
1469
+ _publish_fault(f"journal-finalize-{phase}-before-rename")
1470
+ try:
1471
+ phase4_exit._rename_no_replace(source, destination)
1472
+ except FileExistsError as exc:
1473
+ raise SyncInputError(
1474
+ f"publish finalization destination appeared concurrently: {destination}"
1475
+ ) from exc
1476
+ except OSError as exc:
1477
+ raise SyncInputError(f"cannot publish {phase} journal outcome: {exc}") from exc
1478
+ _publish_fault(f"journal-finalize-{phase}-after-rename")
1479
+ moved_identity = _capture_exact_publish_journal(destination, journal, expected)
1480
+ if moved_identity != expected_identity or os.path.lexists(source):
1481
+ raise SyncInputError(
1482
+ f"publish {phase} journal identity changed during transition"
1483
+ )
1484
+ _fsync_parent_directory(destination.parent)
1485
+ _publish_fault(f"journal-finalize-{phase}-durable")
1486
+ return LoadedPublishJournal(dict(journal), expected, phase, destination)
1487
+
1488
+
1489
+ def _retire_publish_artifact_root(
1490
+ paths: ProjectPaths,
1491
+ journal: Mapping[str, Any],
1492
+ ) -> dict[str, str] | None:
1493
+ """Delete an empty Windows CAS root or retain the exact directory elsewhere."""
1494
+
1495
+ active = _publish_artifact_root(paths, journal)
1496
+ retained = _retained_publish_artifact_root(paths, journal)
1497
+ expected_identity = _decode_serialized_identity(
1498
+ journal.get("artifact_root_identity"),
1499
+ "publish recovery journal artifact_root_identity",
1500
+ expected_file_type=stat.S_IFDIR,
1501
+ )
1502
+ trusted_root = _filesystem_anchor(paths.root)
1503
+
1504
+ if os.name == "nt":
1505
+ if os.path.lexists(retained):
1506
+ raise SyncInputError(
1507
+ f"unexpected retained Windows coordinator artifact root: {retained}"
1508
+ )
1509
+ if not os.path.lexists(active):
1510
+ return None
1511
+ artifact_root = _ensure_publish_artifact_root(paths, journal)
1512
+ try:
1513
+ members = list(artifact_root.iterdir())
1514
+ except OSError as exc:
1515
+ raise SyncInputError(
1516
+ f"cannot inspect coordinator artifact root before cleanup: {exc}"
1517
+ ) from exc
1518
+ if members:
1519
+ raise SyncInputError(
1520
+ "coordinator artifact root is not empty after transaction completion: "
1521
+ f"{sorted(member.name for member in members)}"
1522
+ )
1523
+ try:
1524
+ phase4_exit._delete_empty_directory_by_handle_windows(
1525
+ artifact_root,
1526
+ expected_identity,
1527
+ )
1528
+ except OSError as exc:
1529
+ raise SyncInputError(
1530
+ f"cannot delete exact coordinator artifact root: {exc}"
1531
+ ) from exc
1532
+ if os.path.lexists(artifact_root):
1533
+ raise SyncInputError(
1534
+ f"coordinator artifact root remained after cleanup: {artifact_root}"
1535
+ )
1536
+ _fsync_parent_directory(artifact_root.parent)
1537
+ return None
1538
+
1539
+ active_exists = os.path.lexists(active)
1540
+ retained_exists = os.path.lexists(retained)
1541
+ if active_exists and retained_exists:
1542
+ raise SyncInputError(
1543
+ "both active and retained coordinator artifact roots exist"
1544
+ )
1545
+ if retained_exists:
1546
+ try:
1547
+ phase4_exit._validate_existing_components(
1548
+ trusted_root,
1549
+ retained,
1550
+ "retained coordinator artifact root",
1551
+ )
1552
+ retained_identity = phase4_exit._identity_from_stat(retained.lstat())
1553
+ except (OSError, phase4_exit.Phase4Refusal) as exc:
1554
+ detail = exc.message if isinstance(exc, phase4_exit.Phase4Refusal) else str(exc)
1555
+ raise SyncInputError(
1556
+ f"cannot validate retained coordinator artifact root: {detail}"
1557
+ ) from exc
1558
+ if retained_identity != expected_identity:
1559
+ raise SyncInputError(
1560
+ "retained coordinator artifact root identity changed"
1561
+ )
1562
+ return {
1563
+ "kind": "coordinator-cas-artifacts",
1564
+ "path": retained.as_posix(),
1565
+ "reason": "identity-bound unlink is not portable on this platform",
1566
+ }
1567
+ if not active_exists:
1568
+ raise SyncInputError("coordinator artifact root disappeared before retention")
1569
+ artifact_root = _ensure_publish_artifact_root(paths, journal)
1570
+ try:
1571
+ phase4_exit._rename_no_replace(artifact_root, retained)
1572
+ except FileExistsError as exc:
1573
+ raise SyncInputError(
1574
+ f"retained coordinator artifact root appeared concurrently: {retained}"
1575
+ ) from exc
1576
+ except OSError as exc:
1577
+ raise SyncInputError(
1578
+ f"cannot retain coordinator artifact root safely: {exc}"
1579
+ ) from exc
1580
+ try:
1581
+ retained_identity = phase4_exit._identity_from_stat(retained.lstat())
1582
+ except OSError as exc:
1583
+ raise SyncInputError(
1584
+ f"cannot inspect retained coordinator artifact root: {exc}"
1585
+ ) from exc
1586
+ if retained_identity != expected_identity or os.path.lexists(artifact_root):
1587
+ raise SyncInputError(
1588
+ "coordinator artifact root identity changed during retention"
1589
+ )
1590
+ _fsync_parent_directory(retained.parent)
1591
+ return {
1592
+ "kind": "coordinator-cas-artifacts",
1593
+ "path": retained.as_posix(),
1594
+ "reason": "identity-bound unlink is not portable on this platform",
1595
+ }
1596
+
1597
+
1598
+ def _retire_publish_finalization_journal(
1599
+ paths: ProjectPaths,
1600
+ loaded: LoadedPublishJournal,
1601
+ ) -> Path:
1602
+ """Move the immutable outcome out of its fixed recovery slot, never unlink it."""
1603
+
1604
+ history = _publish_history_path(paths, loaded.journal, loaded.phase)
1605
+ expected_identity = _capture_exact_publish_journal(
1606
+ loaded.path,
1607
+ loaded.journal,
1608
+ loaded.raw,
1609
+ )
1610
+ if os.path.lexists(history):
1611
+ raise SyncInputError(f"publish history path already exists: {history}")
1612
+ _publish_fault("journal-finalize-before-history")
1613
+ try:
1614
+ phase4_exit._rename_no_replace(loaded.path, history)
1615
+ except FileExistsError as exc:
1616
+ raise SyncInputError(
1617
+ f"publish history appeared concurrently: {history}"
1618
+ ) from exc
1619
+ except OSError as exc:
1620
+ raise SyncInputError(f"cannot retain immutable publish history: {exc}") from exc
1621
+ _publish_fault("journal-finalize-after-history")
1622
+ history_identity = _capture_exact_publish_journal(
1623
+ history,
1624
+ loaded.journal,
1625
+ loaded.raw,
1626
+ )
1627
+ if history_identity != expected_identity or os.path.lexists(loaded.path):
1628
+ raise SyncInputError("publish journal identity changed during history retention")
1629
+ _fsync_parent_directory(history.parent)
1630
+ return history
1631
+
1632
+
1633
+ def _require_terminal_publish_state(
1634
+ paths: ProjectPaths,
1635
+ journal: Mapping[str, Any],
1636
+ phase: str,
1637
+ ) -> None:
1638
+ """Bind a terminal journal slot to the exact live project generation."""
1639
+
1640
+ if phase not in {"committed", "rolled_back"}:
1641
+ raise SyncInputError(f"unsupported terminal publish phase: {phase}")
1642
+ use_after = phase == "committed"
1643
+ _revalidate_project_path_identities(paths)
1644
+
1645
+ for artifact in _journal_artifacts(paths, journal):
1646
+ expected = (
1647
+ artifact.candidate.encode("utf-8")
1648
+ if use_after
1649
+ else artifact.original.encode("utf-8")
1650
+ )
1651
+ if _optional_bytes(artifact.path) != expected:
1652
+ raise SyncInputError(
1653
+ f"{phase} publish outcome does not match {artifact.kind}: "
1654
+ f"{artifact.path}"
1655
+ )
1656
+
1657
+ manifest = journal["manifest"]
1658
+ manifest_before = _decode_bytes_snapshot(manifest["before"], "manifest.before")
1659
+ manifest_after = _decode_bytes_snapshot(manifest["after"], "manifest.after")
1660
+ expected_manifest = manifest_after if use_after else manifest_before
1661
+ if _optional_bytes(paths.manifest_path) != expected_manifest:
1662
+ raise SyncInputError(
1663
+ f"{phase} publish outcome does not match the recorded manifest"
1664
+ )
1665
+
1666
+ scan = journal["scan_state"]
1667
+ scan_before = _decode_bytes_snapshot(scan["before"], "scan_state.before")
1668
+ scan_after = _decode_bytes_snapshot(scan["after"], "scan_state.after")
1669
+ expected_scan = scan_after if use_after and bool(scan["needed"]) else scan_before
1670
+ if _optional_bytes(paths.scan_state_path) != expected_scan:
1671
+ raise SyncInputError(
1672
+ f"{phase} publish outcome does not match the recorded scan state"
1673
+ )
1674
+
1675
+ if expected_manifest is not None:
1676
+ loaded_manifest = contract.load_manifest(
1677
+ paths.manifest_path,
1678
+ docs_root=paths.docs_root,
1679
+ verify_files=True,
1680
+ verify_complete_set=True,
1681
+ )
1682
+ if use_after and loaded_manifest.get("generation_id") != journal.get(
1683
+ "manifest_generation_id"
1684
+ ):
1685
+ raise SyncInputError(
1686
+ "committed publish outcome has an unexpected manifest generation"
1687
+ )
1688
+
1689
+ if expected_scan is not None:
1690
+ try:
1691
+ parsed_scan = scan_dirs.parse_previous_state_bytes(
1692
+ expected_scan,
1693
+ source=f"{phase} publish outcome scan state",
1694
+ )
1695
+ except (ValueError, contract.ProjectDocsContractError) as exc:
1696
+ raise SyncInputError(
1697
+ f"{phase} publish outcome scan state is invalid: {exc}"
1698
+ ) from exc
1699
+ if parsed_scan is None:
1700
+ raise SyncInputError(f"{phase} publish outcome scan state is absent")
1701
+ if use_after and bool(scan["needed"]):
1702
+ bindings = {
1703
+ "candidate_generation_id": journal["candidate_generation_id"],
1704
+ "snapshot_fingerprint": journal["source_snapshot_fingerprint"],
1705
+ "manifest_generation_id": journal["manifest_generation_id"],
1706
+ }
1707
+ for field, expected in bindings.items():
1708
+ if parsed_scan.get(field) != expected:
1709
+ raise SyncInputError(
1710
+ f"committed publish outcome scan-state {field} is inconsistent"
1711
+ )
1712
+
1713
+ if use_after:
1714
+ fresh_source = scan_dirs.build_candidate_state(paths.root)
1715
+ if (
1716
+ fresh_source.get("snapshot_fingerprint")
1717
+ != journal["source_snapshot_fingerprint"]
1718
+ ):
1719
+ raise SyncInputError(
1720
+ "source snapshot changed before committed journal finalization"
1721
+ )
1722
+ _revalidate_project_path_identities(paths)
1723
+
1724
+
1725
+
1726
+ def _finalize_publish_journal(
1727
+ paths: ProjectPaths,
1728
+ loaded: LoadedPublishJournal,
1729
+ ) -> dict[str, Any]:
1730
+ if loaded.phase not in {"committed", "rolled_back"}:
1731
+ raise SyncInputError("prepared publish journal cannot be finalized directly")
1732
+ _require_terminal_publish_state(paths, loaded.journal, loaded.phase)
1733
+ retained_artifact = _retire_publish_artifact_root(paths, loaded.journal)
1734
+ _cleanup_publish_journal_temps(_publish_journal_path(paths))
1735
+ history = _retire_publish_finalization_journal(paths, loaded)
1736
+ return {
1737
+ "phase": loaded.phase,
1738
+ "history": history.as_posix(),
1739
+ "retained_artifacts": (
1740
+ [retained_artifact] if retained_artifact is not None else []
1741
+ ),
1742
+ }
1743
+
1744
+
1745
+ def _build_publish_journal(
1746
+ prepared: PreparedSync,
1747
+ artifacts: Sequence[PublishArtifact],
1748
+ committed_scan_state: Mapping[str, Any] | None,
1749
+ transaction_id: str,
1750
+ artifact_root_identity: tuple[int, int, int, int],
1751
+ ) -> dict[str, Any]:
1752
+ artifact_records = []
1753
+ for artifact in artifacts:
1754
+ artifact_records.append(
1755
+ {
1756
+ "kind": artifact.kind,
1757
+ "path": artifact.path.relative_to(prepared.paths.root).as_posix(),
1758
+ "before": _bytes_snapshot(artifact.original.encode("utf-8")),
1759
+ "after": _bytes_snapshot(artifact.candidate.encode("utf-8")),
1760
+ }
1761
+ )
1762
+ manifest_after = contract.stable_json_dumps(prepared.manifest).encode("utf-8")
1763
+ scan_after = (
1764
+ contract.stable_json_dumps(dict(committed_scan_state)).encode("utf-8")
1765
+ if committed_scan_state is not None
1766
+ else None
1767
+ )
1768
+ journal_path = _publish_journal_path(prepared.paths)
1769
+ return {
1770
+ "schema_version": PUBLISH_JOURNAL_SCHEMA_VERSION,
1771
+ "kind": PUBLISH_JOURNAL_KIND,
1772
+ "transaction_id": transaction_id,
1773
+ "artifact_root": _publish_artifact_root_name(journal_path, transaction_id),
1774
+ "artifact_root_identity": _serialized_identity(artifact_root_identity),
1775
+ "created_at": _utc_now(),
1776
+ "root_identity": list(prepared.paths.root_identity),
1777
+ "docs_root_identity": list(prepared.paths.docs_root_identity),
1778
+ "artifacts": artifact_records,
1779
+ "manifest": {
1780
+ "changed": prepared.manifest_changed,
1781
+ "before": _bytes_snapshot(prepared.original_manifest_bytes),
1782
+ "after": _bytes_snapshot(manifest_after),
1783
+ },
1784
+ "scan_state": {
1785
+ "needed": prepared.scan_commit_needed,
1786
+ "before": _bytes_snapshot(prepared.original_scan_state_bytes),
1787
+ "after": _bytes_snapshot(scan_after),
1788
+ },
1789
+ "manifest_generation_id": prepared.manifest["generation_id"],
1790
+ "source_snapshot_fingerprint": prepared.scan_candidate["snapshot_fingerprint"],
1791
+ "candidate_generation_id": prepared.scan_candidate["candidate_generation_id"],
1792
+ }
1793
+
1794
+
1795
+ def _validate_publish_journal(paths: ProjectPaths, value: Any) -> dict[str, Any]:
1796
+ required = {
1797
+ "schema_version",
1798
+ "kind",
1799
+ "transaction_id",
1800
+ "journal_identity",
1801
+ "artifact_root",
1802
+ "artifact_root_identity",
1803
+ "created_at",
1804
+ "root_identity",
1805
+ "docs_root_identity",
1806
+ "artifacts",
1807
+ "manifest",
1808
+ "scan_state",
1809
+ "manifest_generation_id",
1810
+ "source_snapshot_fingerprint",
1811
+ "candidate_generation_id",
1812
+ }
1813
+ if not isinstance(value, Mapping) or set(value) != required:
1814
+ raise SyncInputError("publish recovery journal has an invalid schema")
1815
+ data = dict(value)
1816
+ if (
1817
+ data.get("schema_version") != PUBLISH_JOURNAL_SCHEMA_VERSION
1818
+ or data.get("kind") != PUBLISH_JOURNAL_KIND
1819
+ ):
1820
+ raise SyncInputError("publish recovery journal version or kind is unsupported")
1821
+ transaction_id = data.get("transaction_id")
1822
+ if not isinstance(transaction_id, str):
1823
+ raise SyncInputError("publish recovery journal transaction_id is invalid")
1824
+ try:
1825
+ parsed_transaction_id = uuid.UUID(transaction_id)
1826
+ except ValueError as exc:
1827
+ raise SyncInputError(
1828
+ "publish recovery journal transaction_id is invalid"
1829
+ ) from exc
1830
+ if parsed_transaction_id.version != 4 or str(parsed_transaction_id) != transaction_id:
1831
+ raise SyncInputError("publish recovery journal transaction_id is not canonical UUID4")
1832
+ expected_artifact_root = _publish_artifact_root_name(
1833
+ _publish_journal_path(paths),
1834
+ transaction_id,
1835
+ )
1836
+ if data.get("artifact_root") != expected_artifact_root:
1837
+ raise SyncInputError("publish recovery journal artifact_root is invalid")
1838
+ _decode_serialized_identity(
1839
+ data.get("journal_identity"),
1840
+ "publish recovery journal journal_identity",
1841
+ expected_file_type=stat.S_IFREG,
1842
+ )
1843
+ _decode_serialized_identity(
1844
+ data.get("artifact_root_identity"),
1845
+ "publish recovery journal artifact_root_identity",
1846
+ expected_file_type=stat.S_IFDIR,
1847
+ )
1848
+ created_at = data.get("created_at")
1849
+ if not isinstance(created_at, str):
1850
+ raise SyncInputError("publish recovery journal created_at is invalid")
1851
+ try:
1852
+ parsed_created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
1853
+ except ValueError as exc:
1854
+ raise SyncInputError("publish recovery journal created_at is invalid") from exc
1855
+ if parsed_created_at.tzinfo is None:
1856
+ raise SyncInputError(
1857
+ "publish recovery journal created_at must include a timezone"
1858
+ )
1859
+ if data.get("root_identity") != list(paths.root_identity) or data.get(
1860
+ "docs_root_identity"
1861
+ ) != list(paths.docs_root_identity):
1862
+ raise SyncInputError(
1863
+ "publish recovery journal belongs to another filesystem identity"
1864
+ )
1865
+ for field in (
1866
+ "manifest_generation_id",
1867
+ "source_snapshot_fingerprint",
1868
+ "candidate_generation_id",
1869
+ ):
1870
+ digest = data.get(field)
1871
+ if (
1872
+ not isinstance(digest, str)
1873
+ or len(digest) != 64
1874
+ or any(character not in "0123456789abcdef" for character in digest)
1875
+ ):
1876
+ raise SyncInputError(f"publish recovery journal {field} is invalid")
1877
+
1878
+ artifacts = data.get("artifacts")
1879
+ if not isinstance(artifacts, list):
1880
+ raise SyncInputError("publish recovery journal artifacts must be a list")
1881
+ seen: set[str] = set()
1882
+ for index, item in enumerate(artifacts):
1883
+ if not isinstance(item, Mapping) or set(item) != {
1884
+ "kind",
1885
+ "path",
1886
+ "before",
1887
+ "after",
1888
+ }:
1889
+ raise SyncInputError(f"publish recovery artifact {index} is invalid")
1890
+ kind = item.get("kind")
1891
+ relative = item.get("path")
1892
+ if kind not in {"marker", "claude-index"} or not isinstance(relative, str):
1893
+ raise SyncInputError(
1894
+ f"publish recovery artifact {index} has invalid metadata"
1895
+ )
1896
+ folded_relative = relative.casefold()
1897
+ if folded_relative in seen:
1898
+ raise SyncInputError(
1899
+ f"publish recovery artifact path is duplicated: {relative}"
1900
+ )
1901
+ seen.add(folded_relative)
1902
+ if kind == "claude-index":
1903
+ if relative != "CLAUDE.md":
1904
+ raise SyncInputError("CLAUDE recovery artifact path is invalid")
1905
+ else:
1906
+ prefix = "project_docs/"
1907
+ if not relative.startswith(prefix):
1908
+ raise SyncInputError("marker recovery artifact path is invalid")
1909
+ contract.validate_manifest_relative_path(relative[len(prefix) :])
1910
+ artifact_before = _decode_bytes_snapshot(
1911
+ item.get("before"),
1912
+ f"artifact[{index}].before",
1913
+ )
1914
+ artifact_after = _decode_bytes_snapshot(
1915
+ item.get("after"),
1916
+ f"artifact[{index}].after",
1917
+ )
1918
+ if artifact_before is None:
1919
+ raise SyncInputError("publish recovery artifacts must have a preimage")
1920
+ if artifact_after is None:
1921
+ raise SyncInputError("publish recovery artifacts must have a candidate")
1922
+ if artifact_before == artifact_after:
1923
+ raise SyncInputError(
1924
+ "publish recovery artifact candidate equals its preimage"
1925
+ )
1926
+
1927
+ manifest = data.get("manifest")
1928
+ if not isinstance(manifest, Mapping) or set(manifest) != {
1929
+ "changed",
1930
+ "before",
1931
+ "after",
1932
+ }:
1933
+ raise SyncInputError("publish recovery manifest snapshot is invalid")
1934
+ if type(manifest.get("changed")) is not bool:
1935
+ raise SyncInputError("publish recovery manifest changed flag is invalid")
1936
+ manifest_before = _decode_bytes_snapshot(manifest.get("before"), "manifest.before")
1937
+ manifest_after = _decode_bytes_snapshot(manifest.get("after"), "manifest.after")
1938
+ if manifest_after is None:
1939
+ raise SyncInputError("publish recovery manifest candidate is absent")
1940
+ if bool(manifest.get("changed")) != (manifest_before != manifest_after):
1941
+ raise SyncInputError("publish recovery manifest changed flag is inconsistent")
1942
+ try:
1943
+ manifest_value = contract.parse_json_strict(
1944
+ manifest_after.decode("utf-8", errors="strict"),
1945
+ source="publish recovery journal manifest.after",
1946
+ )
1947
+ validated_manifest = contract.validate_manifest_v2(
1948
+ manifest_value,
1949
+ paths.docs_root,
1950
+ verify_files=False,
1951
+ verify_complete_set=False,
1952
+ )
1953
+ except (
1954
+ UnicodeDecodeError,
1955
+ contract.ProjectDocsContractError,
1956
+ ) as exc:
1957
+ raise SyncInputError(
1958
+ f"publish recovery manifest candidate is invalid: {exc}"
1959
+ ) from exc
1960
+ if validated_manifest.get("generation_id") != data["manifest_generation_id"]:
1961
+ raise SyncInputError(
1962
+ "publish recovery manifest generation disagrees with journal metadata"
1963
+ )
1964
+
1965
+ scan_state = data.get("scan_state")
1966
+ if not isinstance(scan_state, Mapping) or set(scan_state) != {
1967
+ "needed",
1968
+ "before",
1969
+ "after",
1970
+ }:
1971
+ raise SyncInputError("publish recovery scan-state snapshot is invalid")
1972
+ if type(scan_state.get("needed")) is not bool:
1973
+ raise SyncInputError("publish recovery scan-state needed flag is invalid")
1974
+ scan_before = _decode_bytes_snapshot(scan_state.get("before"), "scan_state.before")
1975
+ scan_after = _decode_bytes_snapshot(scan_state.get("after"), "scan_state.after")
1976
+ if bool(scan_state.get("needed")) != (scan_after is not None):
1977
+ raise SyncInputError("publish recovery scan-state candidate is inconsistent")
1978
+ if bool(scan_state.get("needed")) and scan_before == scan_after:
1979
+ raise SyncInputError(
1980
+ "publish recovery scan-state candidate equals its preimage"
1981
+ )
1982
+ if scan_after is not None:
1983
+ try:
1984
+ parsed_scan_after = scan_dirs.parse_previous_state_bytes(
1985
+ scan_after,
1986
+ source="publish recovery journal scan_state.after",
1987
+ )
1988
+ except (ValueError, contract.ProjectDocsContractError) as exc:
1989
+ raise SyncInputError(
1990
+ f"publish recovery scan-state candidate is invalid: {exc}"
1991
+ ) from exc
1992
+ if parsed_scan_after is None:
1993
+ raise SyncInputError("publish recovery scan-state candidate is absent")
1994
+ bindings = {
1995
+ "candidate_generation_id": data["candidate_generation_id"],
1996
+ "snapshot_fingerprint": data["source_snapshot_fingerprint"],
1997
+ "manifest_generation_id": data["manifest_generation_id"],
1998
+ }
1999
+ for field, expected_binding in bindings.items():
2000
+ if parsed_scan_after.get(field) != expected_binding:
2001
+ raise SyncInputError(
2002
+ f"publish recovery scan-state {field} binding is inconsistent"
2003
+ )
2004
+ return data
2005
+
2006
+
2007
+ def _load_publish_journal(paths: ProjectPaths) -> LoadedPublishJournal | None:
2008
+ slots = contract.coordinator_publish_journal_paths(paths.root)
2009
+ found: list[tuple[str, Path, bytes, tuple[int, int, int, int]]] = []
2010
+ for phase, path in slots.items():
2011
+ raw, identity = _optional_bytes_with_identity(
2012
+ path,
2013
+ label=f"{phase} publish journal",
2014
+ require_single_link=True,
2015
+ )
2016
+ if raw is not None:
2017
+ if identity is None:
2018
+ raise SyncInputError(f"{phase} publish journal has no identity")
2019
+ found.append((phase, path, raw, identity))
2020
+ if len(found) > 1:
2021
+ raise SyncInputError(
2022
+ "multiple coordinator publish journal slots are occupied: "
2023
+ f"{[phase for phase, _path, _raw, _identity in found]}"
2024
+ )
2025
+ if not found:
2026
+ pending = contract.coordinator_pending_publish_status(paths.root)
2027
+ if pending is not None:
2028
+ raise SyncInputError(
2029
+ "coordinator publish residue has no recoverable immutable journal: "
2030
+ f"{pending['entries']}"
2031
+ )
2032
+ return None
2033
+
2034
+ phase, path, raw, identity = found[0]
2035
+ try:
2036
+ text = raw.decode("utf-8", errors="strict")
2037
+ except UnicodeDecodeError as exc:
2038
+ raise SyncInputError(
2039
+ f"publish recovery journal is not strict UTF-8: {exc}"
2040
+ ) from exc
2041
+ value = contract.parse_json_strict(text, source=str(path))
2042
+ journal = _validate_publish_journal(paths, value)
2043
+ if identity != _journal_expected_identity(journal):
2044
+ raise SyncInputError(
2045
+ f"{phase} publish recovery journal identity does not match its payload"
2046
+ )
2047
+ return LoadedPublishJournal(journal, raw, phase, path)
2048
+
2049
+
2050
+ def _decode_required_text(raw: bytes | None, label: str) -> str:
2051
+ if raw is None:
2052
+ raise SyncInputError(f"{label} snapshot is unexpectedly absent")
2053
+ try:
2054
+ return raw.decode("utf-8", errors="strict")
2055
+ except UnicodeDecodeError as exc:
2056
+ raise SyncInputError(f"{label} snapshot is not strict UTF-8") from exc
2057
+
2058
+
2059
+ def _journal_artifacts(
2060
+ paths: ProjectPaths,
2061
+ journal: Mapping[str, Any],
2062
+ ) -> list[PublishArtifact]:
2063
+ result: list[PublishArtifact] = []
2064
+ for index, item in enumerate(journal["artifacts"]):
2065
+ relative = str(item["path"])
2066
+ kind = str(item["kind"])
2067
+ if kind == "claude-index":
2068
+ path = paths.claude_path
2069
+ else:
2070
+ docs_relative = relative[len("project_docs/") :]
2071
+ path = paths.docs_root.joinpath(*PurePosixPath(docs_relative).parts)
2072
+ before = _decode_required_text(
2073
+ _decode_bytes_snapshot(item["before"], f"artifact[{index}].before"),
2074
+ f"artifact[{index}].before",
2075
+ )
2076
+ after = _decode_required_text(
2077
+ _decode_bytes_snapshot(item["after"], f"artifact[{index}].after"),
2078
+ f"artifact[{index}].after",
2079
+ )
2080
+ result.append(PublishArtifact(path, before, after, kind))
2081
+ return result
2082
+
2083
+
2084
+ def _restore_optional_text_snapshot(
2085
+ path: Path,
2086
+ before: bytes | None,
2087
+ after: bytes | None,
2088
+ label: str,
2089
+ paths: ProjectPaths,
2090
+ artifact_root: Path,
2091
+ artifact_root_identity: tuple[int, int, int, int],
2092
+ ) -> None:
2093
+ _revalidate_project_path_identities(paths)
2094
+ _set_publish_path_state(
2095
+ path,
2096
+ before,
2097
+ after,
2098
+ desired_after=False,
2099
+ allow_both=True,
2100
+ label=label,
2101
+ paths=paths,
2102
+ artifact_root=artifact_root,
2103
+ artifact_root_identity=artifact_root_identity,
2104
+ )
2105
+ _revalidate_project_path_identities(paths)
2106
+
2107
+
2108
+ def _rollback_publish_journal(
2109
+ paths: ProjectPaths,
2110
+ journal: Mapping[str, Any],
2111
+ ) -> None:
2112
+ artifact_root = _ensure_publish_artifact_root(paths, journal)
2113
+ artifact_root_identity = _publish_artifact_root_expected_identity(journal)
2114
+ artifacts = _journal_artifacts(paths, journal)
2115
+ for artifact in reversed(artifacts):
2116
+ _set_publish_path_state(
2117
+ artifact.path,
2118
+ artifact.original.encode("utf-8"),
2119
+ artifact.candidate.encode("utf-8"),
2120
+ desired_after=False,
2121
+ allow_both=True,
2122
+ label=f"{artifact.kind} recovery rollback",
2123
+ paths=paths,
2124
+ artifact_root=artifact_root,
2125
+ artifact_root_identity=artifact_root_identity,
2126
+ )
2127
+
2128
+ scan = journal["scan_state"]
2129
+ scan_before = _decode_bytes_snapshot(scan["before"], "scan_state.before")
2130
+ scan_after = _decode_bytes_snapshot(scan["after"], "scan_state.after")
2131
+ _restore_optional_text_snapshot(
2132
+ paths.scan_state_path,
2133
+ scan_before,
2134
+ scan_after,
2135
+ "scan state",
2136
+ paths,
2137
+ artifact_root,
2138
+ artifact_root_identity,
2139
+ )
2140
+
2141
+
2142
+ def _complete_publish_journal(
2143
+ paths: ProjectPaths,
2144
+ journal: Mapping[str, Any],
2145
+ ) -> None:
2146
+ artifact_root = _ensure_publish_artifact_root(paths, journal)
2147
+ artifact_root_identity = _publish_artifact_root_expected_identity(journal)
2148
+ for artifact in _journal_artifacts(paths, journal):
2149
+ _require_regular_file(artifact.path, artifact.kind)
2150
+ if contract.read_utf8(artifact.path) != artifact.candidate:
2151
+ raise SyncInputError(
2152
+ f"{artifact.kind} does not contain the committed candidate during recovery"
2153
+ )
2154
+
2155
+ manifest = journal["manifest"]
2156
+ manifest_after = _decode_bytes_snapshot(manifest["after"], "manifest.after")
2157
+ if _optional_bytes(paths.manifest_path) != manifest_after:
2158
+ raise SyncInputError("manifest changed during forward recovery")
2159
+ loaded_manifest = contract.load_manifest(
2160
+ paths.manifest_path,
2161
+ docs_root=paths.docs_root,
2162
+ verify_files=True,
2163
+ verify_complete_set=True,
2164
+ )
2165
+ if loaded_manifest.get("generation_id") != journal["manifest_generation_id"]:
2166
+ raise SyncInputError("manifest generation changed during forward recovery")
2167
+
2168
+ fresh_source = scan_dirs.build_candidate_state(paths.root)
2169
+ if fresh_source["snapshot_fingerprint"] != journal["source_snapshot_fingerprint"]:
2170
+ raise SyncInputError("source snapshot changed before forward recovery")
2171
+
2172
+ scan = journal["scan_state"]
2173
+ scan_before = _decode_bytes_snapshot(scan["before"], "scan_state.before")
2174
+ scan_after = _decode_bytes_snapshot(scan["after"], "scan_state.after")
2175
+ if scan["needed"]:
2176
+ if scan_after is None:
2177
+ raise SyncInputError("forward recovery has no scan-state candidate")
2178
+ parsed_after = scan_dirs.parse_previous_state_bytes(
2179
+ scan_after,
2180
+ source="coordinator recovery journal scan state",
2181
+ )
2182
+ if (
2183
+ parsed_after is None
2184
+ or parsed_after.get("candidate_generation_id")
2185
+ != journal["candidate_generation_id"]
2186
+ ):
2187
+ raise SyncInputError("recovery scan-state generation is invalid")
2188
+ if parsed_after.get("project_identity") != fresh_source.get("project_identity"):
2189
+ raise SyncInputError("recovery scan state belongs to another project")
2190
+ _set_publish_path_state(
2191
+ paths.scan_state_path,
2192
+ scan_before,
2193
+ scan_after,
2194
+ desired_after=True,
2195
+ allow_both=True,
2196
+ label="scan-state forward recovery",
2197
+ paths=paths,
2198
+ artifact_root=artifact_root,
2199
+ artifact_root_identity=artifact_root_identity,
2200
+ )
2201
+ elif _optional_bytes(paths.scan_state_path) != scan_before:
2202
+ raise SyncInputError("scan state changed outside the pending transaction")
2203
+
2204
+ _revalidate_project_path_identities(paths)
2205
+ if _optional_bytes(paths.manifest_path) != manifest_after:
2206
+ raise SyncInputError("manifest changed before recovery completion")
2207
+ contract.load_manifest(
2208
+ paths.manifest_path,
2209
+ docs_root=paths.docs_root,
2210
+ verify_files=True,
2211
+ verify_complete_set=True,
2212
+ )
2213
+
2214
+
2215
+ def recover_project(
2216
+ root: str | os.PathLike[str] = ".",
2217
+ *,
2218
+ lock_timeout: float = 10.0,
2219
+ ) -> tuple[dict[str, Any], int]:
2220
+ """Resolve one durable coordinator journal without guessing foreign changes."""
2221
+
2222
+ paths = _project_paths(root)
2223
+ with _project_lock_preserving_primary(paths.root, timeout=lock_timeout):
2224
+ phase4_gate = _phase4_recovery_gate(paths.root, apply=True)
2225
+ if phase4_gate is not None:
2226
+ result = phase4_gate[0]
2227
+ result["mode"] = "recover"
2228
+ return result, EXIT_GATE_FAILED
2229
+ loaded = _load_publish_journal(paths)
2230
+ if loaded is None:
2231
+ result = _empty_error_result(
2232
+ "recover",
2233
+ "no-recovery-required",
2234
+ "no pending coordinator publish transaction exists",
2235
+ )
2236
+ result["ok"] = True
2237
+ result["status"] = "no-recovery-required"
2238
+ result["errors"] = []
2239
+ result["publish"]["error"] = None
2240
+ return result, EXIT_OK
2241
+ journal = loaded.journal
2242
+ manifest_changed = bool(journal["manifest"]["changed"])
2243
+ if loaded.phase in {"committed", "rolled_back"}:
2244
+ outcome_phase = loaded.phase
2245
+ action = f"finalized-{outcome_phase}"
2246
+ finalization = _finalize_publish_journal(paths, loaded)
2247
+ else:
2248
+ manifest = journal["manifest"]
2249
+ manifest_before = _decode_bytes_snapshot(
2250
+ manifest["before"],
2251
+ "manifest.before",
2252
+ )
2253
+ manifest_after = _decode_bytes_snapshot(
2254
+ manifest["after"],
2255
+ "manifest.after",
2256
+ )
2257
+ current_manifest = _optional_bytes(paths.manifest_path)
2258
+ manifest_changed = bool(manifest["changed"])
2259
+
2260
+ artifact_root = _ensure_publish_artifact_root(paths, journal)
2261
+ artifact_root_identity = _publish_artifact_root_expected_identity(journal)
2262
+ if manifest_changed and current_manifest == manifest_after:
2263
+ _set_publish_path_state(
2264
+ paths.manifest_path,
2265
+ manifest_before,
2266
+ manifest_after,
2267
+ desired_after=True,
2268
+ allow_both=True,
2269
+ label="manifest forward recovery",
2270
+ paths=paths,
2271
+ artifact_root=artifact_root,
2272
+ artifact_root_identity=artifact_root_identity,
2273
+ )
2274
+ _complete_publish_journal(paths, journal)
2275
+ action = "completed-forward"
2276
+ outcome_phase = "committed"
2277
+ elif current_manifest == manifest_before or (
2278
+ manifest_before is not None and current_manifest is None
2279
+ ):
2280
+ _set_publish_path_state(
2281
+ paths.manifest_path,
2282
+ manifest_before,
2283
+ manifest_after,
2284
+ desired_after=False,
2285
+ allow_both=True,
2286
+ label="manifest recovery rollback",
2287
+ paths=paths,
2288
+ artifact_root=artifact_root,
2289
+ artifact_root_identity=artifact_root_identity,
2290
+ )
2291
+ _rollback_publish_journal(paths, journal)
2292
+ action = "rolled-back"
2293
+ outcome_phase = "rolled_back"
2294
+ else:
2295
+ raise SyncInputError(
2296
+ "manifest is neither the recorded preimage nor committed candidate; "
2297
+ "recovery journal was retained"
2298
+ )
2299
+
2300
+ finalized = _transition_publish_journal(
2301
+ paths,
2302
+ journal,
2303
+ loaded.raw,
2304
+ outcome_phase,
2305
+ )
2306
+ finalization = _finalize_publish_journal(paths, finalized)
2307
+ result = _empty_error_result("recover", "recovered", "")
2308
+ result["ok"] = True
2309
+ result["status"] = "recovered"
2310
+ result["recovery"] = {
2311
+ "action": action,
2312
+ "manifest_generation_id": journal["manifest_generation_id"],
2313
+ "finalization": finalization,
2314
+ }
2315
+ result["errors"] = []
2316
+ committed_outcome = outcome_phase == "committed"
2317
+ result["publish"]["completed"] = committed_outcome
2318
+ result["publish"]["rolled_back"] = not committed_outcome
2319
+ result["publish"]["retained"] = copy.deepcopy(
2320
+ finalization["retained_artifacts"]
2321
+ )
2322
+ if committed_outcome:
2323
+ _set_component_disposition(
2324
+ result["publish"],
2325
+ "manifest",
2326
+ (
2327
+ PublishDisposition.INSTALLED
2328
+ if manifest_changed
2329
+ else PublishDisposition.UNCHANGED
2330
+ ),
2331
+ )
2332
+ _set_component_disposition(
2333
+ result["publish"],
2334
+ "scan_state",
2335
+ (
2336
+ PublishDisposition.INSTALLED
2337
+ if bool(journal["scan_state"]["needed"])
2338
+ else PublishDisposition.UNCHANGED
2339
+ ),
2340
+ )
2341
+ _set_transaction_disposition(
2342
+ result["publish"],
2343
+ PublishDisposition.INSTALLED,
2344
+ )
2345
+ else:
2346
+ _set_component_disposition(
2347
+ result["publish"],
2348
+ "manifest",
2349
+ (
2350
+ PublishDisposition.NOT_INSTALLED
2351
+ if manifest_changed
2352
+ else PublishDisposition.UNCHANGED
2353
+ ),
2354
+ )
2355
+ _set_component_disposition(
2356
+ result["publish"],
2357
+ "scan_state",
2358
+ (
2359
+ PublishDisposition.NOT_INSTALLED
2360
+ if bool(journal["scan_state"]["needed"])
2361
+ else PublishDisposition.UNCHANGED
2362
+ ),
2363
+ )
2364
+ _set_transaction_disposition(
2365
+ result["publish"],
2366
+ PublishDisposition.NOT_INSTALLED,
2367
+ )
2368
+ result["publish"]["error"] = None
2369
+ return result, EXIT_OK
2370
+
2371
+
2372
+ def _write_with_detection(
2373
+ artifact: PublishArtifact,
2374
+ paths: ProjectPaths,
2375
+ artifact_root: Path,
2376
+ artifact_root_identity: tuple[int, int, int, int],
2377
+ ) -> BaseException | None:
2378
+ """Identity-aware CAS publication with post-install failure classification."""
2379
+
2380
+ before = artifact.original.encode("utf-8")
2381
+ after = artifact.candidate.encode("utf-8")
2382
+ _revalidate_project_path_identities(paths)
2383
+ try:
2384
+ _set_publish_path_state(
2385
+ artifact.path,
2386
+ before,
2387
+ after,
2388
+ desired_after=True,
2389
+ allow_both=False,
2390
+ label=artifact.kind,
2391
+ paths=paths,
2392
+ artifact_root=artifact_root,
2393
+ artifact_root_identity=artifact_root_identity,
2394
+ )
2395
+ except BaseException as exc:
2396
+ _revalidate_project_path_identities(paths)
2397
+ if _optional_bytes(artifact.path) == after:
2398
+ return exc
2399
+ raise
2400
+ _revalidate_project_path_identities(paths)
2401
+ return None
2402
+
2403
+
2404
+ def _rollback_artifacts(
2405
+ artifacts: Sequence[PublishArtifact],
2406
+ paths: ProjectPaths,
2407
+ artifact_root: Path,
2408
+ artifact_root_identity: tuple[int, int, int, int],
2409
+ ) -> list[dict[str, str]]:
2410
+ failures: list[dict[str, str]] = []
2411
+ for artifact in reversed(artifacts):
2412
+ try:
2413
+ _revalidate_project_path_identities(paths)
2414
+ _set_publish_path_state(
2415
+ artifact.path,
2416
+ artifact.original.encode("utf-8"),
2417
+ artifact.candidate.encode("utf-8"),
2418
+ desired_after=False,
2419
+ allow_both=True,
2420
+ label=f"{artifact.kind} rollback",
2421
+ paths=paths,
2422
+ artifact_root=artifact_root,
2423
+ artifact_root_identity=artifact_root_identity,
2424
+ )
2425
+ except BaseException as exc: # pragma: no cover - double I/O failure
2426
+ failures.append(
2427
+ {
2428
+ "path": artifact.path.as_posix(),
2429
+ "kind": artifact.kind,
2430
+ "error": str(exc),
2431
+ }
2432
+ )
2433
+ return failures
2434
+
2435
+
2436
+ def _publish(
2437
+ prepared: PreparedSync, report: dict[str, Any], lock_timeout: float
2438
+ ) -> bool:
2439
+ publish = report["publish"]
2440
+ artifacts: list[PublishArtifact] = []
2441
+ marker_artifacts = [
2442
+ PublishArtifact(
2443
+ prepared.paths.docs_root.joinpath(*PurePosixPath(relative).parts),
2444
+ prepared.original_documents[relative],
2445
+ candidate,
2446
+ "marker",
2447
+ )
2448
+ for relative, candidate in sorted(prepared.marker_contents.items())
2449
+ ]
2450
+ if prepared.claude_changed:
2451
+ marker_artifacts.append(
2452
+ PublishArtifact(
2453
+ prepared.paths.claude_path,
2454
+ prepared.original_claude,
2455
+ prepared.claude_candidate,
2456
+ "claude-index",
2457
+ )
2458
+ )
2459
+
2460
+ manifest_expected = contract.stable_json_dumps(prepared.manifest).encode("utf-8")
2461
+ try:
2462
+ committed_state = (
2463
+ _build_committed_scan_state(
2464
+ prepared.scan_candidate,
2465
+ prepared.paths.scan_state_path,
2466
+ prepared.manifest["generation_id"],
2467
+ )
2468
+ if prepared.scan_commit_needed
2469
+ else None
2470
+ )
2471
+ except BaseException as exc:
2472
+ _set_component_disposition(
2473
+ publish,
2474
+ "manifest",
2475
+ (
2476
+ PublishDisposition.NOT_INSTALLED
2477
+ if prepared.manifest_changed
2478
+ else PublishDisposition.UNCHANGED
2479
+ ),
2480
+ )
2481
+ _set_component_disposition(
2482
+ publish,
2483
+ "scan_state",
2484
+ (
2485
+ PublishDisposition.NOT_INSTALLED
2486
+ if prepared.scan_commit_needed
2487
+ else PublishDisposition.UNCHANGED
2488
+ ),
2489
+ )
2490
+ _set_transaction_disposition(publish, PublishDisposition.NOT_INSTALLED)
2491
+ publish["error"] = str(exc)
2492
+ publish["rolled_back"] = True
2493
+ raise SyncPublishError(
2494
+ f"publish transaction could not be prepared: {exc}",
2495
+ report,
2496
+ ) from exc
2497
+ expected_scan_state = (
2498
+ contract.stable_json_dumps(committed_state).encode("utf-8")
2499
+ if committed_state is not None
2500
+ else None
2501
+ )
2502
+ transaction_needed = bool(
2503
+ marker_artifacts or prepared.manifest_changed or prepared.scan_commit_needed
2504
+ )
2505
+ journal_path = _publish_journal_path(prepared.paths)
2506
+ journal_expected: bytes | None = None
2507
+ journal: dict[str, Any] | None = None
2508
+ artifact_root: Path | None = None
2509
+ artifact_root_identity: tuple[int, int, int, int] | None = None
2510
+ publication_finalized = False
2511
+ _set_component_disposition(
2512
+ publish,
2513
+ "manifest",
2514
+ (
2515
+ PublishDisposition.NOT_ATTEMPTED
2516
+ if prepared.manifest_changed
2517
+ else PublishDisposition.UNCHANGED
2518
+ ),
2519
+ )
2520
+ _set_component_disposition(
2521
+ publish,
2522
+ "scan_state",
2523
+ (
2524
+ PublishDisposition.NOT_ATTEMPTED
2525
+ if prepared.scan_commit_needed
2526
+ else PublishDisposition.UNCHANGED
2527
+ ),
2528
+ )
2529
+ _set_transaction_disposition(
2530
+ publish,
2531
+ (
2532
+ PublishDisposition.NOT_ATTEMPTED
2533
+ if transaction_needed
2534
+ else PublishDisposition.UNCHANGED
2535
+ ),
2536
+ )
2537
+
2538
+ def record_published(kind: str, path: Path) -> None:
2539
+ item = {
2540
+ "kind": kind,
2541
+ "path": path.relative_to(prepared.paths.root).as_posix(),
2542
+ }
2543
+ if item not in publish["published"]:
2544
+ publish["published"].append(item)
2545
+
2546
+ def classify_scan_state() -> PublishDisposition:
2547
+ try:
2548
+ current = _optional_bytes(prepared.paths.scan_state_path)
2549
+ except BaseException:
2550
+ disposition = PublishDisposition.UNKNOWN
2551
+ else:
2552
+ if expected_scan_state is not None and current == expected_scan_state:
2553
+ disposition = PublishDisposition.INSTALLED
2554
+ record_published("scan-state", prepared.paths.scan_state_path)
2555
+ elif current == prepared.original_scan_state_bytes:
2556
+ disposition = PublishDisposition.NOT_INSTALLED
2557
+ else:
2558
+ disposition = PublishDisposition.UNKNOWN
2559
+ _set_component_disposition(publish, "scan_state", disposition)
2560
+ return disposition
2561
+
2562
+ try:
2563
+ with _project_lock_preserving_primary(
2564
+ prepared.paths.root,
2565
+ timeout=lock_timeout,
2566
+ secondary_errors=publish["secondary_errors"],
2567
+ ):
2568
+ recovery_gate = _phase4_recovery_gate(prepared.paths.root, apply=True)
2569
+ if recovery_gate is not None:
2570
+ report.clear()
2571
+ report.update(recovery_gate[0])
2572
+ return False
2573
+ _documents_unchanged(prepared)
2574
+ _persistent_inputs_unchanged(prepared)
2575
+ coordinator_gate = _coordinator_recovery_gate(
2576
+ prepared.paths,
2577
+ apply=True,
2578
+ )
2579
+ if coordinator_gate is not None:
2580
+ report.clear()
2581
+ report.update(coordinator_gate[0])
2582
+ return False
2583
+ if transaction_needed:
2584
+ transaction_id = str(uuid.uuid4())
2585
+ artifact_root, artifact_root_identity = _create_publish_artifact_root(
2586
+ prepared.paths,
2587
+ transaction_id,
2588
+ )
2589
+ journal_draft = _build_publish_journal(
2590
+ prepared,
2591
+ marker_artifacts,
2592
+ committed_state,
2593
+ transaction_id,
2594
+ artifact_root_identity,
2595
+ )
2596
+ journal, journal_expected = _publish_journal_exclusive(
2597
+ journal_path,
2598
+ journal_draft,
2599
+ )
2600
+ artifact_root = _ensure_publish_artifact_root(prepared.paths, journal)
2601
+ artifact_root_identity = _publish_artifact_root_expected_identity(journal)
2602
+ _publish_fault("publish-journal-ready")
2603
+
2604
+ try:
2605
+ for artifact in marker_artifacts:
2606
+ # 先登记尝试,确保 post-replace 异常或 KeyboardInterrupt 仍会
2607
+ # 进入精确回滚,而不会遗漏已安装但尚未记账的文件。
2608
+ artifacts.append(artifact)
2609
+ if artifact_root is None or artifact_root_identity is None:
2610
+ raise SyncInputError("publish artifact root was not prepared")
2611
+ deferred_error = _write_with_detection(
2612
+ artifact,
2613
+ prepared.paths,
2614
+ artifact_root,
2615
+ artifact_root_identity,
2616
+ )
2617
+ record_published(artifact.kind, artifact.path)
2618
+ if deferred_error is not None:
2619
+ raise deferred_error
2620
+
2621
+ _documents_match_candidate(prepared)
2622
+
2623
+ _revalidate_project_path_identities(prepared.paths)
2624
+ if prepared.manifest_changed:
2625
+ if artifact_root is None or artifact_root_identity is None:
2626
+ raise SyncInputError("publish artifact root was not prepared")
2627
+ _set_publish_path_state(
2628
+ prepared.paths.manifest_path,
2629
+ prepared.original_manifest_bytes,
2630
+ manifest_expected,
2631
+ desired_after=True,
2632
+ allow_both=False,
2633
+ label="manifest",
2634
+ paths=prepared.paths,
2635
+ artifact_root=artifact_root,
2636
+ artifact_root_identity=artifact_root_identity,
2637
+ )
2638
+ elif (
2639
+ _optional_bytes(prepared.paths.manifest_path)
2640
+ != prepared.original_manifest_bytes
2641
+ ):
2642
+ raise SyncInputError("manifest preimage changed before commit")
2643
+ _revalidate_project_path_identities(prepared.paths)
2644
+ _verify_committed_manifest(prepared)
2645
+ if prepared.manifest_changed:
2646
+ _set_component_disposition(
2647
+ publish,
2648
+ "manifest",
2649
+ PublishDisposition.INSTALLED,
2650
+ )
2651
+ record_published("manifest", prepared.paths.manifest_path)
2652
+ _publish_fault("manifest-verified")
2653
+ except BaseException as exc:
2654
+ # 覆盖 atomic replace 成功后、Python 尚未来得及记录处置状态
2655
+ # 就收到中断的窗口。未知字节绝不能按 pre-commit 回滚处理。
2656
+ manifest_disposition = PublishDisposition(
2657
+ publish["manifest_disposition"]
2658
+ )
2659
+ if (
2660
+ prepared.manifest_changed
2661
+ and manifest_disposition is not PublishDisposition.INSTALLED
2662
+ ):
2663
+ try:
2664
+ current_manifest = _optional_bytes(prepared.paths.manifest_path)
2665
+ except BaseException:
2666
+ manifest_disposition = PublishDisposition.UNKNOWN
2667
+ else:
2668
+ if current_manifest == manifest_expected:
2669
+ manifest_disposition = PublishDisposition.INSTALLED
2670
+ elif current_manifest == prepared.original_manifest_bytes:
2671
+ manifest_disposition = PublishDisposition.NOT_INSTALLED
2672
+ else:
2673
+ manifest_disposition = PublishDisposition.UNKNOWN
2674
+ _set_component_disposition(
2675
+ publish,
2676
+ "manifest",
2677
+ manifest_disposition,
2678
+ )
2679
+
2680
+ if manifest_disposition in {
2681
+ PublishDisposition.INSTALLED,
2682
+ PublishDisposition.UNKNOWN,
2683
+ }:
2684
+ _set_transaction_disposition(
2685
+ publish,
2686
+ (
2687
+ PublishDisposition.PARTIALLY_INSTALLED
2688
+ if manifest_disposition is PublishDisposition.INSTALLED
2689
+ else PublishDisposition.UNKNOWN
2690
+ ),
2691
+ )
2692
+ publish["error"] = str(exc)
2693
+ raise SyncPublishError(
2694
+ f"publish failed at or after manifest commit: {exc}",
2695
+ report,
2696
+ ) from exc
2697
+
2698
+ rollback_failures = (
2699
+ [
2700
+ {
2701
+ "path": journal_path.as_posix(),
2702
+ "kind": "publish-artifacts",
2703
+ "error": "publish artifact root is unavailable for rollback",
2704
+ }
2705
+ ]
2706
+ if artifact_root is None or artifact_root_identity is None
2707
+ else _rollback_artifacts(
2708
+ artifacts,
2709
+ prepared.paths,
2710
+ artifact_root,
2711
+ artifact_root_identity,
2712
+ )
2713
+ )
2714
+ rollback_state_complete = not rollback_failures
2715
+ if rollback_state_complete and journal_expected is not None:
2716
+ try:
2717
+ if journal is None:
2718
+ raise SyncInputError(
2719
+ "publish journal payload is unavailable during rollback"
2720
+ )
2721
+ rolled_back_journal = _transition_publish_journal(
2722
+ prepared.paths,
2723
+ journal,
2724
+ journal_expected,
2725
+ "rolled_back",
2726
+ )
2727
+ finalization = _finalize_publish_journal(
2728
+ prepared.paths,
2729
+ rolled_back_journal,
2730
+ )
2731
+ publish["retained"].extend(
2732
+ copy.deepcopy(finalization["retained_artifacts"])
2733
+ )
2734
+ except BaseException as journal_exc:
2735
+ publish["finalization_pending"] = True
2736
+ publish["secondary_errors"].append(
2737
+ {
2738
+ "stage": "rollback-finalization",
2739
+ "error": str(journal_exc),
2740
+ }
2741
+ )
2742
+ publish["rolled_back"] = rollback_state_complete
2743
+ publish["rollback_failures"] = rollback_failures
2744
+ _set_transaction_disposition(
2745
+ publish,
2746
+ (
2747
+ PublishDisposition.NOT_INSTALLED
2748
+ if rollback_state_complete
2749
+ else PublishDisposition.UNKNOWN
2750
+ ),
2751
+ )
2752
+ publish["error"] = str(exc)
2753
+ raise SyncPublishError(
2754
+ f"publish failed before manifest commit: {exc}",
2755
+ report,
2756
+ ) from exc
2757
+
2758
+ if prepared.scan_commit_needed:
2759
+ try:
2760
+ if committed_state is None or expected_scan_state is None:
2761
+ raise SyncInputError("prepared scan-state candidate is missing")
2762
+ if (
2763
+ _optional_bytes(prepared.paths.scan_state_path)
2764
+ != prepared.original_scan_state_bytes
2765
+ ):
2766
+ raise SyncInputError(
2767
+ "scan state changed before candidate promotion"
2768
+ )
2769
+ _revalidate_project_path_identities(prepared.paths)
2770
+ _documents_match_candidate(prepared)
2771
+ _verify_committed_manifest(prepared)
2772
+ _source_snapshot_unchanged(prepared)
2773
+ if artifact_root is None or artifact_root_identity is None:
2774
+ raise SyncInputError("publish artifact root was not prepared")
2775
+ _set_publish_path_state(
2776
+ prepared.paths.scan_state_path,
2777
+ prepared.original_scan_state_bytes,
2778
+ expected_scan_state,
2779
+ desired_after=True,
2780
+ allow_both=False,
2781
+ label="scan state",
2782
+ paths=prepared.paths,
2783
+ artifact_root=artifact_root,
2784
+ artifact_root_identity=artifact_root_identity,
2785
+ )
2786
+ _revalidate_project_path_identities(prepared.paths)
2787
+ _documents_match_candidate(prepared)
2788
+ _verify_committed_manifest(prepared)
2789
+ _source_snapshot_unchanged(prepared)
2790
+ _publish_fault("scan-state-verified")
2791
+ _set_component_disposition(
2792
+ publish,
2793
+ "scan_state",
2794
+ PublishDisposition.INSTALLED,
2795
+ )
2796
+ record_published("scan-state", prepared.paths.scan_state_path)
2797
+ _publish_fault("scan-state-recorded")
2798
+ except BaseException as exc:
2799
+ scan_disposition = classify_scan_state()
2800
+ manifest_disposition = PublishDisposition(
2801
+ publish["manifest_disposition"]
2802
+ )
2803
+ if scan_disposition is PublishDisposition.UNKNOWN:
2804
+ transaction_disposition = PublishDisposition.UNKNOWN
2805
+ elif (
2806
+ scan_disposition is PublishDisposition.NOT_INSTALLED
2807
+ and manifest_disposition is PublishDisposition.UNCHANGED
2808
+ and not artifacts
2809
+ ):
2810
+ transaction_disposition = PublishDisposition.NOT_INSTALLED
2811
+ else:
2812
+ transaction_disposition = PublishDisposition.PARTIALLY_INSTALLED
2813
+ _set_transaction_disposition(
2814
+ publish,
2815
+ transaction_disposition,
2816
+ )
2817
+ failure_message = (
2818
+ "scan state publish failed "
2819
+ f"(manifest={manifest_disposition.value}, "
2820
+ f"installed_artifacts={len(artifacts)}, "
2821
+ f"scan_state={scan_disposition.value}): {exc}"
2822
+ )
2823
+ publish["error"] = failure_message
2824
+ raise SyncPublishError(failure_message, report) from exc
2825
+
2826
+ _publish_fault("publish-before-journal-cleanup")
2827
+ if journal_expected is not None:
2828
+ if journal is None:
2829
+ raise SyncInputError(
2830
+ "publish journal payload is unavailable during commit"
2831
+ )
2832
+ try:
2833
+ committed_journal = _transition_publish_journal(
2834
+ prepared.paths,
2835
+ journal,
2836
+ journal_expected,
2837
+ "committed",
2838
+ )
2839
+ except BaseException as exc:
2840
+ pending = _load_publish_journal(prepared.paths)
2841
+ if pending is not None and pending.phase == "committed":
2842
+ _set_transaction_disposition(
2843
+ publish,
2844
+ PublishDisposition.INSTALLED,
2845
+ )
2846
+ publish["finalization_pending"] = True
2847
+ publish["error"] = str(exc)
2848
+ raise SyncPublishError(
2849
+ f"publication committed but journal finalization is pending: {exc}",
2850
+ report,
2851
+ ) from exc
2852
+ raise
2853
+ _set_transaction_disposition(
2854
+ publish,
2855
+ PublishDisposition.INSTALLED,
2856
+ )
2857
+ try:
2858
+ finalization = _finalize_publish_journal(
2859
+ prepared.paths,
2860
+ committed_journal,
2861
+ )
2862
+ publish["retained"].extend(
2863
+ copy.deepcopy(finalization["retained_artifacts"])
2864
+ )
2865
+ except BaseException as exc:
2866
+ publish["finalization_pending"] = True
2867
+ publish["error"] = str(exc)
2868
+ raise SyncPublishError(
2869
+ f"publication committed but cleanup finalization is pending: {exc}",
2870
+ report,
2871
+ ) from exc
2872
+ else:
2873
+ _set_transaction_disposition(
2874
+ publish,
2875
+ PublishDisposition.UNCHANGED,
2876
+ )
2877
+ publication_finalized = True
2878
+ _publish_fault("publish-completed")
2879
+ publish["completed"] = True
2880
+ except SyncPublishError:
2881
+ raise
2882
+ except BaseException as exc:
2883
+ if publication_finalized:
2884
+ publish["completed"] = False
2885
+ publish["error"] = str(exc)
2886
+ raise SyncPublishError(
2887
+ f"publication was finalized but lock release failed: {exc}",
2888
+ report,
2889
+ ) from exc
2890
+
2891
+ manifest_disposition = PublishDisposition(publish["manifest_disposition"])
2892
+ scan_disposition = PublishDisposition(publish["scan_state_disposition"])
2893
+ if (
2894
+ prepared.scan_commit_needed
2895
+ and scan_disposition is PublishDisposition.NOT_ATTEMPTED
2896
+ ):
2897
+ scan_disposition = classify_scan_state()
2898
+ if any(
2899
+ disposition
2900
+ in {
2901
+ PublishDisposition.INSTALLED,
2902
+ PublishDisposition.UNKNOWN,
2903
+ }
2904
+ for disposition in (manifest_disposition, scan_disposition)
2905
+ ):
2906
+ if PublishDisposition.UNKNOWN in {
2907
+ manifest_disposition,
2908
+ scan_disposition,
2909
+ }:
2910
+ _set_transaction_disposition(
2911
+ publish,
2912
+ PublishDisposition.UNKNOWN,
2913
+ )
2914
+ else:
2915
+ _set_transaction_disposition(
2916
+ publish,
2917
+ PublishDisposition.PARTIALLY_INSTALLED,
2918
+ )
2919
+ publish["completed"] = False
2920
+ failure_message = (
2921
+ "publish failed with unresolved durable state "
2922
+ f"(manifest={manifest_disposition.value}, "
2923
+ f"scan_state={scan_disposition.value}, "
2924
+ f"installed_artifacts={len(artifacts)}): {exc}"
2925
+ )
2926
+ publish["error"] = failure_message
2927
+ raise SyncPublishError(failure_message, report) from exc
2928
+ raise
2929
+ return True
2930
+
2931
+
2932
+ def _prepare(
2933
+ paths: ProjectPaths,
2934
+ stage_docs: Path,
2935
+ *,
2936
+ run_timestamp: str,
2937
+ force_full: bool,
2938
+ ) -> PreparedSync:
2939
+ # 先捕获所有持久输入预像,再基于这些输入作候选决策。即使后续
2940
+ # 解析阶段观察到并发替换,发布锁内的精确字节复核也会拒绝提交。
2941
+ original_claude = contract.read_utf8(paths.claude_path)
2942
+ original_manifest_bytes = _optional_bytes(paths.manifest_path)
2943
+ original_scan_state_bytes = _optional_bytes(paths.scan_state_path)
2944
+
2945
+ marker_contents, marker_originals, marker_details = _normalized_marker_files(
2946
+ paths.docs_root
2947
+ )
2948
+ captured_docs = stage_docs.parent / ".captured-project-docs"
2949
+ captured_docs.mkdir()
2950
+ original_documents = _stage_documents(
2951
+ paths.docs_root,
2952
+ stage_docs,
2953
+ captured_docs,
2954
+ marker_contents,
2955
+ marker_originals,
2956
+ )
2957
+ current_manifest, manifest_warnings = _load_current_manifest(
2958
+ paths,
2959
+ original_manifest_bytes,
2960
+ captured_docs,
2961
+ )
2962
+ manifest, manifest_changed, current_generation, current_schema = _select_manifest(
2963
+ paths,
2964
+ stage_docs,
2965
+ run_timestamp,
2966
+ current_manifest,
2967
+ original_manifest_bytes,
2968
+ )
2969
+ previous_state, scan_candidate, scan_commit_needed = _scan_candidate(
2970
+ paths,
2971
+ original_scan_state_bytes,
2972
+ force_full=force_full,
2973
+ manifest_generation_id=manifest["generation_id"],
2974
+ )
2975
+ source_snapshot_root = stage_docs.parent
2976
+ known_source_paths = _stage_source_snapshot(
2977
+ source_snapshot_root,
2978
+ scan_candidate,
2979
+ )
2980
+ source_inventory = _phase4_source_inventory(scan_candidate)
2981
+ validation, validation_errors = _validate_documents(
2982
+ source_snapshot_root,
2983
+ known_source_paths,
2984
+ stage_docs,
2985
+ manifest,
2986
+ scan_candidate,
2987
+ )
2988
+ broken_count, broken = link_check.check_links(stage_docs)
2989
+ links = {"ok": broken_count == 0, "broken_count": broken_count, "broken": broken}
2990
+ link_errors = (
2991
+ [
2992
+ {
2993
+ "code": "broken-document-links",
2994
+ "message": f"candidate document tree contains {broken_count} invalid or missing links",
2995
+ }
2996
+ ]
2997
+ if broken_count
2998
+ else []
2999
+ )
3000
+
3001
+ phase4, phase4_errors, phase4_warnings = _phase4_report(
3002
+ source_snapshot_root,
3003
+ stage_docs,
3004
+ manifest,
3005
+ source_inventory,
3006
+ )
3007
+ phase4_counts = phase4.get("counts", {})
3008
+ phase4_candidates = (
3009
+ phase4_counts.get("candidates", 0) if isinstance(phase4_counts, Mapping) else 0
3010
+ )
3011
+ if type(phase4_candidates) is int and phase4_candidates > 0 and scan_commit_needed:
3012
+ # Quarantine candidates freeze the scan baseline only. This keeps the
3013
+ # reference-clearing edits publishable so the quarantine workflow can
3014
+ # complete instead of deadlocking between the coordinator gate and the
3015
+ # Phase 4 manifest consistency check.
3016
+ scan_commit_needed = False
3017
+ phase4_warnings.append(
3018
+ {
3019
+ "code": "scan-baseline-frozen",
3020
+ "severity": "warning",
3021
+ "message": (
3022
+ "scan baseline commit deferred until pending Phase 4 "
3023
+ "candidates are quarantined"
3024
+ ),
3025
+ }
3026
+ )
3027
+ claude_candidate = claude_doc_index.replace_doc_tree_section(
3028
+ original_claude,
3029
+ manifest,
3030
+ )
3031
+ claude_changed = claude_candidate != original_claude
3032
+
3033
+ return PreparedSync(
3034
+ paths=paths,
3035
+ stage_docs=stage_docs,
3036
+ run_timestamp=run_timestamp,
3037
+ force_full=force_full,
3038
+ original_documents=original_documents,
3039
+ marker_contents=marker_contents,
3040
+ marker_details=marker_details,
3041
+ original_claude=original_claude,
3042
+ original_manifest_bytes=original_manifest_bytes,
3043
+ original_scan_state_bytes=original_scan_state_bytes,
3044
+ previous_scan_state=previous_state,
3045
+ scan_candidate=scan_candidate,
3046
+ scan_commit_needed=scan_commit_needed,
3047
+ manifest=manifest,
3048
+ manifest_changed=manifest_changed,
3049
+ current_manifest_generation=current_generation,
3050
+ current_manifest_schema=current_schema,
3051
+ claude_candidate=claude_candidate,
3052
+ claude_changed=claude_changed,
3053
+ validation=validation,
3054
+ links=links,
3055
+ phase4=phase4,
3056
+ warnings=[*manifest_warnings, *phase4_warnings],
3057
+ errors=[*validation_errors, *link_errors, *phase4_errors],
3058
+ )
3059
+
3060
+
3061
+ def _build_worklist_scaffold(prepared: PreparedSync) -> list[dict[str, Any]]:
3062
+ docs_root = prepared.paths.docs_root
3063
+ directories = prepared.scan_candidate.get("directories", [])
3064
+ scaffold: list[dict[str, Any]] = []
3065
+
3066
+ for item in directories:
3067
+ path = str(item.get("path", ""))
3068
+ change = item.get("change", "unchanged")
3069
+ snapshot = item.get("snapshot", {})
3070
+ files = snapshot.get("files", [])
3071
+ child_dirs = snapshot.get("child_directories", [])
3072
+ is_empty = bool(item.get("is_empty", False))
3073
+
3074
+ recommended_profile = "placeholder" if is_empty else "standard"
3075
+ doc_relative = "index.md" if not path else f"{path}.md"
3076
+ doc_project_path = (
3077
+ "project_docs/index.md" if not path else f"project_docs/{path}.md"
3078
+ )
3079
+
3080
+ precomputed_links: dict[str, Any] = {
3081
+ "children": [],
3082
+ }
3083
+
3084
+ # Parent doc link
3085
+ parent_path = posixpath.dirname(path) if path else ""
3086
+ if parent_path:
3087
+ parent_doc = f"{parent_path}.md"
3088
+ try:
3089
+ link = contract.compute_relative_doc_link(
3090
+ doc_relative, parent_doc, docs_root
3091
+ )
3092
+ precomputed_links["parent"] = {
3093
+ "path": parent_path,
3094
+ "doc_path": f"project_docs/{parent_path}.md",
3095
+ "relative_link": link,
3096
+ }
3097
+ except Exception:
3098
+ pass
3099
+
3100
+ # Children doc links
3101
+ for child in child_dirs:
3102
+ child_subpath = child if not path else f"{path}/{child}"
3103
+ child_doc = f"{child_subpath}.md"
3104
+ try:
3105
+ link = contract.compute_relative_doc_link(
3106
+ doc_relative, child_doc, docs_root
3107
+ )
3108
+ precomputed_links["children"].append(
3109
+ {
3110
+ "name": child,
3111
+ "path": child_subpath,
3112
+ "doc_path": f"project_docs/{child_subpath}.md",
3113
+ "relative_link": link,
3114
+ }
3115
+ )
3116
+ except Exception:
3117
+ pass
3118
+
3119
+ # Tests doc link
3120
+ try:
3121
+ tests_link = contract.compute_relative_doc_link(
3122
+ doc_relative, "tests.md", docs_root
3123
+ )
3124
+ precomputed_links["tests"] = {
3125
+ "doc_path": "project_docs/tests.md",
3126
+ "relative_link": tests_link,
3127
+ }
3128
+ except Exception:
3129
+ pass
3130
+
3131
+ direct_files = [
3132
+ {
3133
+ "name": f.get("name"),
3134
+ "size": f.get("size"),
3135
+ "is_py": str(f.get("name", "")).casefold().endswith(".py"),
3136
+ }
3137
+ for f in files
3138
+ ]
3139
+
3140
+ scaffold.append(
3141
+ {
3142
+ "path": path,
3143
+ "change": change,
3144
+ "doc_path": doc_project_path,
3145
+ "recommended_profile": recommended_profile,
3146
+ "direct_files": direct_files,
3147
+ "direct_subdirectories": list(child_dirs),
3148
+ "precomputed_links": precomputed_links,
3149
+ }
3150
+ )
3151
+
3152
+ return scaffold
3153
+
3154
+
3155
+ def _report_warnings(prepared: PreparedSync) -> list[Any]:
3156
+ """Prepared warnings plus any runtime durability degradation observed."""
3157
+
3158
+ warnings_value = [copy.deepcopy(item) for item in prepared.warnings]
3159
+ degraded = phase4_exit.directory_fsync_degraded()
3160
+ if degraded:
3161
+ warnings_value.append(
3162
+ {
3163
+ "code": "durability-degraded",
3164
+ "severity": "warning",
3165
+ "message": (
3166
+ "directory fsync was skipped because this filesystem refuses it; "
3167
+ "crash durability of the published namespace is degraded: "
3168
+ + "; ".join(degraded)
3169
+ ),
3170
+ }
3171
+ )
3172
+ return warnings_value
3173
+
3174
+
3175
+ def _report(prepared: PreparedSync, *, apply: bool) -> dict[str, Any]:
3176
+ scan = prepared.scan_candidate
3177
+ planned: list[dict[str, str]] = [
3178
+ {"kind": "marker", "path": path} for path in sorted(prepared.marker_contents)
3179
+ ]
3180
+ if prepared.claude_changed:
3181
+ planned.append({"kind": "claude-index", "path": "CLAUDE.md"})
3182
+ if prepared.manifest_changed:
3183
+ planned.append({"kind": "manifest", "path": "project_docs/_manifest.json"})
3184
+ if prepared.scan_commit_needed:
3185
+ planned.append({"kind": "scan-state", "path": "project_docs/_scan_state.json"})
3186
+
3187
+ return {
3188
+ "schema_version": RESULT_SCHEMA_VERSION,
3189
+ "ok": prepared.gates_passed,
3190
+ "mode": "apply" if apply else "dry-run",
3191
+ "root": prepared.paths.root.as_posix(),
3192
+ "run_timestamp": prepared.run_timestamp,
3193
+ "scan": {
3194
+ "mode": scan["mode"],
3195
+ "baseline": copy.deepcopy(scan["baseline"]),
3196
+ "candidate_generation_id": scan["candidate_generation_id"],
3197
+ "snapshot_fingerprint": scan["snapshot_fingerprint"],
3198
+ "changes": copy.deepcopy(scan["changes"]),
3199
+ "change_counts": copy.deepcopy(scan["change_counts"]),
3200
+ "worklist": {
3201
+ "directories": copy.deepcopy(scan["directories"]),
3202
+ "deleted_directories": copy.deepcopy(scan["deleted_directories"]),
3203
+ "unknown_directories": copy.deepcopy(scan["unknown_directories"]),
3204
+ "scaffold": _build_worklist_scaffold(prepared),
3205
+ },
3206
+ "full_total": scan["full_total"],
3207
+ "boundary_count": scan["boundary_count"],
3208
+ "skipped_directory_count": scan["skipped_directory_count"],
3209
+ "unknown_scopes": copy.deepcopy(scan["snapshot"]["unknown_scopes"]),
3210
+ "commit_needed": prepared.scan_commit_needed,
3211
+ },
3212
+ "markers": {
3213
+ "candidate_count": len(prepared.marker_details),
3214
+ "candidate_file_count": len(prepared.marker_contents),
3215
+ "changes": prepared.marker_details,
3216
+ },
3217
+ "validation": prepared.validation,
3218
+ "links": prepared.links,
3219
+ "phase4": prepared.phase4,
3220
+ "manifest": {
3221
+ "schema_version": prepared.manifest["schema_version"],
3222
+ "generation_id": prepared.manifest["generation_id"],
3223
+ "current_generation_id": prepared.current_manifest_generation,
3224
+ "current_schema_version": prepared.current_manifest_schema,
3225
+ "changed": prepared.manifest_changed,
3226
+ "total": prepared.manifest["total"],
3227
+ "depth_counts": prepared.manifest["depth_counts"],
3228
+ },
3229
+ "claude": {"changed": prepared.claude_changed},
3230
+ "planned_writes": planned,
3231
+ "warnings": _report_warnings(prepared),
3232
+ "errors": prepared.errors,
3233
+ "publish": {
3234
+ "requested": apply,
3235
+ "completed": False,
3236
+ "disposition": PublishDisposition.NOT_ATTEMPTED.value,
3237
+ "manifest_disposition": PublishDisposition.NOT_ATTEMPTED.value,
3238
+ "scan_state_disposition": PublishDisposition.NOT_ATTEMPTED.value,
3239
+ "manifest_commit_point": False,
3240
+ "manifest_commit_ambiguous": False,
3241
+ "scan_state_committed": False,
3242
+ "scan_state_commit_ambiguous": False,
3243
+ "partial_commit": False,
3244
+ "rolled_back": False,
3245
+ "rollback_failures": [],
3246
+ "secondary_errors": [],
3247
+ "finalization_pending": False,
3248
+ "retained": [],
3249
+ "published": [],
3250
+ "error": None,
3251
+ },
3252
+ }
3253
+
3254
+
3255
+ def _create_stage_root(paths: ProjectPaths) -> Path:
3256
+ """Create coordinator staging under the configured system temp directory."""
3257
+
3258
+ try:
3259
+ system_temp = Path(tempfile.gettempdir()).resolve(strict=True)
3260
+ except (OSError, RuntimeError) as exc:
3261
+ raise SyncInputError(
3262
+ f"system temporary directory is unavailable: {exc}"
3263
+ ) from exc
3264
+ if system_temp == paths.root or system_temp.is_relative_to(paths.root):
3265
+ raise SyncInputError(
3266
+ "system temporary directory must be outside the project tree"
3267
+ )
3268
+ try:
3269
+ created = Path(
3270
+ tempfile.mkdtemp(
3271
+ prefix="proj-doc-builder-stage-",
3272
+ dir=system_temp,
3273
+ )
3274
+ )
3275
+ except OSError as exc:
3276
+ raise SyncInputError(
3277
+ f"cannot create coordinator staging directory: {exc}"
3278
+ ) from exc
3279
+ try:
3280
+ stage_root = created.resolve(strict=True)
3281
+ except (OSError, RuntimeError) as exc:
3282
+ try:
3283
+ shutil.rmtree(created)
3284
+ except OSError as cleanup_exc:
3285
+ raise SyncInputError(
3286
+ "cannot resolve or clean coordinator staging directory: "
3287
+ f"resolve={exc}; cleanup={cleanup_exc}"
3288
+ ) from cleanup_exc
3289
+ raise SyncInputError(
3290
+ f"cannot resolve coordinator staging directory: {exc}"
3291
+ ) from exc
3292
+ if stage_root == paths.root or stage_root.is_relative_to(paths.root):
3293
+ try:
3294
+ shutil.rmtree(stage_root)
3295
+ except OSError as cleanup_exc:
3296
+ raise SyncInputError(
3297
+ "coordinator staging was created inside the project tree and "
3298
+ f"cleanup failed: {cleanup_exc}"
3299
+ ) from cleanup_exc
3300
+ raise SyncInputError("coordinator staging must not be inside the project tree")
3301
+ return stage_root
3302
+
3303
+
3304
+ def _remove_stage_root(
3305
+ stage_root: Path,
3306
+ expected_identity: tuple[int, int, int, int],
3307
+ ) -> None:
3308
+ """Detach only the staging directory created by this invocation, then remove it."""
3309
+
3310
+ if _is_reparse(stage_root):
3311
+ raise SyncInputError(
3312
+ f"coordinator staging directory became indirect: {stage_root}"
3313
+ )
3314
+ try:
3315
+ current = stage_root.lstat()
3316
+ except OSError as exc:
3317
+ raise SyncInputError(
3318
+ f"cannot inspect coordinator staging directory {stage_root}: {exc}"
3319
+ ) from exc
3320
+ if (
3321
+ not stat.S_ISDIR(current.st_mode)
3322
+ or phase4_exit._identity_from_stat(current) != expected_identity
3323
+ ):
3324
+ raise SyncInputError(
3325
+ f"coordinator staging directory identity changed: {stage_root}"
3326
+ )
3327
+
3328
+ detached = stage_root.with_name(
3329
+ f".{stage_root.name}.cleanup-{uuid.uuid4().hex}"
3330
+ )
3331
+ try:
3332
+ phase4_exit._rename_no_replace(stage_root, detached)
3333
+ detached_state = detached.lstat()
3334
+ except OSError as exc:
3335
+ raise SyncInputError(
3336
+ f"cannot detach coordinator staging directory {stage_root}: {exc}"
3337
+ ) from exc
3338
+ if (
3339
+ os.path.lexists(stage_root)
3340
+ or _is_reparse(detached)
3341
+ or not stat.S_ISDIR(detached_state.st_mode)
3342
+ or phase4_exit._identity_from_stat(detached_state) != expected_identity
3343
+ ):
3344
+ raise SyncInputError(
3345
+ f"coordinator staging identity changed during detachment: {stage_root}"
3346
+ )
3347
+ _fsync_parent_directory(detached.parent)
3348
+ try:
3349
+ shutil.rmtree(detached)
3350
+ except OSError as exc:
3351
+ raise SyncInputError(
3352
+ f"cannot clean coordinator staging directory {detached}: {exc}"
3353
+ ) from exc
3354
+ if os.path.lexists(detached):
3355
+ raise SyncInputError(
3356
+ f"detached coordinator staging directory remains: {detached}"
3357
+ )
3358
+ _fsync_parent_directory(detached.parent)
3359
+
3360
+
3361
+ @contextmanager
3362
+ def _coordinator_stage(paths: ProjectPaths) -> Any:
3363
+ stage_root = _create_stage_root(paths)
3364
+ try:
3365
+ identity = phase4_exit._identity_from_stat(stage_root.lstat())
3366
+ except OSError as exc:
3367
+ raise SyncInputError(
3368
+ f"cannot capture coordinator staging identity: {exc}"
3369
+ ) from exc
3370
+ try:
3371
+ yield stage_root
3372
+ except BaseException as primary:
3373
+ try:
3374
+ _remove_stage_root(stage_root, identity)
3375
+ except BaseException as cleanup_exc:
3376
+ if isinstance(primary, SyncPublishError):
3377
+ primary.result["publish"].setdefault("secondary_errors", []).append(
3378
+ {
3379
+ "stage": "staging-cleanup",
3380
+ "error": str(cleanup_exc),
3381
+ }
3382
+ )
3383
+ add_note = getattr(primary, "add_note", None)
3384
+ if callable(add_note):
3385
+ add_note(f"coordinator staging cleanup also failed: {cleanup_exc}")
3386
+ raise
3387
+ else:
3388
+ _remove_stage_root(stage_root, identity)
3389
+
3390
+
3391
+ def synchronize_project(
3392
+ root: str | os.PathLike[str] = ".",
3393
+ *,
3394
+ apply: bool = False,
3395
+ force_full: bool = False,
3396
+ lock_timeout: float = 10.0,
3397
+ run_timestamp: str | None = None,
3398
+ ) -> tuple[dict[str, Any], int]:
3399
+ """Run all gates and optionally publish the prepared transaction."""
3400
+
3401
+ paths = _project_paths(root)
3402
+ recovery_gate = _coordinator_recovery_gate(paths, apply=apply)
3403
+ if recovery_gate is not None:
3404
+ return recovery_gate
3405
+ recovery_gate = _phase4_recovery_gate(paths.root, apply=apply)
3406
+ if recovery_gate is not None:
3407
+ return recovery_gate
3408
+ timestamp = run_timestamp or _utc_now()
3409
+ # Reuse the manifest parser for strict timezone validation before staging.
3410
+ try:
3411
+ datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
3412
+ except ValueError as exc:
3413
+ raise SyncInputError(
3414
+ f"run_timestamp is not valid ISO-8601: {timestamp!r}"
3415
+ ) from exc
3416
+
3417
+ with _coordinator_stage(paths) as stage_root:
3418
+ stage_docs = stage_root / "project_docs"
3419
+ stage_docs.mkdir()
3420
+ prepared = _prepare(
3421
+ paths,
3422
+ stage_docs,
3423
+ run_timestamp=timestamp,
3424
+ force_full=force_full,
3425
+ )
3426
+ recovery_gate = _coordinator_recovery_gate(paths, apply=apply)
3427
+ if recovery_gate is not None:
3428
+ return recovery_gate
3429
+ recovery_gate = _phase4_recovery_gate(paths.root, apply=apply)
3430
+ if recovery_gate is not None:
3431
+ return recovery_gate
3432
+ report = _report(prepared, apply=apply)
3433
+ if not prepared.gates_passed:
3434
+ report["ok"] = False
3435
+ return report, EXIT_GATE_FAILED
3436
+ if not apply:
3437
+ report["ok"] = True
3438
+ return report, EXIT_OK
3439
+
3440
+ # 即使零写入也必须进入统一根锁并执行锁内 Phase 4 recovery、
3441
+ # manifest 和活动 inventory 复核,不能用无锁快速路径伪造完成状态。
3442
+ if not _publish(prepared, report, lock_timeout):
3443
+ report["ok"] = False
3444
+ return report, EXIT_GATE_FAILED
3445
+ report["ok"] = True
3446
+ return report, EXIT_OK
3447
+
3448
+
3449
+ def _coordinator_recovery_gate(
3450
+ paths: ProjectPaths,
3451
+ *,
3452
+ apply: bool,
3453
+ ) -> tuple[dict[str, Any], int] | None:
3454
+ mode = "apply" if apply else "dry-run"
3455
+ try:
3456
+ pending = contract.coordinator_pending_publish_status(paths.root)
3457
+ if pending is None:
3458
+ return None
3459
+ loaded = _load_publish_journal(paths)
3460
+ except (
3461
+ SyncInputError,
3462
+ contract.ProjectDocsContractError,
3463
+ ) as exc:
3464
+ recovery = {"required": True, "detail": str(exc)}
3465
+ else:
3466
+ if loaded is None:
3467
+ recovery = copy.deepcopy(pending)
3468
+ recovery["detail"] = (
3469
+ "coordinator journal residue exists without a prepared journal"
3470
+ )
3471
+ else:
3472
+ journal = loaded.journal
3473
+ recovery = {
3474
+ "required": True,
3475
+ "kind": journal["kind"],
3476
+ "phase": loaded.phase,
3477
+ "created_at": journal["created_at"],
3478
+ "manifest_generation_id": journal["manifest_generation_id"],
3479
+ "transaction_id": journal["transaction_id"],
3480
+ "entries": copy.deepcopy(pending["entries"]),
3481
+ }
3482
+ message = "a pending coordinator publish transaction requires --recover"
3483
+ if isinstance(recovery.get("detail"), str):
3484
+ message = f"{message}: {recovery['detail']}"
3485
+ result = _empty_error_result(mode, "coordinator-recovery-required", message)
3486
+ result["status"] = "coordinator-recovery-required"
3487
+ result["recovery"] = recovery
3488
+ result["planned_writes"] = []
3489
+ return result, EXIT_GATE_FAILED
3490
+
3491
+
3492
+ def _phase4_recovery_gate(
3493
+ root: Path,
3494
+ *,
3495
+ apply: bool,
3496
+ ) -> tuple[dict[str, Any], int] | None:
3497
+ """Block coordinator staging/publish while a Phase 4 journal is unresolved."""
3498
+
3499
+ mode = "apply" if apply else "dry-run"
3500
+ try:
3501
+ recovery = phase4_exit.pending_recovery_status(root)
3502
+ except phase4_exit.Phase4Refusal as exc:
3503
+ recovery = {"required": True, "detail": exc.message}
3504
+ if recovery is None:
3505
+ return None
3506
+ message = "a pending Phase 4 transaction requires phase4_exit.py --recover"
3507
+ if isinstance(recovery.get("detail"), str):
3508
+ message = f"{message}: {recovery['detail']}"
3509
+ result = _empty_error_result(mode, "phase4-recovery-required", message)
3510
+ result["status"] = "phase4-recovery-required"
3511
+ result["phase4"] = {
3512
+ "status": "phase4-recovery-required",
3513
+ "recovery": recovery,
3514
+ }
3515
+ result["scan"] = {
3516
+ "commit_needed": False,
3517
+ "blocked_by_phase4_recovery": True,
3518
+ }
3519
+ result["planned_writes"] = []
3520
+ return result, EXIT_GATE_FAILED
3521
+
3522
+
3523
+ def _empty_error_result(mode: str, code: str, message: str) -> dict[str, Any]:
3524
+ return {
3525
+ "schema_version": RESULT_SCHEMA_VERSION,
3526
+ "ok": False,
3527
+ "mode": mode,
3528
+ "errors": [{"code": code, "message": message}],
3529
+ "publish": {
3530
+ "requested": mode == "apply",
3531
+ "completed": False,
3532
+ "disposition": PublishDisposition.NOT_ATTEMPTED.value,
3533
+ "manifest_disposition": PublishDisposition.NOT_ATTEMPTED.value,
3534
+ "scan_state_disposition": PublishDisposition.NOT_ATTEMPTED.value,
3535
+ "manifest_commit_point": False,
3536
+ "manifest_commit_ambiguous": False,
3537
+ "scan_state_committed": False,
3538
+ "scan_state_commit_ambiguous": False,
3539
+ "partial_commit": False,
3540
+ "rolled_back": False,
3541
+ "rollback_failures": [],
3542
+ "secondary_errors": [],
3543
+ "finalization_pending": False,
3544
+ "retained": [],
3545
+ "published": [],
3546
+ "error": message,
3547
+ },
3548
+ }
3549
+
3550
+
3551
+ def _parser() -> argparse.ArgumentParser:
3552
+ parser = argparse.ArgumentParser(
3553
+ description="Stage, validate, and atomically finalize project_docs synchronization"
3554
+ )
3555
+ parser.add_argument("root", nargs="?", default=".", help="project root")
3556
+ mode = parser.add_mutually_exclusive_group()
3557
+ mode.add_argument(
3558
+ "--apply", action="store_true", help="publish after all gates pass"
3559
+ )
3560
+ mode.add_argument(
3561
+ "--dry-run",
3562
+ action="store_true",
3563
+ help="explicit report-only mode (also the default)",
3564
+ )
3565
+ mode.add_argument(
3566
+ "--recover",
3567
+ action="store_true",
3568
+ help="recover one pending coordinator publish transaction",
3569
+ )
3570
+ parser.add_argument(
3571
+ "--full", action="store_true", help="select all directories for audit"
3572
+ )
3573
+ parser.add_argument("--lock-timeout", type=float, default=10.0)
3574
+ parser.add_argument(
3575
+ "--json", action="store_true", help="emit exactly one JSON document"
3576
+ )
3577
+ return parser
3578
+
3579
+
3580
+ def _emit(result: Mapping[str, Any], *, as_json: bool) -> None:
3581
+ if as_json:
3582
+ sys.stdout.write(contract.stable_json_dumps(dict(result)))
3583
+ return
3584
+ status = "通过" if result.get("ok") else "失败"
3585
+ print(f"proj-doc-builder {result.get('mode', 'unknown')}: {status}")
3586
+ manifest = result.get("manifest")
3587
+ if isinstance(manifest, Mapping):
3588
+ print(
3589
+ f"文档: {manifest.get('total')},generation: "
3590
+ f"{manifest.get('generation_id')}"
3591
+ )
3592
+ for error in result.get("errors", []):
3593
+ if isinstance(error, Mapping):
3594
+ print(
3595
+ f"ERROR [{error.get('code')}]: {error.get('message')}", file=sys.stderr
3596
+ )
3597
+
3598
+
3599
+ def main(argv: Sequence[str] | None = None) -> int:
3600
+ _configure_stdio()
3601
+ args = _parser().parse_args(argv)
3602
+ mode = "recover" if args.recover else "apply" if args.apply else "dry-run"
3603
+ try:
3604
+ if args.lock_timeout < 0:
3605
+ raise SyncInputError("--lock-timeout must be non-negative")
3606
+ if args.recover:
3607
+ if args.full:
3608
+ raise SyncInputError("--full cannot be combined with --recover")
3609
+ result, exit_code = recover_project(
3610
+ args.root,
3611
+ lock_timeout=args.lock_timeout,
3612
+ )
3613
+ else:
3614
+ result, exit_code = synchronize_project(
3615
+ args.root,
3616
+ apply=args.apply,
3617
+ force_full=args.full,
3618
+ lock_timeout=args.lock_timeout,
3619
+ )
3620
+ except SyncPublishError as exc:
3621
+ result = exc.result
3622
+ result["ok"] = False
3623
+ result["errors"].append({"code": "publish-failed", "message": str(exc)})
3624
+ exit_code = EXIT_PUBLISH_FAILED
3625
+ except (
3626
+ OSError,
3627
+ RuntimeError,
3628
+ ValueError,
3629
+ contract.ProjectDocsContractError,
3630
+ ) as exc:
3631
+ result = _empty_error_result(mode, "input-or-operational-error", str(exc))
3632
+ exit_code = EXIT_INPUT_ERROR
3633
+ result["exit_code"] = exit_code
3634
+ _emit(result, as_json=args.json)
3635
+ return exit_code
3636
+
3637
+
3638
+ if __name__ == "__main__":
3639
+ raise SystemExit(main())