@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,781 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Focused tests for the shared project_docs contract."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import copy
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ import project_docs_contract as contract
13
+
14
+ SYNCED_1 = "2026-07-29T12:00:00+08:00"
15
+ SYNCED_2 = "2026-07-30T12:00:00+08:00"
16
+
17
+
18
+ def _write_doc(
19
+ path: Path,
20
+ title: str,
21
+ *,
22
+ status: str = "✅",
23
+ synced_at: str | None = SYNCED_1,
24
+ repeated_suffix: bool = False,
25
+ ) -> None:
26
+ path.parent.mkdir(parents=True, exist_ok=True)
27
+ marker = ""
28
+ if synced_at is not None:
29
+ marker = f"<!-- Last synced: {synced_at} by proj-doc-builder v4.0 -->"
30
+ if repeated_suffix:
31
+ marker += " by proj-doc-builder v4.0 -->"
32
+ marker += "\n"
33
+ path.write_text(
34
+ f"# {title}\n\n{marker}\n## 状态\n\n{status} 完整\n",
35
+ encoding="utf-8",
36
+ )
37
+
38
+
39
+ def _make_docs(tmp_path: Path) -> Path:
40
+ root = tmp_path / "project_docs"
41
+ root.mkdir()
42
+ _write_doc(root / "root.md", "根文档")
43
+ _write_doc(root / "group" / "child.md", "子文档", status="🔶")
44
+ return root
45
+
46
+
47
+ def test_valid_manifest_paths_and_depth() -> None:
48
+ assert contract.validate_manifest_relative_path("root.md").as_posix() == "root.md"
49
+ assert contract.validate_manifest_relative_path("a/b.md").as_posix() == "a/b.md"
50
+ assert contract.manifest_path_depth("root.md") == 0
51
+ assert contract.manifest_path_depth("a/b.md") == 1
52
+ assert contract.manifest_path_depth("a/b/c.md") == 2
53
+
54
+
55
+ @pytest.mark.parametrize(
56
+ "value",
57
+ [
58
+ "",
59
+ "/absolute.md",
60
+ "C:/absolute.md",
61
+ "C:relative.md",
62
+ "//server/share.md",
63
+ "bad\x00name.md",
64
+ r"a\b.md",
65
+ ".",
66
+ "..",
67
+ "./a.md",
68
+ "a/../b.md",
69
+ "a/./b.md",
70
+ "a//b.md",
71
+ "a/",
72
+ "not-markdown.txt",
73
+ ".md",
74
+ "upper.MD",
75
+ "folder/report:meta.md",
76
+ "folder/bad?.md",
77
+ "folder/name./child.md",
78
+ "folder/name /child.md",
79
+ "CON.md",
80
+ "folder/LPT1.log.md",
81
+ "bad\x01name.md",
82
+ ],
83
+ )
84
+ def test_invalid_manifest_paths(value: str) -> None:
85
+ with pytest.raises(contract.PathValidationError):
86
+ contract.validate_manifest_relative_path(value)
87
+
88
+
89
+ def test_casefold_path_conflicts_are_rejected() -> None:
90
+ with pytest.raises(contract.PathConflictError, match="case conflict"):
91
+ contract.ensure_unique_manifest_paths(["Folder/A.md", "folder/a.md"])
92
+ with pytest.raises(contract.PathConflictError, match="duplicate"):
93
+ contract.ensure_unique_manifest_paths(["same.md", "same.md"])
94
+
95
+
96
+ def test_manifest_symlink_escape_is_rejected(tmp_path: Path) -> None:
97
+ root = tmp_path / "project_docs"
98
+ root.mkdir()
99
+ outside = tmp_path / "outside.md"
100
+ _write_doc(outside, "外部")
101
+ link = root / "escape.md"
102
+ try:
103
+ link.symlink_to(outside)
104
+ except (NotImplementedError, OSError) as exc:
105
+ pytest.skip(f"symlink creation is unavailable: {exc}")
106
+
107
+ with pytest.raises(contract.PathValidationError, match="outside"):
108
+ contract.resolve_manifest_document(root, "escape.md")
109
+
110
+
111
+ def test_manifest_discovery_rejects_external_directory_link_and_loop(
112
+ tmp_path: Path,
113
+ ) -> None:
114
+ root = _make_docs(tmp_path)
115
+ outside = tmp_path / "outside_docs"
116
+ outside.mkdir()
117
+ _write_doc(outside / "secret.md", "外部")
118
+ external_link = root / "external"
119
+ try:
120
+ external_link.symlink_to(outside, target_is_directory=True)
121
+ except (NotImplementedError, OSError) as exc:
122
+ pytest.skip(f"directory symlink creation is unavailable: {exc}")
123
+
124
+ with pytest.raises(contract.PathValidationError, match="symlink or reparse point"):
125
+ contract.build_manifest(root, last_synced=SYNCED_1)
126
+
127
+ external_link.unlink()
128
+ loop = root / "loop"
129
+ loop.symlink_to(root, target_is_directory=True)
130
+ with pytest.raises(contract.PathValidationError, match="symlink or reparse point"):
131
+ contract.build_manifest(root, last_synced=SYNCED_1)
132
+
133
+
134
+ def test_markdown_link_rules_and_structured_results(tmp_path: Path) -> None:
135
+ root = tmp_path / "project_docs"
136
+ source = root / "a" / "source.md"
137
+ target = root / "b" / "target.md"
138
+ encoded_target = root / "b" / "目标 文档.md"
139
+ _write_doc(source, "源")
140
+ _write_doc(target, "目标")
141
+ _write_doc(encoded_target, "编码目标")
142
+
143
+ content = "\n".join(
144
+ [
145
+ "[extensionless](../b/target)",
146
+ "[encoded](<../b/%E7%9B%AE%E6%A0%87%20%E6%96%87%E6%A1%A3.md?mode=1#part>)",
147
+ "[web](https://example.com/x.md)",
148
+ "[mail](mailto:test@example.com)",
149
+ "[anchor](#section)",
150
+ "[source](../code/tool.py)",
151
+ "[other](../manual.pdf)",
152
+ "[outside](../../../outside.md)",
153
+ "[encoded-outside](%2E%2E/%2E%2E/outside.md)",
154
+ "[encoded-backslash](..%5Cb%5Ctarget.md)",
155
+ "[encoded-nul](../b/target%00.md)",
156
+ "[ads](../b/report:meta.md)",
157
+ "[device](../b/CON.md)",
158
+ "[absolute](/absolute.md)",
159
+ "[bad-percent](../b/%FF.md)",
160
+ ]
161
+ )
162
+ links = contract.parse_markdown_links(
163
+ content,
164
+ source_doc=source,
165
+ docs_root=root,
166
+ )
167
+ by_text = {link.text: link for link in links}
168
+
169
+ extensionless = by_text["extensionless"]
170
+ assert extensionless.disposition is contract.LinkDisposition.LOCAL_DOCUMENT
171
+ assert extensionless.project_relative_path == "b/target.md"
172
+ assert extensionless.exists is True
173
+
174
+ encoded = by_text["encoded"]
175
+ assert encoded.disposition is contract.LinkDisposition.LOCAL_DOCUMENT
176
+ assert encoded.project_relative_path == "b/目标 文档.md"
177
+ assert encoded.query == "mode=1"
178
+ assert encoded.fragment == "part"
179
+ assert encoded.exists is True
180
+
181
+ for text in ("web", "mail", "anchor", "source", "other"):
182
+ assert by_text[text].disposition is contract.LinkDisposition.SKIPPED
183
+ for text in (
184
+ "outside",
185
+ "encoded-outside",
186
+ "encoded-backslash",
187
+ "encoded-nul",
188
+ "ads",
189
+ "device",
190
+ "absolute",
191
+ "bad-percent",
192
+ ):
193
+ assert by_text[text].disposition is contract.LinkDisposition.INVALID
194
+
195
+
196
+ def test_reference_style_and_html_links_are_resolved(tmp_path: Path) -> None:
197
+ root = tmp_path / "project_docs"
198
+ source = root / "refs" / "source.md"
199
+ target = root / "target.md"
200
+ _write_doc(source, "源")
201
+ _write_doc(target, "目标")
202
+ content = "\n".join(
203
+ [
204
+ "[full][target-id]",
205
+ "[collapsed][]",
206
+ "[shortcut]",
207
+ '<a href="../target.md#html">HTML</a>',
208
+ "",
209
+ "[target-id]: ../target.md",
210
+ "[collapsed]: <../target.md?mode=1>",
211
+ "[shortcut]: ../target",
212
+ ]
213
+ )
214
+
215
+ links = contract.parse_markdown_links(
216
+ content,
217
+ source_doc=source,
218
+ docs_root=root,
219
+ )
220
+ by_text = {link.text: link for link in links if link.text}
221
+
222
+ assert by_text["full"].project_relative_path == "target.md"
223
+ assert by_text["collapsed"].query == "mode=1"
224
+ assert by_text["shortcut"].project_relative_path == "target.md"
225
+ html = next(link for link in links if link.text == "")
226
+ assert html.project_relative_path == "target.md"
227
+ assert html.fragment == "html"
228
+
229
+
230
+ def test_link_resolution_rejects_symlink_escape(tmp_path: Path) -> None:
231
+ root = tmp_path / "project_docs"
232
+ root.mkdir()
233
+ source = root / "source.md"
234
+ _write_doc(source, "源")
235
+ outside = tmp_path / "outside.md"
236
+ _write_doc(outside, "外部")
237
+ link = root / "linked.md"
238
+ try:
239
+ link.symlink_to(outside)
240
+ except (NotImplementedError, OSError) as exc:
241
+ pytest.skip(f"symlink creation is unavailable: {exc}")
242
+
243
+ result = contract.resolve_markdown_target(
244
+ "linked.md",
245
+ source_doc=source,
246
+ docs_root=root,
247
+ )
248
+ assert result.disposition is contract.LinkDisposition.INVALID
249
+ assert result.reason == "target-outside-docs-root"
250
+
251
+
252
+ def test_read_markdown_links_rejects_external_source_before_read(
253
+ tmp_path: Path,
254
+ ) -> None:
255
+ root = tmp_path / "project_docs"
256
+ root.mkdir()
257
+ outside = tmp_path / "outside.md"
258
+ outside.write_bytes(b"secret-\xff")
259
+ source = root / "source.md"
260
+ try:
261
+ source.symlink_to(outside)
262
+ except (NotImplementedError, OSError) as exc:
263
+ pytest.skip(f"symlink creation is unavailable: {exc}")
264
+
265
+ with pytest.raises(contract.LinkResolutionError, match="outside"):
266
+ contract.read_markdown_links(source, root)
267
+
268
+
269
+ def test_secure_document_read_rejects_swap_to_external_symlink(
270
+ tmp_path: Path,
271
+ monkeypatch: pytest.MonkeyPatch,
272
+ ) -> None:
273
+ root = tmp_path / "project_docs"
274
+ root.mkdir()
275
+ victim = root / "victim.md"
276
+ outside = tmp_path / "outside.md"
277
+ _write_doc(victim, "原始")
278
+ _write_doc(outside, "外部")
279
+ original_resolve = contract.resolve_manifest_document
280
+ swapped = False
281
+
282
+ def swapping_resolve(*args: object, **kwargs: object) -> contract.SafeManifestPath:
283
+ nonlocal swapped
284
+ safe_path = original_resolve(*args, **kwargs)
285
+ if safe_path.relative_path == "victim.md" and not swapped:
286
+ try:
287
+ victim.unlink()
288
+ victim.symlink_to(outside)
289
+ except (NotImplementedError, OSError) as exc:
290
+ pytest.skip(f"symlink creation is unavailable: {exc}")
291
+ swapped = True
292
+ return safe_path
293
+
294
+ monkeypatch.setattr(contract, "resolve_manifest_document", swapping_resolve)
295
+ with pytest.raises(contract.PathValidationError):
296
+ contract.read_project_document(root, "victim.md")
297
+
298
+
299
+ def test_compute_relative_doc_link_uses_posix_paths(tmp_path: Path) -> None:
300
+ root = _make_docs(tmp_path)
301
+ link = contract.compute_relative_doc_link(
302
+ "group/child.md",
303
+ "root.md",
304
+ root,
305
+ )
306
+ assert link == "../root.md"
307
+
308
+ future_link = contract.compute_relative_doc_link(
309
+ "new/source.md",
310
+ "future/target.md",
311
+ root,
312
+ )
313
+ assert future_link == "../future/target.md"
314
+ with pytest.raises(contract.PathValidationError):
315
+ contract.compute_relative_doc_link(
316
+ "new/source.md",
317
+ "future/target.md",
318
+ root,
319
+ must_exist=True,
320
+ )
321
+
322
+
323
+ def test_last_synced_parser_ignores_repeated_tail(tmp_path: Path) -> None:
324
+ root = tmp_path / "project_docs"
325
+ root.mkdir()
326
+ doc = root / "marker.md"
327
+ _write_doc(doc, "Marker", repeated_suffix=True)
328
+ content = contract.read_utf8(doc)
329
+ assert contract.parse_last_synced_marker(content) == SYNCED_1
330
+ metadata = contract.parse_document_metadata(content, "marker.md")
331
+ assert metadata.title == "Marker"
332
+ assert metadata.status == "✅"
333
+ assert metadata.synced_at == SYNCED_1
334
+
335
+
336
+ def test_strict_utf8_and_json_reject_corruption(tmp_path: Path) -> None:
337
+ bad_text = tmp_path / "bad.md"
338
+ bad_text.write_bytes(b"valid\xffinvalid")
339
+ with pytest.raises(contract.StrictUtf8Error):
340
+ contract.read_utf8(bad_text)
341
+
342
+ duplicate = tmp_path / "duplicate.json"
343
+ duplicate.write_text('{"a": 1, "a": 2}\n', encoding="utf-8")
344
+ with pytest.raises(contract.JsonContractError, match="duplicate"):
345
+ contract.read_json_strict(duplicate)
346
+
347
+ nonfinite = tmp_path / "nonfinite.json"
348
+ nonfinite.write_text('{"value": NaN}\n', encoding="utf-8")
349
+ with pytest.raises(contract.JsonContractError, match="non-standard"):
350
+ contract.read_json_strict(nonfinite)
351
+
352
+ overflow = tmp_path / "overflow.json"
353
+ overflow.write_text('{"positive": 1e309, "negative": -1e309}\n', encoding="utf-8")
354
+ with pytest.raises(contract.JsonContractError, match="non-finite"):
355
+ contract.read_json_strict(overflow)
356
+
357
+ surrogate = tmp_path / "surrogate.json"
358
+ surrogate.write_text('{"value": "\\ud800"}\n', encoding="utf-8")
359
+ with pytest.raises(contract.JsonContractError, match="surrogate"):
360
+ contract.read_json_strict(surrogate)
361
+
362
+
363
+ def test_atomic_json_is_stable_utf8_and_uses_unique_same_dir_temps(
364
+ tmp_path: Path,
365
+ monkeypatch: pytest.MonkeyPatch,
366
+ ) -> None:
367
+ destination = tmp_path / "manifest.json"
368
+ destination.write_text("old", encoding="utf-8")
369
+ real_replace = contract.os.replace
370
+ temporary_paths: list[Path] = []
371
+
372
+ def recording_replace(source: str | Path, target: str | Path) -> None:
373
+ temporary_paths.append(Path(source))
374
+ real_replace(source, target)
375
+
376
+ monkeypatch.setattr(contract.os, "replace", recording_replace)
377
+ contract.atomic_write_json(destination, {"z": 1, "a": "中文"})
378
+ first_content = destination.read_text(encoding="utf-8")
379
+ contract.atomic_write_json(destination, {"a": "中文", "z": 2})
380
+
381
+ assert first_content == '{\n "a": "中文",\n "z": 1\n}\n'
382
+ assert contract.read_json_strict(destination) == {"a": "中文", "z": 2}
383
+ assert len(temporary_paths) == 2
384
+ assert temporary_paths[0] != temporary_paths[1]
385
+ assert all(path.parent == destination.parent for path in temporary_paths)
386
+ assert not list(tmp_path.glob(".manifest.json.*.tmp"))
387
+
388
+
389
+ def test_exclusive_lock_blocks_a_second_owner(tmp_path: Path) -> None:
390
+ lock_path = tmp_path / "manifest.lock"
391
+ with contract.exclusive_lock(lock_path, timeout=1.0):
392
+ with pytest.raises(contract.LockTimeoutError):
393
+ with contract.exclusive_lock(
394
+ lock_path,
395
+ timeout=0.05,
396
+ poll_interval=0.01,
397
+ ):
398
+ pass
399
+ with contract.exclusive_lock(lock_path, timeout=0.2):
400
+ pass
401
+
402
+
403
+ def test_exclusive_lock_rejects_symlink_without_modifying_target(
404
+ tmp_path: Path,
405
+ ) -> None:
406
+ target = tmp_path / "target.txt"
407
+ target.write_bytes(b"")
408
+ lock_path = tmp_path / "manifest.lock"
409
+ try:
410
+ lock_path.symlink_to(target)
411
+ except (NotImplementedError, OSError) as exc:
412
+ pytest.skip(f"symlink creation unavailable: {exc}")
413
+
414
+ with pytest.raises(contract.LockError, match="link or reparse point"):
415
+ with contract.exclusive_lock(lock_path, timeout=0.01):
416
+ pass
417
+
418
+ assert target.read_bytes() == b""
419
+
420
+
421
+ def test_exclusive_lock_repairs_uninitialized_existing_empty_file(
422
+ tmp_path: Path,
423
+ ) -> None:
424
+ lock_path = tmp_path / "manifest.lock"
425
+ lock_path.write_bytes(b"")
426
+
427
+ with contract.exclusive_lock(lock_path, timeout=0.1):
428
+ pass
429
+ assert lock_path.read_bytes() == b"\0"
430
+
431
+
432
+ def test_exclusive_lock_recovers_after_initialization_write_failure(
433
+ tmp_path: Path,
434
+ monkeypatch: pytest.MonkeyPatch,
435
+ ) -> None:
436
+ lock_path = tmp_path / "manifest.lock"
437
+ original_write = contract.os.write
438
+
439
+ def fail_write(fd: int, data: bytes) -> int:
440
+ raise OSError("injected initialization failure")
441
+
442
+ monkeypatch.setattr(contract.os, "write", fail_write)
443
+ with pytest.raises(contract.LockError, match="cannot safely open"):
444
+ with contract.exclusive_lock(lock_path, timeout=0.01):
445
+ pass
446
+ assert lock_path.read_bytes() == b""
447
+
448
+ monkeypatch.setattr(contract.os, "write", original_write)
449
+ with contract.exclusive_lock(lock_path, timeout=0.1):
450
+ pass
451
+ assert lock_path.read_bytes() == b"\0"
452
+
453
+
454
+ def test_build_and_write_manifest_locks_build_and_replace(
455
+ tmp_path: Path,
456
+ monkeypatch: pytest.MonkeyPatch,
457
+ ) -> None:
458
+ root = tmp_path / "project_docs"
459
+ root.mkdir()
460
+ destination = root / contract.MANIFEST_FILENAME
461
+ expected_project_root = root.parent.resolve()
462
+ expected_manifest_lock = destination.with_name(destination.name + ".lock")
463
+ events: list[tuple[str, Path]] = []
464
+ expected_manifest = {"schema_version": contract.MANIFEST_SCHEMA_VERSION}
465
+
466
+ @contextmanager
467
+ def recording_project_lock(
468
+ project_root: Path,
469
+ **kwargs: object,
470
+ ) -> object:
471
+ assert kwargs == {"timeout": 2.0}
472
+ events.append(("project-lock-enter", Path(project_root)))
473
+ try:
474
+ yield object()
475
+ finally:
476
+ events.append(("project-lock-exit", Path(project_root)))
477
+
478
+ @contextmanager
479
+ def recording_manifest_lock(
480
+ lock_path: Path,
481
+ **kwargs: object,
482
+ ) -> object:
483
+ assert kwargs == {"timeout": 2.0}
484
+ events.append(("manifest-lock-enter", Path(lock_path)))
485
+ try:
486
+ yield object()
487
+ finally:
488
+ events.append(("manifest-lock-exit", Path(lock_path)))
489
+
490
+ def recording_build(docs_root: Path, **kwargs: object) -> dict[str, int]:
491
+ assert events == [
492
+ ("project-lock-enter", expected_project_root),
493
+ ("manifest-lock-enter", expected_manifest_lock),
494
+ ]
495
+ assert Path(docs_root) == root
496
+ assert kwargs["last_synced"] == SYNCED_1
497
+ events.append(("build", root))
498
+ return expected_manifest
499
+
500
+ def recording_write(path: Path, value: object) -> Path:
501
+ assert events == [
502
+ ("project-lock-enter", expected_project_root),
503
+ ("manifest-lock-enter", expected_manifest_lock),
504
+ ("build", root),
505
+ ]
506
+ assert value is expected_manifest
507
+ events.append(("write", Path(path)))
508
+ return Path(path)
509
+
510
+ monkeypatch.setattr(contract, "project_sync_lock", recording_project_lock)
511
+ monkeypatch.setattr(contract, "exclusive_lock", recording_manifest_lock)
512
+ monkeypatch.setattr(contract, "build_manifest", recording_build)
513
+ monkeypatch.setattr(contract, "atomic_write_json", recording_write)
514
+
515
+ returned = contract.build_and_write_manifest(
516
+ root,
517
+ last_synced=SYNCED_1,
518
+ timeout=2.0,
519
+ )
520
+
521
+ assert returned is expected_manifest
522
+ assert events == [
523
+ ("project-lock-enter", expected_project_root),
524
+ ("manifest-lock-enter", expected_manifest_lock),
525
+ ("build", root),
526
+ ("write", destination),
527
+ ("manifest-lock-exit", expected_manifest_lock),
528
+ ("project-lock-exit", expected_project_root),
529
+ ]
530
+
531
+
532
+ def test_manifest_v2_roundtrip_and_stable_generation(tmp_path: Path) -> None:
533
+ root = _make_docs(tmp_path)
534
+ first = contract.build_manifest(root, last_synced=SYNCED_1)
535
+ second = contract.build_manifest(root, last_synced=SYNCED_2)
536
+
537
+ assert first["schema_version"] == 2
538
+ assert first["producer"] == {"name": "proj-doc-builder", "version": "4.0"}
539
+ assert first["docs_root"] == "project_docs"
540
+ assert first["total"] == 2
541
+ assert first["depth_counts"] == {"0": 1, "1": 1}
542
+ assert [entry["path"] for entry in first["files"]] == [
543
+ "group/child.md",
544
+ "root.md",
545
+ ]
546
+ assert [entry["depth"] for entry in first["files"]] == [1, 0]
547
+ assert first["generation_id"] == second["generation_id"]
548
+ assert (
549
+ contract.compute_generation_id(list(reversed(first["files"])))
550
+ == first["generation_id"]
551
+ )
552
+
553
+ manifest_path = root / contract.MANIFEST_FILENAME
554
+ contract.write_manifest(manifest_path, first, use_lock=False)
555
+ loaded = contract.load_manifest(manifest_path, docs_root=root)
556
+ assert loaded == first
557
+ assert manifest_path.read_bytes().endswith(b"\n")
558
+
559
+
560
+ def test_manifest_v2_detects_document_and_manifest_hash_tampering(
561
+ tmp_path: Path,
562
+ ) -> None:
563
+ root = _make_docs(tmp_path)
564
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
565
+ manifest_path = root / contract.MANIFEST_FILENAME
566
+ contract.atomic_write_json(manifest_path, manifest)
567
+
568
+ (root / "root.md").write_text("# changed\n", encoding="utf-8")
569
+ with pytest.raises(contract.ManifestFileMismatchError):
570
+ contract.load_manifest(manifest_path, docs_root=root)
571
+ assert (
572
+ contract.load_manifest(
573
+ manifest_path,
574
+ docs_root=root,
575
+ verify_files=False,
576
+ )["generation_id"]
577
+ == manifest["generation_id"]
578
+ )
579
+
580
+ tampered = copy.deepcopy(manifest)
581
+ tampered["files"][0]["sha256"] = "0" * 64
582
+ with pytest.raises(
583
+ contract.ManifestValidationError, match="generation_id mismatch"
584
+ ):
585
+ contract.validate_manifest_v2(tampered, root, verify_files=False)
586
+
587
+
588
+ def test_verified_manifest_requires_complete_active_document_set(
589
+ tmp_path: Path,
590
+ ) -> None:
591
+ root = _make_docs(tmp_path)
592
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
593
+ extra = root / "extra.md"
594
+ _write_doc(extra, "Extra", status="✅", synced_at=SYNCED_1)
595
+
596
+ with pytest.raises(
597
+ contract.ManifestFileMismatchError,
598
+ match="unregistered active documents",
599
+ ):
600
+ contract.validate_manifest_v2(manifest, root, verify_files=True)
601
+
602
+ assert (
603
+ contract.validate_manifest_v2(
604
+ manifest,
605
+ root,
606
+ verify_files=True,
607
+ verify_complete_set=False,
608
+ )["total"]
609
+ == 2
610
+ )
611
+ assert (
612
+ contract.validate_manifest_v2(
613
+ manifest,
614
+ root,
615
+ verify_files=False,
616
+ )["total"]
617
+ == 2
618
+ )
619
+
620
+ manifest_path = root / contract.MANIFEST_FILENAME
621
+ contract.write_manifest(manifest_path, manifest, use_lock=False)
622
+ assert (
623
+ contract.load_manifest(
624
+ manifest_path,
625
+ docs_root=root,
626
+ verify_complete_set=False,
627
+ )["total"]
628
+ == 2
629
+ )
630
+
631
+
632
+ def test_manifest_v2_verifies_document_metadata(tmp_path: Path) -> None:
633
+ root = _make_docs(tmp_path)
634
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
635
+
636
+ wrong_synced_at = copy.deepcopy(manifest)
637
+ wrong_synced_at["files"][0]["synced_at"] = SYNCED_2
638
+ with pytest.raises(contract.ManifestFileMismatchError, match="synced_at mismatch"):
639
+ contract.validate_manifest_v2(wrong_synced_at, root, verify_files=True)
640
+ contract.validate_manifest_v2(wrong_synced_at, root, verify_files=False)
641
+
642
+ wrong_title = copy.deepcopy(manifest)
643
+ wrong_title["files"][0]["title"] = "伪造标题"
644
+ wrong_title["generation_id"] = contract.compute_generation_id(wrong_title["files"])
645
+ with pytest.raises(contract.ManifestFileMismatchError, match="title mismatch"):
646
+ contract.validate_manifest_v2(wrong_title, root, verify_files=True)
647
+
648
+ invalid_status = copy.deepcopy(manifest)
649
+ invalid_status["files"][0]["status"] = "complete"
650
+ invalid_status["generation_id"] = contract.compute_generation_id(
651
+ invalid_status["files"]
652
+ )
653
+ with pytest.raises(contract.ManifestValidationError, match="status must be one of"):
654
+ contract.validate_manifest_v2(invalid_status, root, verify_files=False)
655
+
656
+
657
+ def test_manifest_v2_verify_files_false_allows_missing_documents(
658
+ tmp_path: Path,
659
+ ) -> None:
660
+ root = _make_docs(tmp_path)
661
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
662
+ (root / "root.md").unlink()
663
+
664
+ contract.validate_manifest_v2(manifest, root, verify_files=False)
665
+ with pytest.raises(contract.PathValidationError, match="cannot be safely resolved"):
666
+ contract.validate_manifest_v2(manifest, root, verify_files=True)
667
+
668
+
669
+ def test_manifest_v2_rejects_inconsistent_aggregates(tmp_path: Path) -> None:
670
+ root = _make_docs(tmp_path)
671
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
672
+
673
+ wrong_total = copy.deepcopy(manifest)
674
+ wrong_total["total"] += 1
675
+ with pytest.raises(contract.ManifestValidationError, match="total mismatch"):
676
+ contract.validate_manifest_v2(wrong_total, root)
677
+
678
+ wrong_depths = copy.deepcopy(manifest)
679
+ wrong_depths["depth_counts"] = {"0": 2}
680
+ with pytest.raises(contract.ManifestValidationError, match="depth_counts mismatch"):
681
+ contract.validate_manifest_v2(wrong_depths, root)
682
+
683
+
684
+ def test_v1_depth_zero_is_recomputed_in_memory_without_writeback(
685
+ tmp_path: Path,
686
+ ) -> None:
687
+ root = _make_docs(tmp_path)
688
+ manifest_path = root / contract.MANIFEST_FILENAME
689
+ v1 = {
690
+ "files": [
691
+ {"path": "root.md", "depth": 0, "title": "根文档", "status": "✅"},
692
+ {
693
+ "path": "group/child.md",
694
+ "depth": 0,
695
+ "title": "子文档",
696
+ "status": "🔶",
697
+ },
698
+ ],
699
+ "total": 2,
700
+ "last_synced": SYNCED_1,
701
+ }
702
+ contract.atomic_write_json(manifest_path, v1)
703
+
704
+ with pytest.warns(
705
+ contract.LegacyManifestWarning, match="depth values are untrusted"
706
+ ):
707
+ loaded = contract.load_manifest(manifest_path, docs_root=root)
708
+
709
+ by_path = {entry["path"]: entry for entry in loaded["files"]}
710
+ assert loaded["schema_version"] == 1
711
+ assert by_path["root.md"]["depth"] == 0
712
+ assert by_path["group/child.md"]["depth"] == 1
713
+ assert by_path["group/child.md"]["bytes"] > 0
714
+ assert len(by_path["group/child.md"]["sha256"]) == 64
715
+ assert by_path["group/child.md"]["synced_at"] == SYNCED_1
716
+
717
+ on_disk = contract.read_json_strict(manifest_path)
718
+ assert "schema_version" not in on_disk
719
+ assert on_disk["files"][1]["depth"] == 0
720
+
721
+ with pytest.warns(contract.LegacyManifestWarning):
722
+ loaded_again = contract.validate_manifest(loaded, root)
723
+ assert loaded_again["files"] == loaded["files"]
724
+
725
+
726
+ @pytest.mark.parametrize("schema_version", [2.0, True, "2", None])
727
+ def test_manifest_schema_version_requires_an_exact_integer(
728
+ tmp_path: Path,
729
+ schema_version: object,
730
+ ) -> None:
731
+ root = _make_docs(tmp_path)
732
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
733
+ manifest["schema_version"] = schema_version
734
+
735
+ with pytest.raises(contract.ManifestSchemaError):
736
+ contract.validate_manifest(manifest, root)
737
+
738
+
739
+ def test_unknown_manifest_schema_fails(tmp_path: Path) -> None:
740
+ root = _make_docs(tmp_path)
741
+ with pytest.raises(contract.ManifestSchemaError, match="unsupported"):
742
+ contract.validate_manifest({"schema_version": 99}, root)
743
+
744
+
745
+ def test_build_manifest_rejects_non_utf8_document(tmp_path: Path) -> None:
746
+ root = tmp_path / "project_docs"
747
+ root.mkdir()
748
+ (root / "bad.md").write_bytes(b"# title\n\xff")
749
+ with pytest.raises(contract.StrictUtf8Error):
750
+ contract.build_manifest(root, last_synced=SYNCED_1)
751
+
752
+
753
+ def test_build_manifest_excludes_only_root_quarantine_documents(tmp_path: Path) -> None:
754
+ root = _make_docs(tmp_path)
755
+ _write_doc(root / contract.QUARANTINE_DIRNAME / "receipt" / "old.md", "旧文档")
756
+ _write_doc(root / ".lingma" / "notes.md", "隐藏但活动的文档")
757
+ _write_doc(
758
+ root / "section" / contract.QUARANTINE_DIRNAME / "notes.md",
759
+ "嵌套同名目录仍属活动树",
760
+ )
761
+
762
+ manifest = contract.build_manifest(root, last_synced=SYNCED_1)
763
+ paths = {entry["path"] for entry in manifest["files"]}
764
+
765
+ assert manifest["total"] == 4
766
+ assert ".lingma/notes.md" in paths
767
+ assert "section/.quarantine/notes.md" in paths
768
+ assert all(
769
+ not entry["path"].startswith(contract.QUARANTINE_DIRNAME + "/")
770
+ for entry in manifest["files"]
771
+ )
772
+
773
+
774
+ def test_build_manifest_rejects_noncanonical_root_quarantine_name(
775
+ tmp_path: Path,
776
+ ) -> None:
777
+ root = _make_docs(tmp_path)
778
+ (root / ".QUARANTINE").mkdir()
779
+
780
+ with pytest.raises(contract.PathValidationError, match="canonical lowercase"):
781
+ contract.build_manifest(root, last_synced=SYNCED_1)