@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
@@ -1,233 +1,239 @@
1
- # -*- coding: utf-8 -*-
2
- """安全、确定地计算和校验 ``project_docs`` 文档链接。"""
3
-
4
- from __future__ import annotations
5
-
6
- import argparse
7
- import json
8
- import os
9
- import sys
10
- from pathlib import Path, PurePosixPath
11
- from typing import Any, Mapping, Sequence
12
-
13
- from project_docs_contract import (
14
- JsonContractError,
15
- LinkDisposition,
16
- ProjectDocsContractError,
17
- atomic_write_json,
18
- compute_relative_doc_link,
19
- configure_stdio_utf8,
20
- read_json_strict,
21
- read_markdown_links,
22
- resolve_docs_root,
23
- stable_json_dumps,
24
- )
25
-
26
-
27
- def _docs_root(project_docs_dir: str | os.PathLike[str]) -> Path:
28
- return resolve_docs_root(project_docs_dir)
29
-
30
-
31
- def _contract_doc_path(value: str | os.PathLike[str], root: Path) -> str | Path:
32
- """把旧 CLI 的 ``project_docs/...`` 写法转换为契约路径。"""
33
-
34
- raw = os.fspath(value)
35
- candidate = Path(raw)
36
- if candidate.is_absolute():
37
- return candidate
38
- if "\\" in raw:
39
- raise ValueError(f"文档路径必须使用正斜杠: {raw!r}")
40
- pure = PurePosixPath(raw)
41
- if pure.parts and pure.parts[0] == root.name:
42
- pure = PurePosixPath(*pure.parts[1:])
43
- return pure.as_posix()
44
-
45
-
46
- def compute_relative_link(
47
- from_doc: str,
48
- to_doc: str,
49
- project_docs_dir: str = "project_docs",
50
- *,
51
- must_exist: bool = False,
52
- ) -> str:
53
- """计算两个受信文档之间的 POSIX 相对链接。"""
54
-
55
- root = _docs_root(project_docs_dir)
56
- return compute_relative_doc_link(
57
- _contract_doc_path(from_doc, root),
58
- _contract_doc_path(to_doc, root),
59
- root,
60
- must_exist=must_exist,
61
- )
62
-
63
-
64
- def validate_doc_links(doc_path: str, project_docs_dir: str) -> list[dict[str, Any]]:
65
- """返回文档中的无效或不存在本地文档链接。"""
66
-
67
- root = _docs_root(project_docs_dir)
68
- source = _contract_doc_path(doc_path, root)
69
- broken: list[dict[str, Any]] = []
70
- for link in read_markdown_links(source, root):
71
- if link.disposition is LinkDisposition.SKIPPED:
72
- continue
73
- if link.disposition is LinkDisposition.INVALID or link.exists is False:
74
- broken.append(
75
- {
76
- "text": link.text,
77
- "target": link.raw_target,
78
- "resolved": link.project_relative_path
79
- or link.normalized_target
80
- or "",
81
- "kind": (
82
- "invalid"
83
- if link.disposition is LinkDisposition.INVALID
84
- else "missing"
85
- ),
86
- "reason": link.reason,
87
- }
88
- )
89
- return broken
90
-
91
-
92
- def batch_compute(
93
- pairs: Sequence[Mapping[str, Any]],
94
- project_docs_dir: str = "project_docs",
95
- *,
96
- must_exist: bool = False,
97
- ) -> list[dict[str, str]]:
98
- """批量计算 ``from``/``to`` 文档对。"""
99
-
100
- if isinstance(pairs, (str, bytes)):
101
- raise JsonContractError("批量输入必须是对象数组")
102
- results: list[dict[str, str]] = []
103
- for index, pair in enumerate(pairs):
104
- if not isinstance(pair, Mapping):
105
- raise JsonContractError(f"pairs[{index}] 必须是对象")
106
- from_doc = pair.get("from")
107
- to_doc = pair.get("to")
108
- if not isinstance(from_doc, str) or not isinstance(to_doc, str):
109
- raise JsonContractError(f"pairs[{index}] 必须包含字符串 from/to")
110
- results.append(
111
- {
112
- "from": from_doc,
113
- "to": to_doc,
114
- "link": compute_relative_link(
115
- from_doc,
116
- to_doc,
117
- project_docs_dir,
118
- must_exist=must_exist,
119
- ),
120
- }
121
- )
122
- return results
123
-
124
-
125
- def _load_pairs(path: str | os.PathLike[str]) -> Sequence[Mapping[str, Any]]:
126
- value = read_json_strict(path)
127
- pairs = value.get("pairs") if isinstance(value, Mapping) else value
128
- if not isinstance(pairs, list):
129
- raise JsonContractError("批量 JSON 必须是数组或包含 pairs 数组的对象")
130
- return pairs
131
-
132
-
133
- def _parser() -> argparse.ArgumentParser:
134
- parser = argparse.ArgumentParser(description="计算并校验 project_docs 文档链接")
135
- parser.add_argument("--from", dest="from_doc", help="源文档路径")
136
- parser.add_argument("--to", dest="to_doc", help="目标文档路径")
137
- parser.add_argument("--validate", help="校验单个文档中的全部链接")
138
- parser.add_argument(
139
- "--project-docs",
140
- default="project_docs",
141
- help="project_docs 目录(默认: project_docs)",
142
- )
143
- parser.add_argument("--batch", help="批量输入 JSON")
144
- parser.add_argument("--output", "-o", help="批量结果输出文件")
145
- parser.add_argument(
146
- "--must-exist", action="store_true", help="计算时要求两端文档存在"
147
- )
148
- parser.add_argument("--json", action="store_true", help="仅向 stdout 输出 JSON")
149
- return parser
150
-
151
-
152
- def main(argv: Sequence[str] | None = None) -> int:
153
- configure_stdio_utf8()
154
- parser = _parser()
155
- args = parser.parse_args(argv)
156
- try:
157
- modes = (
158
- int(bool(args.from_doc or args.to_doc))
159
- + int(bool(args.validate))
160
- + int(bool(args.batch))
161
- )
162
- if modes != 1:
163
- raise ValueError("必须且只能选择 from/to、validate 或 batch 一种模式")
164
- if bool(args.from_doc) != bool(args.to_doc):
165
- raise ValueError("--from 与 --to 必须同时提供")
166
-
167
- if args.from_doc:
168
- link = compute_relative_link(
169
- args.from_doc,
170
- args.to_doc,
171
- args.project_docs,
172
- must_exist=args.must_exist,
173
- )
174
- if args.json:
175
- print(stable_json_dumps({"link": link}), end="")
176
- else:
177
- print(link)
178
- return 0
179
-
180
- if args.validate:
181
- broken = validate_doc_links(args.validate, args.project_docs)
182
- result = {
183
- "document": args.validate,
184
- "broken_count": len(broken),
185
- "broken": broken,
186
- "valid": not broken,
187
- }
188
- if args.json:
189
- print(stable_json_dumps(result), end="")
190
- elif broken:
191
- print(f"发现 {len(broken)} 条无效链接: {args.validate}")
192
- for item in broken:
193
- print(
194
- f" [{item['text']}]({item['target']}) -> "
195
- f"{item['resolved']} ({item['reason']})"
196
- )
197
- else:
198
- print(f"链接有效: {args.validate}")
199
- return 1 if broken else 0
200
-
201
- results = batch_compute(
202
- _load_pairs(args.batch),
203
- args.project_docs,
204
- must_exist=args.must_exist,
205
- )
206
- if args.output:
207
- written = atomic_write_json(args.output, results)
208
- if args.json:
209
- print(
210
- stable_json_dumps(
211
- {
212
- "ok": True,
213
- "count": len(results),
214
- "written": written.as_posix(),
215
- }
216
- ),
217
- end="",
218
- )
219
- elif args.json:
220
- print(stable_json_dumps({"results": results}), end="")
221
- else:
222
- print(json.dumps(results, ensure_ascii=False, indent=2))
223
- return 0
224
- except (OSError, ValueError, ProjectDocsContractError) as exc:
225
- if args.json:
226
- print(stable_json_dumps({"error": str(exc), "ok": False}), end="")
227
- else:
228
- print(f"ERROR: {exc}", file=sys.stderr)
229
- return 2
230
-
231
-
232
- if __name__ == "__main__":
233
- raise SystemExit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """安全、确定地计算和校验 ``project_docs`` 文档链接。"""
3
+
4
+ from __future__ import annotations
5
+ import sys as _bootstrap_sys
6
+ from pathlib import Path as _bootstrap_path
7
+ _bootstrap_sys.dont_write_bytecode = True
8
+ _bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
9
+ import _paths # noqa: E402
10
+ _paths.install()
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+ from pathlib import Path, PurePosixPath
17
+ from typing import Any, Mapping, Sequence
18
+
19
+ from project_docs_contract import (
20
+ JsonContractError,
21
+ LinkDisposition,
22
+ ProjectDocsContractError,
23
+ atomic_write_json,
24
+ compute_relative_doc_link,
25
+ configure_stdio_utf8,
26
+ read_json_strict,
27
+ read_markdown_links,
28
+ resolve_docs_root,
29
+ stable_json_dumps,
30
+ )
31
+
32
+
33
+ def _docs_root(project_docs_dir: str | os.PathLike[str]) -> Path:
34
+ return resolve_docs_root(project_docs_dir)
35
+
36
+
37
+ def _contract_doc_path(value: str | os.PathLike[str], root: Path) -> str | Path:
38
+ """把旧 CLI 的 ``project_docs/...`` 写法转换为契约路径。"""
39
+
40
+ raw = os.fspath(value)
41
+ candidate = Path(raw)
42
+ if candidate.is_absolute():
43
+ return candidate
44
+ if "\\" in raw:
45
+ raise ValueError(f"文档路径必须使用正斜杠: {raw!r}")
46
+ pure = PurePosixPath(raw)
47
+ if pure.parts and pure.parts[0] == root.name:
48
+ pure = PurePosixPath(*pure.parts[1:])
49
+ return pure.as_posix()
50
+
51
+
52
+ def compute_relative_link(
53
+ from_doc: str,
54
+ to_doc: str,
55
+ project_docs_dir: str = "project_docs",
56
+ *,
57
+ must_exist: bool = False,
58
+ ) -> str:
59
+ """计算两个受信文档之间的 POSIX 相对链接。"""
60
+
61
+ root = _docs_root(project_docs_dir)
62
+ return compute_relative_doc_link(
63
+ _contract_doc_path(from_doc, root),
64
+ _contract_doc_path(to_doc, root),
65
+ root,
66
+ must_exist=must_exist,
67
+ )
68
+
69
+
70
+ def validate_doc_links(doc_path: str, project_docs_dir: str) -> list[dict[str, Any]]:
71
+ """返回文档中的无效或不存在本地文档链接。"""
72
+
73
+ root = _docs_root(project_docs_dir)
74
+ source = _contract_doc_path(doc_path, root)
75
+ broken: list[dict[str, Any]] = []
76
+ for link in read_markdown_links(source, root):
77
+ if link.disposition is LinkDisposition.SKIPPED:
78
+ continue
79
+ if link.disposition is LinkDisposition.INVALID or link.exists is False:
80
+ broken.append(
81
+ {
82
+ "text": link.text,
83
+ "target": link.raw_target,
84
+ "resolved": link.project_relative_path
85
+ or link.normalized_target
86
+ or "",
87
+ "kind": (
88
+ "invalid"
89
+ if link.disposition is LinkDisposition.INVALID
90
+ else "missing"
91
+ ),
92
+ "reason": link.reason,
93
+ }
94
+ )
95
+ return broken
96
+
97
+
98
+ def batch_compute(
99
+ pairs: Sequence[Mapping[str, Any]],
100
+ project_docs_dir: str = "project_docs",
101
+ *,
102
+ must_exist: bool = False,
103
+ ) -> list[dict[str, str]]:
104
+ """批量计算 ``from``/``to`` 文档对。"""
105
+
106
+ if isinstance(pairs, (str, bytes)):
107
+ raise JsonContractError("批量输入必须是对象数组")
108
+ results: list[dict[str, str]] = []
109
+ for index, pair in enumerate(pairs):
110
+ if not isinstance(pair, Mapping):
111
+ raise JsonContractError(f"pairs[{index}] 必须是对象")
112
+ from_doc = pair.get("from")
113
+ to_doc = pair.get("to")
114
+ if not isinstance(from_doc, str) or not isinstance(to_doc, str):
115
+ raise JsonContractError(f"pairs[{index}] 必须包含字符串 from/to")
116
+ results.append(
117
+ {
118
+ "from": from_doc,
119
+ "to": to_doc,
120
+ "link": compute_relative_link(
121
+ from_doc,
122
+ to_doc,
123
+ project_docs_dir,
124
+ must_exist=must_exist,
125
+ ),
126
+ }
127
+ )
128
+ return results
129
+
130
+
131
+ def _load_pairs(path: str | os.PathLike[str]) -> Sequence[Mapping[str, Any]]:
132
+ value = read_json_strict(path)
133
+ pairs = value.get("pairs") if isinstance(value, Mapping) else value
134
+ if not isinstance(pairs, list):
135
+ raise JsonContractError("批量 JSON 必须是数组或包含 pairs 数组的对象")
136
+ return pairs
137
+
138
+
139
+ def _parser() -> argparse.ArgumentParser:
140
+ parser = argparse.ArgumentParser(description="计算并校验 project_docs 文档链接")
141
+ parser.add_argument("--from", dest="from_doc", help="源文档路径")
142
+ parser.add_argument("--to", dest="to_doc", help="目标文档路径")
143
+ parser.add_argument("--validate", help="校验单个文档中的全部链接")
144
+ parser.add_argument(
145
+ "--project-docs",
146
+ default="project_docs",
147
+ help="project_docs 目录(默认: project_docs)",
148
+ )
149
+ parser.add_argument("--batch", help="批量输入 JSON")
150
+ parser.add_argument("--output", "-o", help="批量结果输出文件")
151
+ parser.add_argument(
152
+ "--must-exist", action="store_true", help="计算时要求两端文档存在"
153
+ )
154
+ parser.add_argument("--json", action="store_true", help="仅向 stdout 输出 JSON")
155
+ return parser
156
+
157
+
158
+ def main(argv: Sequence[str] | None = None) -> int:
159
+ configure_stdio_utf8()
160
+ parser = _parser()
161
+ args = parser.parse_args(argv)
162
+ try:
163
+ modes = (
164
+ int(bool(args.from_doc or args.to_doc))
165
+ + int(bool(args.validate))
166
+ + int(bool(args.batch))
167
+ )
168
+ if modes != 1:
169
+ raise ValueError("必须且只能选择 from/to、validate 或 batch 一种模式")
170
+ if bool(args.from_doc) != bool(args.to_doc):
171
+ raise ValueError("--from 与 --to 必须同时提供")
172
+
173
+ if args.from_doc:
174
+ link = compute_relative_link(
175
+ args.from_doc,
176
+ args.to_doc,
177
+ args.project_docs,
178
+ must_exist=args.must_exist,
179
+ )
180
+ if args.json:
181
+ print(stable_json_dumps({"link": link}), end="")
182
+ else:
183
+ print(link)
184
+ return 0
185
+
186
+ if args.validate:
187
+ broken = validate_doc_links(args.validate, args.project_docs)
188
+ result = {
189
+ "document": args.validate,
190
+ "broken_count": len(broken),
191
+ "broken": broken,
192
+ "valid": not broken,
193
+ }
194
+ if args.json:
195
+ print(stable_json_dumps(result), end="")
196
+ elif broken:
197
+ print(f"发现 {len(broken)} 条无效链接: {args.validate}")
198
+ for item in broken:
199
+ print(
200
+ f" [{item['text']}]({item['target']}) -> "
201
+ f"{item['resolved']} ({item['reason']})"
202
+ )
203
+ else:
204
+ print(f"链接有效: {args.validate}")
205
+ return 1 if broken else 0
206
+
207
+ results = batch_compute(
208
+ _load_pairs(args.batch),
209
+ args.project_docs,
210
+ must_exist=args.must_exist,
211
+ )
212
+ if args.output:
213
+ written = atomic_write_json(args.output, results)
214
+ if args.json:
215
+ print(
216
+ stable_json_dumps(
217
+ {
218
+ "ok": True,
219
+ "count": len(results),
220
+ "written": written.as_posix(),
221
+ }
222
+ ),
223
+ end="",
224
+ )
225
+ elif args.json:
226
+ print(stable_json_dumps({"results": results}), end="")
227
+ else:
228
+ print(json.dumps(results, ensure_ascii=False, indent=2))
229
+ return 0
230
+ except (OSError, ValueError, ProjectDocsContractError) as exc:
231
+ if args.json:
232
+ print(stable_json_dumps({"error": str(exc), "ok": False}), end="")
233
+ else:
234
+ print(f"ERROR: {exc}", file=sys.stderr)
235
+ return 2
236
+
237
+
238
+ if __name__ == "__main__":
239
+ raise SystemExit(main())