@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,298 @@
1
+ # -*- coding: utf-8 -*-
2
+ """从受验证 manifest 确定性生成根 ``CLAUDE.md`` 文档树区块。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import copy
8
+ import re
9
+ import sys
10
+ from pathlib import Path, PurePosixPath
11
+ from typing import Any, Mapping, MutableMapping, Sequence
12
+
13
+ from project_docs_contract import (
14
+ ManifestValidationError,
15
+ ProjectDocsContractError,
16
+ atomic_write_utf8,
17
+ configure_stdio_utf8,
18
+ load_manifest,
19
+ project_sync_lock,
20
+ read_utf8,
21
+ stable_json_dumps,
22
+ )
23
+
24
+ MARKER_VERSION = "v3.0"
25
+ DOC_TREE_SECTION = "doc-tree-instruction"
26
+ REQUIRED_SECTIONS = (
27
+ DOC_TREE_SECTION,
28
+ "project-overview",
29
+ "common-commands",
30
+ "architecture",
31
+ "test-structure",
32
+ "dependencies",
33
+ )
34
+
35
+
36
+ class ClaudeIndexError(ValueError):
37
+ """CLAUDE 自动生成区块不满足唯一、成对、有序契约。"""
38
+
39
+
40
+ def section_start(section: str) -> str:
41
+ return f"<!-- AUTO-GENERATED {MARKER_VERSION}: {section} START -->"
42
+
43
+
44
+ def section_end(section: str) -> str:
45
+ return f"<!-- AUTO-GENERATED {MARKER_VERSION}: {section} END -->"
46
+
47
+
48
+ def _marker_positions(content: str, section: str) -> tuple[int, int, int, int]:
49
+ start = section_start(section)
50
+ end = section_end(section)
51
+ start_positions = [
52
+ match.start() for match in re.finditer(re.escape(start), content)
53
+ ]
54
+ end_positions = [match.start() for match in re.finditer(re.escape(end), content)]
55
+ if len(start_positions) != 1 or len(end_positions) != 1:
56
+ raise ClaudeIndexError(
57
+ f"CLAUDE section {section!r} markers must each occur once; "
58
+ f"START={len(start_positions)}, END={len(end_positions)}"
59
+ )
60
+ start_pos = start_positions[0]
61
+ end_pos = end_positions[0]
62
+ if start_pos >= end_pos:
63
+ raise ClaudeIndexError(f"CLAUDE section {section!r} END precedes START")
64
+ return start_pos, start_pos + len(start), end_pos, end_pos + len(end)
65
+
66
+
67
+ def validate_required_sections(
68
+ content: str,
69
+ sections: Sequence[str] = REQUIRED_SECTIONS,
70
+ ) -> dict[str, tuple[int, int, int, int]]:
71
+ """校验需要保留的自动区块 marker,并拒绝区块交叠。"""
72
+
73
+ positions = {section: _marker_positions(content, section) for section in sections}
74
+ ordered = sorted(
75
+ (bounds[0], bounds[3], section) for section, bounds in positions.items()
76
+ )
77
+ for (_, previous_end, previous), (next_start, _, following) in zip(
78
+ ordered, ordered[1:]
79
+ ):
80
+ if next_start < previous_end:
81
+ raise ClaudeIndexError(
82
+ f"CLAUDE sections overlap: {previous!r} and {following!r}"
83
+ )
84
+ return positions
85
+
86
+
87
+ def _new_node(name: str) -> dict[str, Any]:
88
+ return {"name": name, "entry": None, "children": {}}
89
+
90
+
91
+ def _manifest_tree(manifest: Mapping[str, Any]) -> dict[str, Any]:
92
+ files = manifest.get("files")
93
+ if not isinstance(files, list):
94
+ raise ManifestValidationError("manifest files must be an array")
95
+ root = _new_node("project_docs")
96
+ for index, raw_entry in enumerate(files):
97
+ if not isinstance(raw_entry, Mapping):
98
+ raise ManifestValidationError(f"files[{index}] must be an object")
99
+ path = raw_entry.get("path")
100
+ if not isinstance(path, str):
101
+ raise ManifestValidationError(f"files[{index}].path must be text")
102
+ pure = PurePosixPath(path)
103
+ parts = list(pure.parts)
104
+ parts[-1] = PurePosixPath(parts[-1]).stem
105
+ node = root
106
+ for part_index, part in enumerate(parts):
107
+ children: MutableMapping[str, dict[str, Any]] = node["children"]
108
+ folded = part.casefold()
109
+ if folded not in children:
110
+ children[folded] = _new_node(part)
111
+ node = children[folded]
112
+ # 历史文档文件名与对应源码目录可能只有大小写差异
113
+ # (如 foo.md / Foo/)。它们是同一树节点,
114
+ # 但完整 manifest path 并不重复;文档节点自身的 spelling 优先。
115
+ if part_index == len(parts) - 1:
116
+ node["name"] = part
117
+ if node["entry"] is not None:
118
+ raise ManifestValidationError(f"duplicate document tree node: {path!r}")
119
+ node["entry"] = copy.deepcopy(dict(raw_entry))
120
+ return root
121
+
122
+
123
+ def _node_label(node: Mapping[str, Any]) -> str:
124
+ name = str(node["name"])
125
+ entry = node.get("entry")
126
+ if not isinstance(entry, Mapping):
127
+ return name
128
+ title = str(entry.get("title", "")).strip()
129
+ status = str(entry.get("status", "❓"))
130
+ title_name, separator, title_description = title.partition(" — ")
131
+ if title_name.casefold() == name.casefold():
132
+ display_name = title_name
133
+ description = title_description.strip() if separator else ""
134
+ else:
135
+ display_name = name
136
+ description = title
137
+ suffix = f" — {description}" if description else ""
138
+ return f"{display_name}{suffix} {status}".rstrip()
139
+
140
+
141
+ def _sorted_children(node: Mapping[str, Any]) -> list[Mapping[str, Any]]:
142
+ children = node.get("children", {})
143
+ return sorted(
144
+ children.values(),
145
+ key=lambda child: (
146
+ 0 if str(child["name"]).casefold() in ("index", "index.md") else 1,
147
+ str(child["name"]).casefold(),
148
+ str(child["name"]),
149
+ ),
150
+ )
151
+
152
+
153
+ def _render_children(
154
+ node: Mapping[str, Any],
155
+ *,
156
+ prefix: str,
157
+ output: list[str],
158
+ ) -> None:
159
+ children = _sorted_children(node)
160
+ for index, child in enumerate(children):
161
+ last = index == len(children) - 1
162
+ output.append(prefix + ("└── " if last else "├── ") + _node_label(child))
163
+ _render_children(
164
+ child,
165
+ prefix=prefix + (" " if last else "│ "),
166
+ output=output,
167
+ )
168
+
169
+
170
+ def render_document_tree(manifest: Mapping[str, Any]) -> str:
171
+ """将 manifest 的每个文档渲染为唯一、完整的树节点。"""
172
+
173
+ tree = _manifest_tree(manifest)
174
+ lines = ["project_docs/"]
175
+ _render_children(tree, prefix="", output=lines)
176
+ return "\n".join(lines)
177
+
178
+
179
+ def render_doc_tree_section(manifest: Mapping[str, Any]) -> str:
180
+ last_synced = manifest.get("last_synced")
181
+ if not isinstance(last_synced, str) or not last_synced:
182
+ raise ManifestValidationError("manifest last_synced must be non-empty text")
183
+ producer = manifest.get("producer")
184
+ if not isinstance(producer, Mapping):
185
+ raise ManifestValidationError("manifest producer must be an object")
186
+ producer_name = producer.get("name")
187
+ producer_version = producer.get("version")
188
+ if not isinstance(producer_name, str) or not isinstance(producer_version, str):
189
+ raise ManifestValidationError("manifest producer name/version must be text")
190
+
191
+ tree = render_document_tree(manifest)
192
+ return "\n".join(
193
+ [
194
+ section_start(DOC_TREE_SECTION),
195
+ f"<!-- Last synced: {last_synced} by {producer_name} v{producer_version} -->",
196
+ "",
197
+ "## 项目文档体系 (Documentation Tree)",
198
+ "",
199
+ "自动生成的项目文档集中在 `project_docs/`,目录结构镜像项目源码。",
200
+ "每个 `.md` 文件描述对应目录的内容(文件清单、关键符号、依赖关系、系统角色等)。",
201
+ "",
202
+ "**使用方式**:",
203
+ "- 从下方文档树中定位目标目录",
204
+ "- 读取 `project_docs/` 下对应的 `.md` 文件",
205
+ "- 每个 `.md` 顶部有面包屑导航,`## 依赖关系` 展示上下游模块",
206
+ "- 叶节点 `.md` 包含对应目录的代码级详情",
207
+ "",
208
+ "### 文档树 (project_docs/)",
209
+ "",
210
+ "```",
211
+ tree,
212
+ "```",
213
+ "",
214
+ "状态: ✅ 完整 🔶 开发中 ⬜ 占位 📦 历史存档 ❓ 未知",
215
+ "",
216
+ section_end(DOC_TREE_SECTION),
217
+ ]
218
+ )
219
+
220
+
221
+ def replace_doc_tree_section(content: str, manifest: Mapping[str, Any]) -> str:
222
+ """只替换 doc-tree 区块,保留其他 CLAUDE 内容逐字不变。"""
223
+
224
+ positions = validate_required_sections(content)
225
+ start_pos, _, _, end_after = positions[DOC_TREE_SECTION]
226
+ newline = "\r\n" if "\r\n" in content else "\n"
227
+ rendered = render_doc_tree_section(manifest).replace("\n", newline)
228
+ return content[:start_pos] + rendered + content[end_after:]
229
+
230
+
231
+ def update_claude_doc_index(
232
+ claude_path: str | Path,
233
+ manifest: Mapping[str, Any],
234
+ *,
235
+ apply: bool = False,
236
+ lock_timeout: float = 10.0,
237
+ ) -> dict[str, Any]:
238
+ """生成候选 CLAUDE 内容;显式 apply 在根锁内重新读取后发布。"""
239
+
240
+ path = Path(claude_path).resolve(strict=True)
241
+
242
+ def prepare() -> tuple[str, bool]:
243
+ current = read_utf8(path)
244
+ candidate = replace_doc_tree_section(current, manifest)
245
+ return candidate, candidate != current
246
+
247
+ if apply:
248
+ with project_sync_lock(path.parent, timeout=lock_timeout):
249
+ candidate, changed = prepare()
250
+ if changed:
251
+ atomic_write_utf8(path, candidate)
252
+ else:
253
+ candidate, changed = prepare()
254
+ return {"path": path.as_posix(), "changed": changed, "content": candidate}
255
+
256
+
257
+ def _parser() -> argparse.ArgumentParser:
258
+ parser = argparse.ArgumentParser(description="生成 CLAUDE.md 文档树区块")
259
+ parser.add_argument("--claude", default="CLAUDE.md", help="根 CLAUDE.md")
260
+ parser.add_argument("--manifest", default="project_docs/_manifest.json")
261
+ parser.add_argument("--project-docs", default="project_docs")
262
+ parser.add_argument("--apply", action="store_true", help="原子写入 CLAUDE.md")
263
+ parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
264
+ return parser
265
+
266
+
267
+ def main(argv: Sequence[str] | None = None) -> int:
268
+ configure_stdio_utf8()
269
+ args = _parser().parse_args(argv)
270
+ try:
271
+ manifest = load_manifest(args.manifest, docs_root=args.project_docs)
272
+ result = update_claude_doc_index(args.claude, manifest, apply=args.apply)
273
+ output = {
274
+ "ok": True,
275
+ "changed": result["changed"],
276
+ "applied": bool(args.apply and result["changed"]),
277
+ "path": result["path"],
278
+ }
279
+ if args.json:
280
+ print(stable_json_dumps(output), end="")
281
+ else:
282
+ action = (
283
+ "已更新"
284
+ if output["applied"]
285
+ else "需要更新" if output["changed"] else "无变化"
286
+ )
287
+ print(f"CLAUDE 文档树: {action}")
288
+ return 0
289
+ except (OSError, ClaudeIndexError, ProjectDocsContractError) as exc:
290
+ if args.json:
291
+ print(stable_json_dumps({"ok": False, "error": str(exc)}), end="")
292
+ else:
293
+ print(f"ERROR: {exc}", file=sys.stderr)
294
+ return 2
295
+
296
+
297
+ if __name__ == "__main__":
298
+ raise SystemExit(main())
@@ -0,0 +1,233 @@
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())
@@ -0,0 +1,152 @@
1
+ # -*- coding: utf-8 -*-
2
+ """严格校验 ``project_docs`` 内的 Markdown 文档链接。
3
+
4
+ 本工具只校验和报告,不生成或写入 manifest。manifest 发布由
5
+ ``sync_project_docs.py`` 的最终协调阶段负责。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import concurrent.futures
12
+ import os
13
+ import sys
14
+ from pathlib import Path, PurePosixPath
15
+ from typing import Any, Sequence
16
+
17
+ from project_docs_contract import (
18
+ LinkDisposition,
19
+ PathConflictError,
20
+ PathValidationError,
21
+ ProjectDocsContractError,
22
+ configure_stdio_utf8,
23
+ discover_active_markdown_paths,
24
+ read_markdown_links,
25
+ resolve_docs_root,
26
+ stable_json_dumps,
27
+ )
28
+
29
+
30
+ def discover_documents(project_docs: str | os.PathLike[str]) -> list[tuple[str, Path]]:
31
+ """使用共享契约确定性枚举完整活动 Markdown 集合。"""
32
+
33
+ root = resolve_docs_root(project_docs)
34
+ return [
35
+ (relative, root.joinpath(*PurePosixPath(relative).parts))
36
+ for relative in discover_active_markdown_paths(root)
37
+ ]
38
+
39
+
40
+ def check_links(
41
+ project_docs: str | os.PathLike[str],
42
+ ) -> tuple[int, list[dict[str, Any]]]:
43
+ """检查全部本地文档链接,返回 ``(问题数, 详情)``。"""
44
+
45
+ root = resolve_docs_root(project_docs)
46
+ docs = discover_documents(root)
47
+ issues: list[dict[str, Any]] = []
48
+
49
+ def _check_doc(doc_rel: str) -> list[dict[str, Any]]:
50
+ doc_issues: list[dict[str, Any]] = []
51
+ for link in read_markdown_links(doc_rel, root):
52
+ if link.disposition is LinkDisposition.SKIPPED:
53
+ continue
54
+ if link.disposition is LinkDisposition.INVALID:
55
+ doc_issues.append(
56
+ {
57
+ "doc": doc_rel,
58
+ "text": link.text,
59
+ "target": link.raw_target,
60
+ "resolved": link.normalized_target,
61
+ "kind": "invalid",
62
+ "reason": link.reason,
63
+ }
64
+ )
65
+ elif link.exists is False:
66
+ doc_issues.append(
67
+ {
68
+ "doc": doc_rel,
69
+ "text": link.text,
70
+ "target": link.raw_target,
71
+ "resolved": link.project_relative_path,
72
+ "kind": "missing",
73
+ "reason": link.reason,
74
+ }
75
+ )
76
+ return doc_issues
77
+
78
+ if len(docs) > 1:
79
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
80
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
81
+ doc_rels = [doc_rel for doc_rel, _ in docs]
82
+ for doc_issues in executor.map(_check_doc, doc_rels):
83
+ issues.extend(doc_issues)
84
+ else:
85
+ for doc_rel, _ in docs:
86
+ issues.extend(_check_doc(doc_rel))
87
+
88
+ return len(issues), issues
89
+
90
+
91
+ def _parser() -> argparse.ArgumentParser:
92
+ parser = argparse.ArgumentParser(description="校验 project_docs Markdown 链接")
93
+ parser.add_argument(
94
+ "--project-docs",
95
+ default="project_docs",
96
+ help="project_docs 目录(默认: project_docs)",
97
+ )
98
+ parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
99
+ parser.add_argument(
100
+ "--check-only",
101
+ action="store_true",
102
+ help="兼容旧参数;当前工具始终只执行链接检查",
103
+ )
104
+ parser.add_argument(
105
+ "--manifest-only",
106
+ action="store_true",
107
+ help="已废弃;manifest 只能由同步协调器发布",
108
+ )
109
+ return parser
110
+
111
+
112
+ def main(argv: Sequence[str] | None = None) -> int:
113
+ configure_stdio_utf8()
114
+ args = _parser().parse_args(argv)
115
+ if args.manifest_only:
116
+ message = "--manifest-only 已废弃;请使用 sync_project_docs.py 构建 manifest"
117
+ if args.json:
118
+ print(stable_json_dumps({"error": message, "ok": False}), end="")
119
+ else:
120
+ print(f"ERROR: {message}", file=sys.stderr)
121
+ return 2
122
+
123
+ try:
124
+ issue_count, issues = check_links(args.project_docs)
125
+ result = {
126
+ "ok": issue_count == 0,
127
+ "broken_count": issue_count,
128
+ "broken": issues,
129
+ "manifest_written": False,
130
+ }
131
+ if args.json:
132
+ print(stable_json_dumps(result), end="")
133
+ elif issue_count:
134
+ print(f"发现 {issue_count} 条无效或断开的文档链接:")
135
+ for issue in issues:
136
+ print(
137
+ f" {issue['doc']} -> {issue['target']} "
138
+ f"({issue['kind']}: {issue['reason']})"
139
+ )
140
+ else:
141
+ print("文档链接校验通过:0 条断链。")
142
+ return 1 if issue_count else 0
143
+ except (OSError, ProjectDocsContractError, PathConflictError) as exc:
144
+ if args.json:
145
+ print(stable_json_dumps({"error": str(exc), "ok": False}), end="")
146
+ else:
147
+ print(f"ERROR: {exc}", file=sys.stderr)
148
+ return 2
149
+
150
+
151
+ if __name__ == "__main__":
152
+ raise SystemExit(main())