@walvka-code/proj-doc-builder 0.0.0-stage → 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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -3
  3. package/README.zh-CN.md +258 -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 +59 -4
  10. package/skills/proj-doc-builder/SKILL.md +412 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +103 -0
  12. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  13. package/skills/proj-doc-builder/references/checklist.md +90 -0
  14. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  15. package/skills/proj-doc-builder/references/linking.md +83 -0
  16. package/skills/proj-doc-builder/references/migration.md +32 -0
  17. package/skills/proj-doc-builder/references/phase4.md +200 -0
  18. package/skills/proj-doc-builder/references/templates.md +212 -0
  19. package/skills/proj-doc-builder/tests/claims.json +76 -0
  20. package/skills/proj-doc-builder/tests/conftest.py +23 -0
  21. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  22. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  23. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  24. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  25. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -0
  26. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  27. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  28. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +812 -0
  29. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  30. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  31. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  32. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  33. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  34. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  35. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  36. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  37. package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
  38. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  39. package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
  40. package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
  41. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  42. package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
  43. package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
  44. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
  45. package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
  46. package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
  47. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
  48. package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
  49. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  50. package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
  51. package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
  52. package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
  53. package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
  54. package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
  55. package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
@@ -0,0 +1,156 @@
1
+ # -*- coding: utf-8 -*-
2
+ """End-to-end happy path: the documented ``init → scaffold-dump → gen → apply``
3
+ chain must bootstrap a non-empty project on a *fresh* tree, and a zero-change
4
+ re-apply must write nothing.
5
+
6
+ This test exists because the six-phase workflow in SKILL.md was the one path
7
+ no unit test exercised end-to-end. The review loop found that ``--init`` once
8
+ shipped without a CLAUDE.md skeleton and that ``--apply`` on an empty tree
9
+ published a ``total: 0`` manifest that then starved the scaffold of facts;
10
+ both defects survived 400+ focused unit tests because no test ran the
11
+ documented happy path from scratch. This test runs it through the real CLI
12
+ subprocesses, exactly as a user would.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ _TOOLS = Path(__file__).resolve().parents[1] / "tools"
24
+ _SYNC = _TOOLS / "pipeline" / "sync_project_docs.py"
25
+ _GEN = _TOOLS / "pipeline" / "gen_docs_from_scaffold.py"
26
+ _LOAD = _TOOLS / "reader" / "load_docs.py"
27
+
28
+
29
+ def _run(script: Path, cwd: Path, *args: str, allow_failure: bool = False) -> dict:
30
+ env = {
31
+ **os.environ,
32
+ "PYTHONDONTWRITEBYTECODE": "1",
33
+ # The tools print Chinese diagnostics. A Windows runner's default
34
+ # locale is cp1252, so the child needs a UTF-8 stdio encoding and this
35
+ # parent must decode with one too — otherwise subprocess capture raises
36
+ # UnicodeDecodeError and `stdout` comes back as None.
37
+ "PYTHONUTF8": "1",
38
+ "PYTHONIOENCODING": "utf-8",
39
+ "PYTHONPATH": str(_TOOLS),
40
+ }
41
+ proc = subprocess.run(
42
+ [sys.executable, "-X", "utf8", str(script), *args],
43
+ cwd=str(cwd),
44
+ env=env,
45
+ capture_output=True,
46
+ text=True,
47
+ encoding="utf-8",
48
+ errors="replace",
49
+ timeout=120,
50
+ )
51
+ assert allow_failure or proc.returncode == 0, (
52
+ f"{script.name} {' '.join(args)} failed (rc={proc.returncode}):\n"
53
+ f"stdout:\n{proc.stdout[-1200:]}\nstderr:\n{proc.stderr[-1200:]}"
54
+ )
55
+ return {"stdout": proc.stdout, "stderr": proc.stderr, "returncode": proc.returncode}
56
+
57
+
58
+ def _fresh_project(tmp_path: Path) -> Path:
59
+ src = tmp_path / "src"
60
+ src.mkdir()
61
+ (src / "alpha.py").write_text("def alpha():\n return 1\n", encoding="utf-8")
62
+ (src / "beta.py").write_text("def beta():\n return 2\n", encoding="utf-8")
63
+ pkg = tmp_path / "pkg"
64
+ pkg.mkdir()
65
+ (pkg / "__init__.py").write_text("", encoding="utf-8")
66
+ (pkg / "core.py").write_text("class Core:\n pass\n", encoding="utf-8")
67
+ return tmp_path
68
+
69
+
70
+ def test_documented_happy_path_bootstraps_a_non_empty_project(tmp_path: Path) -> None:
71
+ root = _fresh_project(tmp_path)
72
+
73
+ _run(_SYNC, root, ".", "--init")
74
+ _run(_SYNC, root, ".", "--scaffold-dump", "scaffold.json", "--paths", ".", "src", "pkg")
75
+ gen = _run(_GEN, root, "--scaffold", "scaffold.json", "--json")
76
+ gen_payload = json.loads(gen["stdout"])
77
+ assert gen_payload["written_count"] >= 2, (
78
+ f"generator wrote {gen_payload['written_count']} docs; expected >=2 "
79
+ f"(src.md + index.md). written={gen_payload['written']}"
80
+ )
81
+
82
+ apply = _run(_SYNC, root, ".", "--apply", "--json")
83
+ apply_payload = json.loads(apply["stdout"])
84
+ assert apply_payload["ok"], f"apply failed: {apply_payload}"
85
+ manifest = json.loads((root / "project_docs" / "_manifest.json").read_text(encoding="utf-8"))
86
+ assert manifest["total"] >= 2, (
87
+ f"manifest total={manifest['total']}; the bootstrap must publish the "
88
+ "generated docs, not an empty manifest"
89
+ )
90
+
91
+ brief = _run(_LOAD, root, ".", "--mode", "brief", "--json")
92
+ brief_payload = json.loads(brief["stdout"])
93
+ assert brief_payload["ok"], f"brief failed: {brief_payload}"
94
+ assert brief_payload["counts"]["documents"] >= 2, (
95
+ f"brief reports {brief_payload['counts']['documents']} documents; "
96
+ "a freshly-bootstrapped project must be loadable with a non-zero tree"
97
+ )
98
+ assert brief_payload["manifest"]["doc_contract_version"], (
99
+ "brief must report a real contract version derived from per-file entries"
100
+ )
101
+
102
+
103
+ def test_zero_change_apply_writes_nothing_after_bootstrap(tmp_path: Path) -> None:
104
+ root = _fresh_project(tmp_path)
105
+ _run(_SYNC, root, ".", "--init")
106
+ _run(_SYNC, root, ".", "--scaffold-dump", "scaffold.json", "--paths", ".", "src", "pkg")
107
+ _run(_GEN, root, "--scaffold", "scaffold.json")
108
+ _run(_SYNC, root, ".", "--apply")
109
+
110
+ manifest_before = (root / "project_docs" / "_manifest.json").read_bytes()
111
+ scan_before = (root / "project_docs" / "_scan_state.json").read_bytes()
112
+ claude_before = (root / "CLAUDE.md").read_bytes()
113
+
114
+ _run(_SYNC, root, ".", "--apply", "--json")
115
+
116
+ assert (root / "project_docs" / "_manifest.json").read_bytes() == manifest_before, (
117
+ "a zero-change apply must not rewrite the manifest"
118
+ )
119
+ assert (root / "project_docs" / "_scan_state.json").read_bytes() == scan_before, (
120
+ "a zero-change apply must not rewrite the scan state"
121
+ )
122
+ assert (root / "CLAUDE.md").read_bytes() == claude_before, (
123
+ "a zero-change apply must not rewrite CLAUDE.md"
124
+ )
125
+
126
+
127
+ def test_full_dry_run_blocks_a_critical_failure_on_an_unchanged_doc(tmp_path: Path) -> None:
128
+ """``--full`` is the documented pre-publish terminal gate; it must block
129
+ when an already-published (unchanged) document has a critical check
130
+ failure, not silently pass it advisory-only."""
131
+ root = _fresh_project(tmp_path)
132
+ _run(_SYNC, root, ".", "--init")
133
+ _run(_SYNC, root, ".", "--scaffold-dump", "scaffold.json", "--paths", ".", "src", "pkg")
134
+ _run(_GEN, root, "--scaffold", "scaffold.json")
135
+ _run(_SYNC, root, ".", "--apply")
136
+
137
+ src_doc = root / "project_docs" / "src.md"
138
+ text = src_doc.read_text(encoding="utf-8")
139
+ src_doc.write_text(
140
+ "\n".join(line for line in text.split("\n") if not line.startswith("**导航**")),
141
+ encoding="utf-8",
142
+ )
143
+
144
+ full = _run(_SYNC, root, ".", "--full", "--dry-run", "--json", allow_failure=True)
145
+ assert full["returncode"] != 0, (
146
+ "--full must exit non-zero when an unchanged doc fails a critical check"
147
+ )
148
+ payload = json.loads(full["stdout"])
149
+ validation = payload.get("validation") or {}
150
+ assert not payload["ok"], (
151
+ "--full must block when an unchanged doc fails a critical check"
152
+ )
153
+ blocking = validation.get("blocking_failure_count", 0)
154
+ assert blocking >= 1, (
155
+ f"--full reported blocking_failure_count={blocking}; expected >=1"
156
+ )
@@ -0,0 +1,279 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Tests for the shared-resolver link CLIs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+
14
+ import compute_link
15
+ import link_check
16
+
17
+
18
+ def _write(path: Path, content: str) -> None:
19
+ path.parent.mkdir(parents=True, exist_ok=True)
20
+ path.write_text(content, encoding="utf-8")
21
+
22
+
23
+ def _docs(tmp_path: Path) -> Path:
24
+ root = tmp_path / "project_docs"
25
+ _write(root / "index.md", "# Index\n\n[child](section/child)\n")
26
+ _write(
27
+ root / "section" / "child.md",
28
+ "# Child\n\n[root](../index.md#top)\n[code](../../src/tool.py)\n",
29
+ )
30
+ return root
31
+
32
+
33
+ def test_compute_relative_link_accepts_legacy_project_docs_prefix(
34
+ tmp_path: Path,
35
+ ) -> None:
36
+ root = _docs(tmp_path)
37
+ assert (
38
+ compute_link.compute_relative_link(
39
+ "project_docs/section/child.md",
40
+ "project_docs/index.md",
41
+ str(root),
42
+ must_exist=True,
43
+ )
44
+ == "../index.md"
45
+ )
46
+
47
+
48
+ def test_batch_compute_validates_shape_and_uses_posix(tmp_path: Path) -> None:
49
+ root = _docs(tmp_path)
50
+ result = compute_link.batch_compute(
51
+ [{"from": "index.md", "to": "section/child.md"}],
52
+ str(root),
53
+ must_exist=True,
54
+ )
55
+ assert result == [
56
+ {
57
+ "from": "index.md",
58
+ "to": "section/child.md",
59
+ "link": "section/child.md",
60
+ }
61
+ ]
62
+ with pytest.raises(compute_link.JsonContractError):
63
+ compute_link.batch_compute([{"from": "index.md"}], str(root))
64
+
65
+
66
+ def test_validate_doc_links_reports_invalid_and_missing(tmp_path: Path) -> None:
67
+ root = _docs(tmp_path)
68
+ _write(
69
+ root / "bad.md",
70
+ "# Bad\n\n[missing](missing)\n[outside](../../outside.md)\n",
71
+ )
72
+ issues = compute_link.validate_doc_links("bad.md", str(root))
73
+ assert [(item["kind"], item["target"]) for item in issues] == [
74
+ ("missing", "missing"),
75
+ ("invalid", "../../outside.md"),
76
+ ]
77
+
78
+
79
+ def test_link_check_is_read_only_and_excludes_quarantine(tmp_path: Path) -> None:
80
+ root = _docs(tmp_path)
81
+ _write(root / ".quarantine" / "r" / "old.md", "# Old\n\n[bad](missing.md)\n")
82
+ before = sorted(path.relative_to(root).as_posix() for path in root.rglob("*"))
83
+
84
+ count, issues = link_check.check_links(root)
85
+
86
+ after = sorted(path.relative_to(root).as_posix() for path in root.rglob("*"))
87
+ assert count == 0
88
+ assert issues == []
89
+ assert before == after
90
+ assert not (root / "_manifest.json").exists()
91
+
92
+
93
+ def test_link_check_excludes_only_root_quarantine(tmp_path: Path) -> None:
94
+ root = _docs(tmp_path)
95
+ _write(root / ".quarantine" / "r" / "old.md", "# Old\n\n[bad](missing.md)\n")
96
+ nested = "section/.quarantine/current.md"
97
+ _write(root / nested, "# Current\n\n[bad](missing.md)\n")
98
+
99
+ count, issues = link_check.check_links(root)
100
+
101
+ assert count == 1
102
+ assert issues[0]["doc"] == nested
103
+
104
+
105
+ def test_link_check_reports_encoded_escape_and_missing(tmp_path: Path) -> None:
106
+ root = _docs(tmp_path)
107
+ _write(
108
+ root / "bad.md",
109
+ "# Bad\n\n[missing](none)\n[escape](%2E%2E/%2E%2E/out.md)\n",
110
+ )
111
+ count, issues = link_check.check_links(root)
112
+ assert count == 2
113
+ assert {(item["kind"], item["target"]) for item in issues} == {
114
+ ("missing", "none"),
115
+ ("invalid", "%2E%2E/%2E%2E/out.md"),
116
+ }
117
+
118
+
119
+ def test_link_check_json_stdout_is_single_document(tmp_path: Path, capsys) -> None:
120
+ root = _docs(tmp_path)
121
+ assert link_check.main(["--project-docs", str(root), "--json"]) == 0
122
+ captured = capsys.readouterr()
123
+ assert captured.err == ""
124
+ payload = json.loads(captured.out)
125
+ assert payload["ok"] is True
126
+ assert payload["manifest_written"] is False
127
+
128
+
129
+ def test_link_check_reports_invalid_utf8_as_json_error(tmp_path: Path, capsys) -> None:
130
+ root = _docs(tmp_path)
131
+ (root / "corrupt.md").write_bytes(b"# valid\n\xff")
132
+ assert link_check.main(["--project-docs", str(root), "--json"]) == 2
133
+ captured = capsys.readouterr()
134
+ assert captured.err == ""
135
+ payload = json.loads(captured.out)
136
+ assert payload["ok"] is False
137
+ assert "UTF-8" in payload["error"]
138
+ assert not (root / "_manifest.json").exists()
139
+
140
+
141
+ def test_manifest_only_is_rejected_without_writing(tmp_path: Path, capsys) -> None:
142
+ root = _docs(tmp_path)
143
+ assert (
144
+ link_check.main(["--project-docs", str(root), "--manifest-only", "--json"]) == 2
145
+ )
146
+ payload = json.loads(capsys.readouterr().out)
147
+ assert payload["ok"] is False
148
+ assert not (root / "_manifest.json").exists()
149
+
150
+
151
+ def test_compute_link_json_mode_reports_mode_errors_cleanly(
152
+ tmp_path: Path, capsys
153
+ ) -> None:
154
+ root = _docs(tmp_path)
155
+ assert compute_link.main(["--project-docs", str(root), "--json"]) == 2
156
+ captured = capsys.readouterr()
157
+ assert captured.err == ""
158
+ payload = json.loads(captured.out)
159
+ assert payload["ok"] is False
160
+
161
+
162
+ def test_batch_output_is_atomic_json(tmp_path: Path) -> None:
163
+ root = _docs(tmp_path)
164
+ batch = tmp_path / "pairs.json"
165
+ output = tmp_path / "result.json"
166
+ batch.write_text(
167
+ json.dumps({"pairs": [{"from": "index.md", "to": "section/child.md"}]}),
168
+ encoding="utf-8",
169
+ )
170
+ assert (
171
+ compute_link.main(
172
+ [
173
+ "--project-docs",
174
+ str(root),
175
+ "--batch",
176
+ str(batch),
177
+ "--output",
178
+ str(output),
179
+ "--must-exist",
180
+ ]
181
+ )
182
+ == 0
183
+ )
184
+ assert (
185
+ json.loads(output.read_text(encoding="utf-8"))[0]["link"] == "section/child.md"
186
+ )
187
+
188
+
189
+ def test_link_check_rejects_symlink_escape(tmp_path: Path) -> None:
190
+ root = _docs(tmp_path)
191
+ outside = tmp_path / "outside.md"
192
+ _write(outside, "# Outside\n")
193
+ link = root / "escape.md"
194
+ try:
195
+ link.symlink_to(outside)
196
+ except (NotImplementedError, OSError) as exc:
197
+ pytest.skip(f"symlink unavailable: {exc}")
198
+
199
+ with pytest.raises(link_check.PathValidationError):
200
+ link_check.check_links(root)
201
+
202
+
203
+ def test_link_tools_reject_symlinked_docs_root(tmp_path: Path) -> None:
204
+ real_root = tmp_path / "real_docs"
205
+ _write(real_root / "index.md", "# Index\n")
206
+ linked_root = tmp_path / "project_docs"
207
+ try:
208
+ linked_root.symlink_to(real_root, target_is_directory=True)
209
+ except (NotImplementedError, OSError) as exc:
210
+ pytest.skip(f"directory symlink unavailable: {exc}")
211
+
212
+ with pytest.raises(link_check.PathValidationError, match="root"):
213
+ link_check.check_links(linked_root)
214
+ with pytest.raises(link_check.PathValidationError, match="root"):
215
+ compute_link.compute_relative_link(
216
+ "index.md",
217
+ "index.md",
218
+ str(linked_root),
219
+ must_exist=True,
220
+ )
221
+
222
+
223
+ def test_link_check_rejects_inventory_to_read_symlink_swap(
224
+ tmp_path: Path,
225
+ monkeypatch: pytest.MonkeyPatch,
226
+ ) -> None:
227
+ root = tmp_path / "project_docs"
228
+ victim = root / "a.md"
229
+ replacement = root / "b.md"
230
+ _write(victim, "# A\n\n[missing](missing.md)\n")
231
+ _write(replacement, "# B\n")
232
+ original_discover = link_check.discover_active_markdown_paths
233
+ swapped = False
234
+
235
+ def swapping_discover(root_value: Path) -> list[str]:
236
+ nonlocal swapped
237
+ paths = original_discover(root_value)
238
+ if not swapped:
239
+ try:
240
+ victim.unlink()
241
+ victim.symlink_to(replacement)
242
+ except (NotImplementedError, OSError) as exc:
243
+ pytest.skip(f"symlink unavailable: {exc}")
244
+ swapped = True
245
+ return paths
246
+
247
+ monkeypatch.setattr(
248
+ link_check,
249
+ "discover_active_markdown_paths",
250
+ swapping_discover,
251
+ )
252
+ with pytest.raises(link_check.ProjectDocsContractError):
253
+ link_check.check_links(root)
254
+
255
+
256
+ def test_link_check_json_forces_utf8_under_ascii_environment(tmp_path: Path) -> None:
257
+ root = tmp_path / "project_docs"
258
+ _write(root / "中文.md", "# 中文\n\n[缺失](不存在.md)\n")
259
+ environment = dict(os.environ)
260
+ environment["PYTHONIOENCODING"] = "ascii"
261
+ environment["PYTHONDONTWRITEBYTECODE"] = "1"
262
+
263
+ completed = subprocess.run(
264
+ [
265
+ sys.executable,
266
+ str(Path(link_check.__file__)),
267
+ "--project-docs",
268
+ str(root),
269
+ "--json",
270
+ ],
271
+ check=False,
272
+ capture_output=True,
273
+ env=environment,
274
+ )
275
+
276
+ payload = json.loads(completed.stdout.decode("utf-8"))
277
+ assert completed.returncode == 1
278
+ assert completed.stderr == b""
279
+ assert payload["broken"][0]["doc"] == "中文.md"