@walvka-code/proj-doc-builder 4.0.0 → 4.5.2

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 (61) hide show
  1. package/README.md +290 -272
  2. package/README.zh-CN.md +258 -240
  3. package/package.json +6 -2
  4. package/skills/proj-doc-builder/SKILL.md +97 -35
  5. package/skills/proj-doc-builder/references/audit_script.md +103 -96
  6. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  7. package/skills/proj-doc-builder/references/checklist.md +20 -10
  8. package/skills/proj-doc-builder/references/exclusions.md +1 -1
  9. package/skills/proj-doc-builder/references/linking.md +83 -83
  10. package/skills/proj-doc-builder/references/templates.md +57 -17
  11. package/skills/proj-doc-builder/tests/claims.json +76 -0
  12. package/skills/proj-doc-builder/tests/conftest.py +17 -5
  13. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  14. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  15. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -248
  16. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +32 -1
  17. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1 -1
  18. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  19. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -2169
  20. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  21. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  22. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  23. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  24. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  25. package/skills/proj-doc-builder/tests/test_validate_doc.py +172 -15
  26. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  27. package/skills/proj-doc-builder/tools/{claude_doc_index.py → core/claude_doc_index.py} +504 -298
  28. package/skills/proj-doc-builder/tools/{compute_link.py → core/compute_link.py} +239 -233
  29. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  30. package/skills/proj-doc-builder/tools/{project_docs_contract.py → core/project_docs_contract.py} +460 -53
  31. package/skills/proj-doc-builder/tools/phase4/__init__.py +31 -6
  32. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +11 -4
  33. package/skills/proj-doc-builder/tools/phase4/engine.py +17 -2
  34. package/skills/proj-doc-builder/tools/phase4/journal.py +15 -8
  35. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +12 -5
  36. package/skills/proj-doc-builder/tools/phase4_exit.py +153 -47
  37. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  38. package/skills/proj-doc-builder/tools/{sync_project_docs.py → pipeline/sync_project_docs.py} +5531 -3639
  39. package/skills/proj-doc-builder/tools/{load_docs.py → reader/load_docs.py} +654 -380
  40. package/skills/proj-doc-builder/tools/{link_check.py → scan/link_check.py} +203 -152
  41. package/skills/proj-doc-builder/tools/{normalize_markers.py → scan/normalize_markers.py} +211 -205
  42. package/skills/proj-doc-builder/tools/{scan_dirs.py → scan/scan_dirs.py} +2735 -2405
  43. package/skills/proj-doc-builder/tools/{validate_doc.py → validate/validate_doc.py} +1911 -1299
  44. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  45. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  46. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  47. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  48. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  49. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  50. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  51. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  52. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  53. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  54. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  55. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  56. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  57. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  58. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  59. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  60. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  61. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
@@ -0,0 +1,395 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Tests for Stage 1 & Stage 2 upgrades (config, CLAUDE index budget, phase4 package, fast paths)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ import claude_doc_index as indexer
13
+ import link_check
14
+ import phase4
15
+ from phase4 import cas_storage, engine, journal, platform_handles
16
+ import phase4_exit
17
+ import proj_doc_config
18
+ import project_docs_contract as contract
19
+ import scan_dirs
20
+ import sync_project_docs
21
+ import validate_doc
22
+
23
+ SYNCED = "2026-11-27T12:00:00+00:00"
24
+
25
+
26
+ def _write_doc(path: Path, body: str) -> None:
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ path.write_text(body, encoding="utf-8")
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Stage 1.1: proj_doc_config (.projdoc.toml)
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ def test_proj_doc_config_defaults_without_file(tmp_path: Path) -> None:
37
+ cfg = proj_doc_config.load_project_config(tmp_path)
38
+ assert cfg.config_path is None
39
+ assert cfg.scan.max_depth == proj_doc_config.DEFAULT_MAX_DEPTH
40
+ assert ".git" in cfg.scan.exclude_names
41
+ assert cfg.claude_index.max_bytes == proj_doc_config.DEFAULT_CLAUDE_MAX_BYTES
42
+ assert cfg.publish.max_history_entries == proj_doc_config.DEFAULT_PUBLISH_MAX_HISTORY
43
+
44
+
45
+ def test_proj_doc_config_loads_toml_and_matches_exclusions(tmp_path: Path) -> None:
46
+ (tmp_path / ".projdoc.toml").write_text(
47
+ """
48
+ [scan]
49
+ max_depth = 5
50
+ exclude_names = ["generated_vectors", "build_out"]
51
+ exclude_paths = ["vendor/*", "data/raw"]
52
+
53
+ [claude_index]
54
+ max_bytes = 8192
55
+ max_depth = 3
56
+ collapse_threshold = 12
57
+
58
+ [publish]
59
+ max_history_entries = 4
60
+ """.lstrip(),
61
+ encoding="utf-8",
62
+ )
63
+ cfg = proj_doc_config.load_project_config(tmp_path)
64
+ assert cfg.config_path is not None
65
+ assert cfg.scan.max_depth == 5
66
+ assert "generated_vectors" in cfg.scan.exclude_names
67
+ assert ".git" in cfg.scan.exclude_names
68
+ assert cfg.claude_index.max_bytes == 8192
69
+ assert cfg.claude_index.max_depth == 3
70
+ assert cfg.claude_index.collapse_threshold == 12
71
+ assert cfg.publish.max_history_entries == 4
72
+
73
+ assert proj_doc_config.should_exclude_directory("generated_vectors", "a/generated_vectors", config=cfg.scan)
74
+ assert proj_doc_config.should_exclude_directory("sub", "vendor/sub", config=cfg.scan)
75
+ assert proj_doc_config.should_exclude_directory("raw", "data/raw", config=cfg.scan)
76
+ assert not proj_doc_config.should_exclude_directory("src", "src", config=cfg.scan)
77
+
78
+
79
+ def test_proj_doc_config_rejects_invalid_toml(tmp_path: Path) -> None:
80
+ (tmp_path / ".projdoc.toml").write_text("[scan\nbroken", encoding="utf-8")
81
+ with pytest.raises(proj_doc_config.ConfigError):
82
+ proj_doc_config.load_project_config(tmp_path)
83
+
84
+
85
+ def test_scan_dirs_respects_projdoc_toml_exclusions(tmp_path: Path) -> None:
86
+ (tmp_path / ".projdoc.toml").write_text(
87
+ """
88
+ [scan]
89
+ exclude_names = ["skip_me"]
90
+ exclude_paths = ["pkg/ignored_sub"]
91
+ """.lstrip(),
92
+ encoding="utf-8",
93
+ )
94
+ (tmp_path / "pkg").mkdir()
95
+ (tmp_path / "pkg" / "keep.py").write_text("x = 1\n", encoding="utf-8")
96
+ (tmp_path / "pkg" / "ignored_sub").mkdir()
97
+ (tmp_path / "pkg" / "ignored_sub" / "a.py").write_text("y = 2\n", encoding="utf-8")
98
+ (tmp_path / "skip_me").mkdir()
99
+ (tmp_path / "skip_me" / "b.py").write_text("z = 3\n", encoding="utf-8")
100
+
101
+ result = scan_dirs.scan_directories(tmp_path)
102
+ paths = {entry["path"] for entry in result}
103
+ assert "pkg" in paths
104
+ assert "pkg/ignored_sub" not in paths
105
+ assert "skip_me" not in paths
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Stage 1.2: claude_doc_index budget, depth, and folding
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ def test_claude_doc_index_folds_wide_branch_within_budget() -> None:
114
+ files = [{"path": "index.md", "title": "index — Root", "status": "✅"}]
115
+ files.append({"path": "progs.md", "title": "progs — Suite", "status": "✅"})
116
+ for i in range(40):
117
+ files.append(
118
+ {
119
+ "path": f"progs/case_{i:02d}.md",
120
+ "title": f"case_{i:02d} — Long Case Description Number {i:02d}",
121
+ "status": "✅",
122
+ }
123
+ )
124
+ manifest = {
125
+ "schema_version": 2,
126
+ "producer": {"name": "proj-doc-builder", "version": "4.0"},
127
+ "last_synced": SYNCED,
128
+ "files": files,
129
+ }
130
+ full = indexer.render_document_tree(manifest)
131
+ budget = 600
132
+ assert len(full.encode("utf-8")) > budget
133
+
134
+ folded = indexer.render_document_tree(
135
+ manifest,
136
+ max_bytes=budget,
137
+ collapse_threshold=10,
138
+ )
139
+ assert len(folded.encode("utf-8")) <= budget
140
+ assert "已折叠" in folded
141
+ assert indexer.render_document_tree(manifest, max_bytes=budget, collapse_threshold=10) == folded
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Stage 1.3: phase4 subpackage re-exports
146
+ # ---------------------------------------------------------------------------
147
+
148
+
149
+ def test_phase4_subpackage_exports_resolve() -> None:
150
+ assert phase4.analyze_snapshot is phase4_exit.analyze_snapshot
151
+ assert engine.analyze_snapshot is phase4_exit.analyze_snapshot
152
+ assert journal.recover_pending_transaction is phase4_exit._recover_pending_transaction
153
+ assert platform_handles.fsync_directory is phase4_exit._fsync_directory
154
+ assert cas_storage.text_snapshot is phase4_exit._text_snapshot
155
+
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # Stage 2: link_check graph sharing & contract target_paths
159
+ # ---------------------------------------------------------------------------
160
+
161
+
162
+ def test_link_check_with_graph_matches_check_links(tmp_path: Path) -> None:
163
+ docs = tmp_path / "project_docs"
164
+ _write_doc(
165
+ docs / "index.md",
166
+ "# index — Root\n\nSee [alpha](alpha.md), [missing](nope.md), and [escape](../outside.md).\n",
167
+ )
168
+ _write_doc(docs / "alpha.md", "# alpha — Module\n\nBack to [index](index.md).\n")
169
+
170
+ count1, issues1 = link_check.check_links(docs)
171
+ count2, issues2, inbound, invalid = link_check.check_links_with_graph(docs)
172
+
173
+ assert count1 == count2 == 2
174
+ assert issues1 == issues2
175
+ assert "index.md" in inbound.get("alpha.md", set())
176
+ assert "alpha.md" in inbound.get("index.md", set())
177
+ assert len(invalid) == 1
178
+
179
+
180
+ def test_contract_load_manifest_target_paths_verifies_only_target(tmp_path: Path) -> None:
181
+ docs = tmp_path / "project_docs"
182
+ _write_doc(docs / "index.md", "# index — Root\n")
183
+ _write_doc(docs / "alpha.md", "# alpha — Module\n")
184
+ _write_doc(docs / "beta.md", "# beta — Other\n")
185
+
186
+ manifest = contract.build_manifest(docs, last_synced=SYNCED)
187
+ (docs / contract.MANIFEST_FILENAME).write_text(
188
+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
189
+ encoding="utf-8",
190
+ )
191
+
192
+ # Tamper with beta.md only
193
+ _write_doc(docs / "beta.md", "# beta — Tampered\n")
194
+
195
+ # Full load must detect beta.md tampering
196
+ with pytest.raises(contract.ManifestValidationError):
197
+ contract.load_manifest(docs, verify_files=True, verify_complete_set=True)
198
+
199
+ # Targeted load of alpha.md succeeds in O(1) without touching beta.md
200
+ loaded = contract.load_manifest(
201
+ docs,
202
+ verify_files=True,
203
+ verify_complete_set=False,
204
+ target_paths=("alpha.md",),
205
+ )
206
+ assert loaded["schema_version"] == 2
207
+
208
+ # Targeted load of beta.md still fails closed
209
+ with pytest.raises(contract.ManifestValidationError):
210
+ contract.load_manifest(
211
+ docs,
212
+ verify_files=True,
213
+ verify_complete_set=False,
214
+ target_paths=("beta.md",),
215
+ )
216
+
217
+
218
+ # ---------------------------------------------------------------------------
219
+ # Stage 2: validate_doc virtual source inventory & sync history pruning
220
+ # ---------------------------------------------------------------------------
221
+
222
+
223
+ def test_validate_doc_accepts_virtual_source_inventory(tmp_path: Path) -> None:
224
+ docs = tmp_path / "project_docs"
225
+ doc_path = docs / "empty_mod.md"
226
+ _write_doc(
227
+ doc_path,
228
+ "\n".join(
229
+ [
230
+ "<!-- profile: placeholder -->",
231
+ "<!-- status: ⬜ -->",
232
+ "",
233
+ "# empty_mod — Placeholder Module",
234
+ "",
235
+ "[project_docs](index.md) / empty_mod",
236
+ "",
237
+ "## 概述",
238
+ "",
239
+ "该目录当前为空占位目录,等待后续实现。",
240
+ "",
241
+ ]
242
+ ),
243
+ )
244
+ _write_doc(docs / "index.md", "# index — Root\n")
245
+
246
+ # Pass a non-existent source_dir path under project_root with an explicit virtual inventory.
247
+ virtual_source = tmp_path / "empty_mod"
248
+ assert not virtual_source.exists()
249
+ report = validate_doc.validate_doc(
250
+ doc_path,
251
+ virtual_source,
252
+ project_docs_dir=docs,
253
+ project_root=tmp_path,
254
+ source_inventory=((), ()),
255
+ )
256
+ assert report["error_code"] is None
257
+ assert report["profile"] == "placeholder"
258
+
259
+
260
+ def test_extract_virtual_source_inventories_and_collision_detection() -> None:
261
+ good = {
262
+ "snapshot": {
263
+ "directories": [
264
+ {
265
+ "path": "pkg",
266
+ "snapshot": {
267
+ "child_directories": ["sub"],
268
+ "files": [{"name": "a.py"}],
269
+ },
270
+ }
271
+ ]
272
+ }
273
+ }
274
+ inv = sync_project_docs._extract_virtual_source_inventories(good)
275
+ assert inv["pkg"] == (("a.py",), ("sub",))
276
+
277
+ bad = {
278
+ "snapshot": {
279
+ "directories": [
280
+ {
281
+ "path": "pkg",
282
+ "snapshot": {
283
+ "child_directories": ["same"],
284
+ "files": [{"name": "same"}],
285
+ },
286
+ }
287
+ ]
288
+ }
289
+ }
290
+ with pytest.raises(sync_project_docs.SyncInputError, match="collision"):
291
+ sync_project_docs._extract_virtual_source_inventories(bad)
292
+
293
+
294
+ def test_prune_publish_history_respects_config_limit(tmp_path: Path) -> None:
295
+ (tmp_path / ".projdoc.toml").write_text(
296
+ "[publish]\nmax_history_entries = 2\n",
297
+ encoding="utf-8",
298
+ )
299
+ docs = tmp_path / "project_docs"
300
+ docs.mkdir()
301
+ paths = sync_project_docs.ProjectPaths(
302
+ root=tmp_path,
303
+ docs_root=docs,
304
+ claude_path=tmp_path / "CLAUDE.md",
305
+ manifest_path=docs / "_manifest.json",
306
+ scan_state_path=docs / ".scan_state.json",
307
+ root_identity=(0, 0),
308
+ docs_root_identity=(0, 0),
309
+ )
310
+ journal_path = sync_project_docs._publish_journal_path(paths)
311
+ journal_path.parent.mkdir(parents=True, exist_ok=True)
312
+ prefix = f"{journal_path.stem}{sync_project_docs._PUBLISH_HISTORY_MARKER}"
313
+
314
+ created: list[Path] = []
315
+ for i in range(5):
316
+ f = journal_path.parent / f"{prefix}20261127T00000{i}Z-id{i}.json"
317
+ f.write_text("{}", encoding="utf-8")
318
+ os.utime(f, (1_700_000_000 + i * 10, 1_700_000_000 + i * 10))
319
+ created.append(f)
320
+
321
+ sync_project_docs._prune_publish_history(paths, created[-1])
322
+ remaining = sorted(p.name for p in journal_path.parent.glob(f"{prefix}*.json"))
323
+ assert len(remaining) == 2
324
+ assert created[-1].name in remaining
325
+ assert created[-2].name in remaining
326
+
327
+
328
+ def test_scan_dirs_mtime_cache_opt_in(
329
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
330
+ ) -> None:
331
+ (tmp_path / ".projdoc.toml").write_text(
332
+ "[scan]\nuse_mtime_cache = true\n",
333
+ encoding="utf-8",
334
+ )
335
+ pkg = tmp_path / "pkg"
336
+ pkg.mkdir()
337
+ target_file = pkg / "a.py"
338
+ target_file.write_text("x = 1\n", encoding="utf-8")
339
+
340
+ first = scan_dirs.build_candidate_state(tmp_path)
341
+
342
+ real_open = os.open
343
+
344
+ def guarded_open(path: object, *args: object, **kwargs: object) -> int:
345
+ if Path(str(path)).name == "a.py":
346
+ raise AssertionError("mtime cache should avoid reopening unchanged a.py")
347
+ return real_open(path, *args, **kwargs) # type: ignore[arg-type]
348
+
349
+ monkeypatch.setattr(os, "open", guarded_open)
350
+ second = scan_dirs.build_candidate_state(
351
+ tmp_path, previous=first, incremental=True
352
+ )
353
+ assert "pkg" in second["changes"]["unchanged"]
354
+ assert second["changes"]["modified"] == []
355
+
356
+
357
+ def test_validate_doc_audit_inventory_cli(
358
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
359
+ ) -> None:
360
+ import json
361
+
362
+ pkg = tmp_path / "pkg"
363
+ pkg.mkdir()
364
+ (pkg / "a.py").write_text("a = 1\n", encoding="utf-8")
365
+ (pkg / "b.py").write_text("b = 2\n", encoding="utf-8")
366
+
367
+ docs = tmp_path / "project_docs"
368
+ docs.mkdir()
369
+ doc_path = docs / "pkg.md"
370
+ doc_path.write_text(
371
+ "# pkg\n\n## 文件清单\n\n| 文件 | 说明 |\n|---|---|\n"
372
+ "| `a.py` | a |\n| `ghost.py` | g |\n",
373
+ encoding="utf-8",
374
+ )
375
+
376
+ rc = validate_doc.main(["--audit-inventory", str(tmp_path), "--json"])
377
+ assert rc == validate_doc.EXIT_VALIDATION_FAILED
378
+ payload = json.loads(capsys.readouterr().out)
379
+ assert payload["ok"] is False
380
+ assert payload["audited_docs"] == 1
381
+ assert payload["issue_count"] == 1
382
+ assert payload["issues"][0]["missing"] == ["b.py"]
383
+ assert payload["issues"][0]["extra"] == ["ghost.py"]
384
+
385
+ doc_path.write_text(
386
+ "# pkg\n\n## 文件清单\n\n| 文件 | 说明 |\n|---|---|\n"
387
+ "| `a.py` | a |\n| `b.py` | b |\n",
388
+ encoding="utf-8",
389
+ )
390
+ rc_ok = validate_doc.main(["--audit-inventory", str(tmp_path), "--json"])
391
+ assert rc_ok == validate_doc.EXIT_OK
392
+ payload_ok = json.loads(capsys.readouterr().out)
393
+ assert payload_ok["ok"] is True
394
+ assert payload_ok["issue_count"] == 0
395
+