@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,380 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Verify and load generated ``project_docs`` documentation for AI consumption.
3
+
4
+ Two modes, both **verify before serving**:
5
+
6
+ ``overview``
7
+ Verified manifest metadata + rendered document tree + per-document
8
+ title/status/bytes and (optionally) its section names. Small by default so a
9
+ fresh agent conversation can load the shape of a whole project cheaply.
10
+
11
+ ``target``
12
+ One verified document — the whole file, or a single ``##`` section.
13
+
14
+ This tool is a *reader*: it never writes. It reuses
15
+ ``project_docs_contract`` so readers and writers share one set of path, link,
16
+ manifest and hashing rules instead of drifting apart.
17
+
18
+ Exit codes:
19
+ 0 loaded and verified
20
+ 1 the manifest does not match the documents (stale index), or the requested
21
+ target/section is not registered
22
+ 2 usage, path-safety or encoding error
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import re
29
+ import sys
30
+ from pathlib import Path
31
+ from typing import Any, Mapping, Sequence
32
+
33
+ import claude_doc_index
34
+ import project_docs_contract as contract
35
+
36
+ EXIT_OK = 0
37
+ EXIT_STALE_OR_MISSING = 1
38
+ EXIT_INPUT_ERROR = 2
39
+
40
+ SCHEMA_VERSION = 1
41
+ DOCS_DIRNAME = "project_docs"
42
+ _SECTION_RE = re.compile(r"^##[ \t]+(?P<title>\S.*?)[ \t]*$", re.MULTILINE)
43
+
44
+
45
+ def _docs_root(project_root: str | Path) -> Path:
46
+ """Accept either the project root or the ``project_docs`` directory itself."""
47
+
48
+ root = Path(project_root)
49
+ candidate = root / DOCS_DIRNAME if (root / DOCS_DIRNAME).is_dir() else root
50
+ return contract.resolve_docs_root(candidate)
51
+
52
+
53
+ def _text_result(mode: str, code: str, message: str) -> dict[str, Any]:
54
+ return {
55
+ "schema_version": SCHEMA_VERSION,
56
+ "ok": False,
57
+ "mode": mode,
58
+ "verified": False,
59
+ "errors": [{"code": code, "message": message}],
60
+ }
61
+
62
+
63
+ def _load_verified_manifest(docs_root: Path, mode: str) -> tuple[dict[str, Any] | None, dict[str, Any] | None, int]:
64
+ """Return ``(manifest, error_result, exit_code)``; exactly one is non-None."""
65
+
66
+ try:
67
+ manifest = contract.load_manifest(
68
+ docs_root,
69
+ verify_files=True,
70
+ verify_complete_set=True,
71
+ )
72
+ except FileNotFoundError:
73
+ return None, _text_result(
74
+ mode,
75
+ "manifest-missing",
76
+ f"no {contract.MANIFEST_FILENAME} in {docs_root}; run the synchronizer first",
77
+ ), EXIT_STALE_OR_MISSING
78
+ except (
79
+ contract.ManifestFileMismatchError,
80
+ contract.ManifestValidationError,
81
+ contract.ManifestSchemaError,
82
+ ) as exc:
83
+ return None, _text_result(
84
+ mode,
85
+ "manifest-stale",
86
+ "manifest does not match the documents on disk, refusing to serve a "
87
+ f"stale index ({exc})",
88
+ ), EXIT_STALE_OR_MISSING
89
+ except contract.ProjectDocsContractError as exc:
90
+ return None, _text_result(mode, "manifest-invalid", str(exc)), EXIT_STALE_OR_MISSING
91
+ except (OSError, ValueError) as exc:
92
+ return None, _text_result(mode, "manifest-unreadable", str(exc)), EXIT_STALE_OR_MISSING
93
+ return manifest, None, EXIT_OK
94
+
95
+
96
+ def split_sections(content: str) -> list[dict[str, str]]:
97
+ """Split Markdown into ``##`` sections, preserving order and body text."""
98
+
99
+ matches = list(_SECTION_RE.finditer(content))
100
+ sections: list[dict[str, str]] = []
101
+ for index, match in enumerate(matches):
102
+ title = match.group("title").strip()
103
+ start = match.end()
104
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(content)
105
+ sections.append({"title": title, "body": content[start:end].strip()})
106
+ return sections
107
+
108
+
109
+ def _normalize_target(value: str) -> str:
110
+ """Map a source directory, a document path, or a project-relative path to a doc path."""
111
+
112
+ raw = value.strip().replace("\\", "/")
113
+ if raw.startswith("./"):
114
+ raw = raw[2:]
115
+ if raw.startswith(f"{DOCS_DIRNAME}/"):
116
+ raw = raw[len(DOCS_DIRNAME) + 1 :]
117
+ if raw in {"", ".", "/"}:
118
+ raw = "index.md"
119
+ elif not raw.endswith(".md"):
120
+ raw = raw.rstrip("/") + ".md"
121
+ return contract.validate_manifest_relative_path(raw).as_posix()
122
+
123
+
124
+ def _entry_by_path(manifest: Mapping[str, Any], relative: str) -> dict[str, Any] | None:
125
+ entries = manifest.get("files", [])
126
+ folded = relative.casefold()
127
+ for entry in entries:
128
+ if isinstance(entry, Mapping) and str(entry.get("path", "")).casefold() == folded:
129
+ return dict(entry)
130
+ return None
131
+
132
+
133
+ def overview(
134
+ manifest: Mapping[str, Any],
135
+ docs_root: Path,
136
+ *,
137
+ limit: int = 80,
138
+ sections: int = 6,
139
+ include_tree: bool = True,
140
+ ) -> dict[str, Any]:
141
+ """Verified project shape: tree, counts, and per-document metadata."""
142
+
143
+ entries = [dict(item) for item in manifest.get("files", []) if isinstance(item, Mapping)]
144
+ entries.sort(key=lambda item: str(item.get("path", "")))
145
+ returned = entries if limit <= 0 else entries[:limit]
146
+
147
+ documents: list[dict[str, Any]] = []
148
+ for entry in returned:
149
+ relative = str(entry.get("path", ""))
150
+ item = {
151
+ "path": relative,
152
+ "title": entry.get("title"),
153
+ "status": entry.get("status"),
154
+ "bytes": entry.get("bytes"),
155
+ "depth": entry.get("depth"),
156
+ }
157
+ if sections > 0:
158
+ try:
159
+ content = contract.read_project_document(docs_root, relative)
160
+ except contract.ProjectDocsContractError:
161
+ content = ""
162
+ item["sections"] = [item_["title"] for item_ in split_sections(content)][:sections]
163
+ documents.append(item)
164
+
165
+ result: dict[str, Any] = {
166
+ "schema_version": SCHEMA_VERSION,
167
+ "ok": True,
168
+ "mode": "overview",
169
+ "verified": True,
170
+ "docs_root": DOCS_DIRNAME,
171
+ "manifest": {
172
+ "schema_version": manifest.get("schema_version"),
173
+ "generation_id": manifest.get("generation_id"),
174
+ "last_synced": manifest.get("last_synced"),
175
+ "total": manifest.get("total"),
176
+ "depth_counts": manifest.get("depth_counts"),
177
+ },
178
+ "counts": {
179
+ "documents": len(entries),
180
+ "returned": len(documents),
181
+ },
182
+ "documents": documents,
183
+ }
184
+ if include_tree:
185
+ result["tree"] = claude_doc_index.render_document_tree(manifest)
186
+ if len(documents) < len(entries):
187
+ result["omitted"] = {
188
+ "documents": len(entries) - len(documents),
189
+ "reason": f"limit={limit}; pass --limit 0 for every document",
190
+ }
191
+ return result
192
+
193
+
194
+ def target(
195
+ manifest: Mapping[str, Any],
196
+ docs_root: Path,
197
+ requested: str,
198
+ *,
199
+ section: str | None = None,
200
+ ) -> tuple[dict[str, Any], int]:
201
+ """Load one verified document, optionally narrowed to a single ``##`` section."""
202
+
203
+ try:
204
+ relative = _normalize_target(requested)
205
+ except (contract.PathValidationError, ValueError) as exc:
206
+ return _text_result("target", "unsafe-target", str(exc)), EXIT_INPUT_ERROR
207
+
208
+ entry = _entry_by_path(manifest, relative)
209
+ if entry is None:
210
+ return _text_result(
211
+ "target",
212
+ "target-not-registered",
213
+ f"{relative} is not registered in the manifest; "
214
+ "run --dry-run to see the current worklist",
215
+ ), EXIT_STALE_OR_MISSING
216
+
217
+ canonical = str(entry["path"])
218
+ try:
219
+ content = contract.read_project_document(docs_root, canonical)
220
+ except contract.ProjectDocsContractError as exc:
221
+ return _text_result("target", "target-unreadable", str(exc)), EXIT_INPUT_ERROR
222
+
223
+ result: dict[str, Any] = {
224
+ "schema_version": SCHEMA_VERSION,
225
+ "ok": True,
226
+ "mode": "target",
227
+ "verified": True,
228
+ "doc": {
229
+ "path": canonical,
230
+ "title": entry.get("title"),
231
+ "status": entry.get("status"),
232
+ "bytes": entry.get("bytes"),
233
+ "sha256": entry.get("sha256"),
234
+ "synced_at": entry.get("synced_at"),
235
+ },
236
+ "available_sections": [item["title"] for item in split_sections(content)],
237
+ }
238
+
239
+ if section is None:
240
+ result["content"] = content
241
+ return result, EXIT_OK
242
+
243
+ wanted = section.strip().casefold()
244
+ for item in split_sections(content):
245
+ if item["title"].casefold() == wanted:
246
+ result["section"] = item["title"]
247
+ result["content"] = item["body"]
248
+ return result, EXIT_OK
249
+ failure = _text_result(
250
+ "target",
251
+ "section-not-found",
252
+ f"no '## {section}' section in {canonical}",
253
+ )
254
+ failure["available_sections"] = result["available_sections"]
255
+ return failure, EXIT_STALE_OR_MISSING
256
+
257
+
258
+ def execute(
259
+ project_root: str | Path,
260
+ *,
261
+ mode: str = "overview",
262
+ requested: str | None = None,
263
+ section: str | None = None,
264
+ limit: int = 80,
265
+ sections: int = 6,
266
+ include_tree: bool = True,
267
+ ) -> tuple[dict[str, Any], int]:
268
+ """Run one load: verify the manifest, then serve the requested view."""
269
+
270
+ try:
271
+ docs_root = _docs_root(project_root)
272
+ except contract.ProjectDocsContractError as exc:
273
+ return _text_result(mode, "docs-root-invalid", str(exc)), EXIT_INPUT_ERROR
274
+ except OSError as exc:
275
+ return _text_result(mode, "project-root-invalid", str(exc)), EXIT_INPUT_ERROR
276
+
277
+ manifest, error, exit_code = _load_verified_manifest(docs_root, mode)
278
+ if manifest is None:
279
+ assert error is not None
280
+ return error, exit_code
281
+
282
+ if mode == "overview":
283
+ return overview(
284
+ manifest,
285
+ docs_root,
286
+ limit=limit,
287
+ sections=sections,
288
+ include_tree=include_tree,
289
+ ), EXIT_OK
290
+ if mode == "target":
291
+ if requested is None:
292
+ return _text_result(mode, "target-required", "--target is required for target mode"), EXIT_INPUT_ERROR
293
+ return target(manifest, docs_root, requested, section=section)
294
+ return _text_result(mode, "unknown-mode", f"unsupported mode {mode!r}"), EXIT_INPUT_ERROR
295
+
296
+
297
+ def _parser() -> argparse.ArgumentParser:
298
+ parser = argparse.ArgumentParser(
299
+ description="Verify and load generated project_docs documentation",
300
+ )
301
+ parser.add_argument("root", nargs="?", default=".", help="project root or project_docs")
302
+ parser.add_argument(
303
+ "--mode",
304
+ choices=("overview", "target"),
305
+ default="overview",
306
+ help="overview = project shape; target = one document",
307
+ )
308
+ parser.add_argument(
309
+ "--target",
310
+ "-t",
311
+ default=None,
312
+ help="source directory, document path, or project-relative path",
313
+ )
314
+ parser.add_argument(
315
+ "--section",
316
+ "-s",
317
+ default=None,
318
+ help="with --target: return only this '##' section",
319
+ )
320
+ parser.add_argument(
321
+ "--limit",
322
+ type=int,
323
+ default=80,
324
+ help="max documents in overview (0 = all)",
325
+ )
326
+ parser.add_argument(
327
+ "--sections",
328
+ type=int,
329
+ default=6,
330
+ help="max section names per document in overview (0 = none)",
331
+ )
332
+ parser.add_argument("--no-tree", action="store_true", help="omit the rendered tree")
333
+ parser.add_argument("--json", action="store_true", help="emit exactly one JSON document")
334
+ return parser
335
+
336
+
337
+ def _emit(result: Mapping[str, Any], *, as_json: bool) -> None:
338
+ if as_json:
339
+ sys.stdout.write(contract.stable_json_dumps(dict(result)))
340
+ return
341
+ if not result.get("ok"):
342
+ for error in result.get("errors", []):
343
+ print(f"ERROR [{error['code']}]: {error['message']}", file=sys.stderr)
344
+ return
345
+ if result.get("mode") == "overview":
346
+ manifest = result["manifest"]
347
+ print(
348
+ f"documents: {result['counts']['documents']} "
349
+ f"(returned {result['counts']['returned']}) "
350
+ f"generation: {manifest['generation_id']}"
351
+ )
352
+ print(result.get("tree", ""))
353
+ for item in result["documents"]:
354
+ sections = ", ".join(item.get("sections") or [])
355
+ print(f"- {item['path']} — {item['title']} {item['status']}")
356
+ if sections:
357
+ print(f" sections: {sections}")
358
+ return
359
+ print(result.get("content", ""))
360
+
361
+
362
+ def main(argv: Sequence[str] | None = None) -> int:
363
+ contract.configure_stdio_utf8()
364
+ args = _parser().parse_args(argv)
365
+ result, exit_code = execute(
366
+ args.root,
367
+ mode=args.mode,
368
+ requested=args.target,
369
+ section=args.section,
370
+ limit=args.limit,
371
+ sections=args.sections,
372
+ include_tree=not args.no_tree,
373
+ )
374
+ result["exit_code"] = exit_code
375
+ _emit(result, as_json=args.json)
376
+ return exit_code
377
+
378
+
379
+ if __name__ == "__main__":
380
+ raise SystemExit(main())
@@ -0,0 +1,205 @@
1
+ # -*- coding: utf-8 -*-
2
+ """机械规范化可精确识别的历史 ``Last synced`` 损坏尾缀。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import re
8
+ import sys
9
+ from dataclasses import dataclass
10
+ from pathlib import Path, PurePosixPath
11
+ from typing import Sequence
12
+
13
+ from link_check import discover_documents
14
+ from project_docs_contract import (
15
+ ProjectDocsContractError,
16
+ atomic_write_utf8,
17
+ configure_stdio_utf8,
18
+ parse_last_synced_marker,
19
+ project_sync_lock,
20
+ read_project_document,
21
+ resolve_docs_root,
22
+ stable_json_dumps,
23
+ )
24
+
25
+ # 历史迁移 bug 只会在完整 marker 后追加字面量 `` v3.1 -->``。
26
+ # 使用逐行锚定,避免“修复”任何其他自由文本或不完整注释。
27
+ _DUPLICATE_V31_TAIL_RE = re.compile(
28
+ r"^(?P<marker><!--[ \t]*Last[ \t]+synced[ \t]*:[^\r\n]*?-->)[ \t]+"
29
+ r"v3\.1[ \t]*-->[ \t]*(?=\r?$)",
30
+ re.IGNORECASE | re.MULTILINE,
31
+ )
32
+
33
+
34
+ class MarkerNormalizationError(ValueError):
35
+ """marker 候选不满足可机械修复的精确前置条件。"""
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class MarkerChange:
40
+ path: str
41
+ line: int
42
+ before: str
43
+ after: str
44
+ original_content: str
45
+ normalized_content: str
46
+
47
+
48
+ def normalize_marker_content(
49
+ content: str, *, path: str = "<memory>"
50
+ ) -> tuple[str, list[dict]]:
51
+ """只移除精确的重复 v3.1 尾缀,保留原 marker 时间值。"""
52
+
53
+ changes: list[dict] = []
54
+
55
+ def replace(match: re.Match[str]) -> str:
56
+ marker = match.group("marker")
57
+ if parse_last_synced_marker(marker) is None:
58
+ raise MarkerNormalizationError(f"无法解析 Last synced marker: {path}")
59
+ line = content.count("\n", 0, match.start()) + 1
60
+ changes.append(
61
+ {
62
+ "path": path,
63
+ "line": line,
64
+ "before": match.group(0),
65
+ "after": marker,
66
+ }
67
+ )
68
+ return marker
69
+
70
+ normalized = _DUPLICATE_V31_TAIL_RE.sub(replace, content)
71
+ return normalized, changes
72
+
73
+
74
+ def collect_marker_changes(project_docs: str | Path) -> list[MarkerChange]:
75
+ """安全枚举文档并收集全部候选,不执行写入。"""
76
+
77
+ root = resolve_docs_root(project_docs)
78
+ collected: list[MarkerChange] = []
79
+ for relative, _ in discover_documents(root):
80
+ original = read_project_document(root, relative)
81
+ normalized, changes = normalize_marker_content(original, path=relative)
82
+ for item in changes:
83
+ collected.append(
84
+ MarkerChange(
85
+ path=relative,
86
+ line=item["line"],
87
+ before=item["before"],
88
+ after=item["after"],
89
+ original_content=original,
90
+ normalized_content=normalized,
91
+ )
92
+ )
93
+ collected.sort(key=lambda item: (item.path, item.line))
94
+ return collected
95
+
96
+
97
+ def _unique_file_changes(changes: Sequence[MarkerChange]) -> list[MarkerChange]:
98
+ unique: dict[str, MarkerChange] = {}
99
+ for change in changes:
100
+ previous = unique.get(change.path)
101
+ if (
102
+ previous is not None
103
+ and previous.normalized_content != change.normalized_content
104
+ ):
105
+ raise MarkerNormalizationError(
106
+ f"同一文档产生不一致的 marker 候选: {change.path}"
107
+ )
108
+ unique[change.path] = change
109
+ return [unique[path] for path in sorted(unique)]
110
+
111
+
112
+ def apply_marker_changes(
113
+ project_docs: str | Path,
114
+ changes: Sequence[MarkerChange],
115
+ *,
116
+ lock_timeout: float = 10.0,
117
+ ) -> list[str]:
118
+ """在单一锁下发布;失败时尽力逐文件回滚。"""
119
+
120
+ root = resolve_docs_root(project_docs)
121
+ files = _unique_file_changes(changes)
122
+ applied: list[MarkerChange] = []
123
+ with project_sync_lock(root.parent, timeout=lock_timeout):
124
+ try:
125
+ for change in files:
126
+ pure_path = PurePosixPath(change.path)
127
+ target = root.joinpath(*pure_path.parts)
128
+ if read_project_document(root, change.path) != change.original_content:
129
+ raise MarkerNormalizationError(
130
+ f"发布前文档已变化,拒绝覆盖: {change.path}"
131
+ )
132
+ atomic_write_utf8(target, change.normalized_content)
133
+ applied.append(change)
134
+ except BaseException as exc:
135
+ rollback_errors: list[str] = []
136
+ for change in reversed(applied):
137
+ target = root.joinpath(*PurePosixPath(change.path).parts)
138
+ try:
139
+ current = read_project_document(root, change.path)
140
+ if current != change.normalized_content:
141
+ rollback_errors.append(
142
+ f"{change.path}: 回滚冲突,文件已被并发修改"
143
+ )
144
+ continue
145
+ atomic_write_utf8(target, change.original_content)
146
+ except Exception as rollback_exc: # pragma: no cover - 双重 I/O 故障
147
+ rollback_errors.append(f"{change.path}: {rollback_exc}")
148
+ if rollback_errors:
149
+ raise MarkerNormalizationError(
150
+ f"marker 发布失败且回滚不完整: {exc}; " + "; ".join(rollback_errors)
151
+ ) from exc
152
+ raise
153
+ return [change.path for change in files]
154
+
155
+
156
+ def _parser() -> argparse.ArgumentParser:
157
+ parser = argparse.ArgumentParser(description="规范化历史 Last synced marker 尾缀")
158
+ parser.add_argument("--project-docs", default="project_docs")
159
+ parser.add_argument("--apply", action="store_true", help="原子写入候选修改")
160
+ parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
161
+ return parser
162
+
163
+
164
+ def main(argv: Sequence[str] | None = None) -> int:
165
+ configure_stdio_utf8()
166
+ args = _parser().parse_args(argv)
167
+ try:
168
+ changes = collect_marker_changes(args.project_docs)
169
+ applied_paths: list[str] = []
170
+ if args.apply and changes:
171
+ applied_paths = apply_marker_changes(args.project_docs, changes)
172
+ result = {
173
+ "ok": True,
174
+ "candidate_count": len(changes),
175
+ "candidate_file_count": len({change.path for change in changes}),
176
+ "applied": bool(args.apply and changes),
177
+ "applied_paths": applied_paths,
178
+ "changes": [
179
+ {
180
+ "path": change.path,
181
+ "line": change.line,
182
+ "before": change.before,
183
+ "after": change.after,
184
+ }
185
+ for change in changes
186
+ ],
187
+ }
188
+ if args.json:
189
+ print(stable_json_dumps(result), end="")
190
+ else:
191
+ action = "已规范化" if args.apply else "待规范化"
192
+ print(
193
+ f"{action}: {len(changes)} 处 / {len(set(c.path for c in changes))} 个文件"
194
+ )
195
+ return 0
196
+ except (OSError, MarkerNormalizationError, ProjectDocsContractError) as exc:
197
+ if args.json:
198
+ print(stable_json_dumps({"ok": False, "error": str(exc)}), end="")
199
+ else:
200
+ print(f"ERROR: {exc}", file=sys.stderr)
201
+ return 2
202
+
203
+
204
+ if __name__ == "__main__":
205
+ raise SystemExit(main())
@@ -0,0 +1,57 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Phase 4 modular subpackage providing structured access to Phase 4 subsystems.
3
+
4
+ Submodules:
5
+ - ``platform_handles``: Platform-specific Win32/POSIX handles, locks, reparse points, and fsync.
6
+ - ``cas_storage``: Content-Addressable Storage, SHA-256 fingerprinting, receipts, and payloads.
7
+ - ``journal``: Crash-consistent transaction journal, state machine, and recovery.
8
+ - ``engine``: Candidate analysis, quarantine execution, receipt restoration, and coordinator integration.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import phase4_exit as _core
14
+
15
+ # Re-export core constants, classes, and entrypoints
16
+ EXIT_OK = _core.EXIT_OK
17
+ EXIT_REFUSED = _core.EXIT_REFUSED
18
+ EXIT_OPERATIONAL_FAILURE = _core.EXIT_OPERATIONAL_FAILURE
19
+
20
+ AUTO_MARKER = _core.AUTO_MARKER
21
+ QUARANTINE_DIRNAME = _core.QUARANTINE_DIRNAME
22
+ RECEIPT_FILENAME = _core.RECEIPT_FILENAME
23
+ PAYLOAD_DIRNAME = _core.PAYLOAD_DIRNAME
24
+ QUARANTINE_REASON = _core.QUARANTINE_REASON
25
+
26
+ Phase4Error = _core.Phase4Error
27
+ Phase4Refusal = _core.Phase4Refusal
28
+ Phase4OperationalError = _core.Phase4OperationalError
29
+ ReceiptRecord = _core.ReceiptRecord
30
+ ProjectAnalysis = _core.ProjectAnalysis
31
+
32
+ analyze_project = _core.analyze_project
33
+ quarantine_candidates = _core.quarantine_candidates
34
+ restore_receipt = _core.restore_receipt
35
+ recover_pending_transactions = _core.recover_pending_transactions
36
+ main = _core.main
37
+
38
+ __all__ = [
39
+ "EXIT_OK",
40
+ "EXIT_REFUSED",
41
+ "EXIT_OPERATIONAL_FAILURE",
42
+ "AUTO_MARKER",
43
+ "QUARANTINE_DIRNAME",
44
+ "RECEIPT_FILENAME",
45
+ "PAYLOAD_DIRNAME",
46
+ "QUARANTINE_REASON",
47
+ "Phase4Error",
48
+ "Phase4Refusal",
49
+ "Phase4OperationalError",
50
+ "ReceiptRecord",
51
+ "ProjectAnalysis",
52
+ "analyze_project",
53
+ "quarantine_candidates",
54
+ "restore_receipt",
55
+ "recover_pending_transactions",
56
+ "main",
57
+ ]
@@ -0,0 +1,18 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Content-Addressable Storage (CAS), payload snapshots, receipts, and hash verification."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import phase4_exit as _core
7
+
8
+ text_snapshot = getattr(_core, "_text_snapshot", None)
9
+ write_exclusive_snapshot = getattr(_core, "_write_exclusive_snapshot", None)
10
+ validate_manifest_snapshot = getattr(_core, "_validate_manifest_snapshot", None)
11
+ require_receipt_closed_state = getattr(_core, "_require_receipt_closed_state", None)
12
+
13
+ __all__ = [
14
+ "text_snapshot",
15
+ "write_exclusive_snapshot",
16
+ "validate_manifest_snapshot",
17
+ "require_receipt_closed_state",
18
+ ]
@@ -0,0 +1,20 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Phase 4 engine execution: analysis, quarantine, restore, and coordinator integration."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import phase4_exit as _core
7
+
8
+ analyze_project = _core.analyze_project
9
+ quarantine_candidates = _core.quarantine_candidates
10
+ restore_receipt = _core.restore_receipt
11
+ recover_pending_transactions = _core.recover_pending_transactions
12
+ main = _core.main
13
+
14
+ __all__ = [
15
+ "analyze_project",
16
+ "quarantine_candidates",
17
+ "restore_receipt",
18
+ "recover_pending_transactions",
19
+ "main",
20
+ ]