@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,298 +1,504 @@
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())
1
+ # -*- coding: utf-8 -*-
2
+ """从受验证 manifest 确定性生成根 ``CLAUDE.md`` 文档树区块。"""
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 copy
14
+ import re
15
+ import sys
16
+ from pathlib import Path, PurePosixPath
17
+ from typing import Any, Mapping, MutableMapping, Sequence
18
+
19
+ from project_docs_contract import (
20
+ ManifestValidationError,
21
+ ProjectDocsContractError,
22
+ atomic_write_utf8,
23
+ configure_stdio_utf8,
24
+ load_manifest,
25
+ project_sync_lock,
26
+ read_utf8,
27
+ stable_json_dumps,
28
+ )
29
+ from proj_doc_config import (
30
+ DEFAULT_CLAUDE_COLLAPSE_THRESHOLD,
31
+ DEFAULT_CLAUDE_MAX_BYTES,
32
+ DEFAULT_CLAUDE_MAX_DEPTH,
33
+ load_project_config,
34
+ )
35
+
36
+ MARKER_VERSION = "v3.0"
37
+ DOC_TREE_SECTION = "doc-tree-instruction"
38
+ REQUIRED_SECTIONS = (
39
+ DOC_TREE_SECTION,
40
+ "project-overview",
41
+ "common-commands",
42
+ "architecture",
43
+ "test-structure",
44
+ "dependencies",
45
+ )
46
+
47
+
48
+ class ClaudeIndexError(ValueError):
49
+ """CLAUDE 自动生成区块不满足唯一、成对、有序契约。"""
50
+
51
+
52
+ def section_start(section: str) -> str:
53
+ return f"<!-- AUTO-GENERATED {MARKER_VERSION}: {section} START -->"
54
+
55
+
56
+ def section_end(section: str) -> str:
57
+ return f"<!-- AUTO-GENERATED {MARKER_VERSION}: {section} END -->"
58
+
59
+
60
+ def _marker_positions(content: str, section: str) -> tuple[int, int, int, int]:
61
+ start = section_start(section)
62
+ end = section_end(section)
63
+ start_positions = [
64
+ match.start() for match in re.finditer(re.escape(start), content)
65
+ ]
66
+ end_positions = [match.start() for match in re.finditer(re.escape(end), content)]
67
+ if len(start_positions) != 1 or len(end_positions) != 1:
68
+ raise ClaudeIndexError(
69
+ f"CLAUDE section {section!r} markers must each occur once; "
70
+ f"START={len(start_positions)}, END={len(end_positions)}"
71
+ )
72
+ start_pos = start_positions[0]
73
+ end_pos = end_positions[0]
74
+ if start_pos >= end_pos:
75
+ raise ClaudeIndexError(f"CLAUDE section {section!r} END precedes START")
76
+ return start_pos, start_pos + len(start), end_pos, end_pos + len(end)
77
+
78
+
79
+ def validate_required_sections(
80
+ content: str,
81
+ sections: Sequence[str] = REQUIRED_SECTIONS,
82
+ ) -> dict[str, tuple[int, int, int, int]]:
83
+ """校验需要保留的自动区块 marker,并拒绝区块交叠。"""
84
+
85
+ positions = {section: _marker_positions(content, section) for section in sections}
86
+ ordered = sorted(
87
+ (bounds[0], bounds[3], section) for section, bounds in positions.items()
88
+ )
89
+ for (_, previous_end, previous), (next_start, _, following) in zip(
90
+ ordered, ordered[1:]
91
+ ):
92
+ if next_start < previous_end:
93
+ raise ClaudeIndexError(
94
+ f"CLAUDE sections overlap: {previous!r} and {following!r}"
95
+ )
96
+ return positions
97
+
98
+
99
+ def _new_node(name: str) -> dict[str, Any]:
100
+ return {"name": name, "entry": None, "children": {}}
101
+
102
+
103
+ def _manifest_tree(manifest: Mapping[str, Any]) -> dict[str, Any]:
104
+ files = manifest.get("files")
105
+ if not isinstance(files, list):
106
+ raise ManifestValidationError("manifest files must be an array")
107
+ root = _new_node("project_docs")
108
+ for index, raw_entry in enumerate(files):
109
+ if not isinstance(raw_entry, Mapping):
110
+ raise ManifestValidationError(f"files[{index}] must be an object")
111
+ path = raw_entry.get("path")
112
+ if not isinstance(path, str):
113
+ raise ManifestValidationError(f"files[{index}].path must be text")
114
+ pure = PurePosixPath(path)
115
+ parts = list(pure.parts)
116
+ parts[-1] = PurePosixPath(parts[-1]).stem
117
+ node = root
118
+ for part_index, part in enumerate(parts):
119
+ children: MutableMapping[str, dict[str, Any]] = node["children"]
120
+ folded = part.casefold()
121
+ if folded not in children:
122
+ children[folded] = _new_node(part)
123
+ node = children[folded]
124
+ # 历史文档文件名与对应源码目录可能只有大小写差异
125
+ # (如 foo.md / Foo/)。它们是同一树节点,
126
+ # 但完整 manifest path 并不重复;文档节点自身的 spelling 优先。
127
+ if part_index == len(parts) - 1:
128
+ node["name"] = part
129
+ if node["entry"] is not None:
130
+ raise ManifestValidationError(f"duplicate document tree node: {path!r}")
131
+ node["entry"] = copy.deepcopy(dict(raw_entry))
132
+ return root
133
+
134
+
135
+ def _node_label(node: Mapping[str, Any]) -> str:
136
+ name = str(node["name"])
137
+ entry = node.get("entry")
138
+ if not isinstance(entry, Mapping):
139
+ return name
140
+ title = str(entry.get("title", "")).strip()
141
+ status = str(entry.get("status", "❓"))
142
+ title_name, separator, title_description = title.partition(" — ")
143
+ if title_name.casefold() == name.casefold():
144
+ display_name = title_name
145
+ description = title_description.strip() if separator else ""
146
+ else:
147
+ display_name = name
148
+ description = title
149
+ suffix = f" — {description}" if description else ""
150
+ return f"{display_name}{suffix} {status}".rstrip()
151
+
152
+
153
+ def _sorted_children(node: Mapping[str, Any]) -> list[Mapping[str, Any]]:
154
+ children = node.get("children", {})
155
+ return sorted(
156
+ children.values(),
157
+ key=lambda child: (
158
+ 0 if str(child["name"]).casefold() in ("index", "index.md") else 1,
159
+ str(child["name"]).casefold(),
160
+ str(child["name"]),
161
+ ),
162
+ )
163
+
164
+
165
+ def _count_descendant_docs(node: Mapping[str, Any]) -> int:
166
+ total = 0
167
+ for child in node.get("children", {}).values():
168
+ if child.get("entry") is not None:
169
+ total += 1
170
+ total += _count_descendant_docs(child)
171
+ return total
172
+
173
+
174
+ def _tree_max_depth(node: Mapping[str, Any], current: int = 0) -> int:
175
+ children = node.get("children", {})
176
+ if not children:
177
+ return current
178
+ return max(_tree_max_depth(child, current + 1) for child in children.values())
179
+
180
+
181
+ def _collapse_summary(node: Mapping[str, Any], rel_path: str) -> str:
182
+ direct = len(node.get("children", {}))
183
+ total_docs = _count_descendant_docs(node)
184
+ doc_hint = f"project_docs/{rel_path}.md" if rel_path else "project_docs/index.md"
185
+ if total_docs > direct:
186
+ return f"... (已折叠 {direct} 个子目录 / 共 {total_docs} 份文档,详见 {doc_hint})"
187
+ return f"... (已折叠 {direct} 个子目录,详见 {doc_hint})"
188
+
189
+
190
+ def _render_children(
191
+ node: Mapping[str, Any],
192
+ *,
193
+ prefix: str,
194
+ output: list[str],
195
+ depth: int = 1,
196
+ rel_prefix: str = "",
197
+ max_depth: int = 0,
198
+ collapse_nodes: frozenset[str] = frozenset(),
199
+ ) -> None:
200
+ children = _sorted_children(node)
201
+ for index, child in enumerate(children):
202
+ last = index == len(children) - 1
203
+ child_name = str(child["name"])
204
+ child_rel = f"{rel_prefix}/{child_name}" if rel_prefix else child_name
205
+ output.append(prefix + ("└── " if last else "├── ") + _node_label(child))
206
+ grandchildren = child.get("children", {})
207
+ if not grandchildren:
208
+ continue
209
+ child_prefix = prefix + (" " if last else "│ ")
210
+ if (max_depth > 0 and depth >= max_depth) or (
211
+ child_rel.casefold() in collapse_nodes
212
+ ):
213
+ output.append(child_prefix + "└── " + _collapse_summary(child, child_rel))
214
+ continue
215
+ _render_children(
216
+ child,
217
+ prefix=child_prefix,
218
+ output=output,
219
+ depth=depth + 1,
220
+ rel_prefix=child_rel,
221
+ max_depth=max_depth,
222
+ collapse_nodes=collapse_nodes,
223
+ )
224
+
225
+
226
+ def _collect_large_branches(
227
+ node: Mapping[str, Any],
228
+ *,
229
+ threshold: int,
230
+ rel_prefix: str = "",
231
+ result: set[str] | None = None,
232
+ ) -> set[str]:
233
+ if result is None:
234
+ result = set()
235
+ for child in node.get("children", {}).values():
236
+ child_name = str(child["name"])
237
+ child_rel = f"{rel_prefix}/{child_name}" if rel_prefix else child_name
238
+ grandchildren = child.get("children", {})
239
+ if len(grandchildren) >= threshold:
240
+ result.add(child_rel.casefold())
241
+ elif grandchildren:
242
+ _collect_large_branches(
243
+ child, threshold=threshold, rel_prefix=child_rel, result=result
244
+ )
245
+ return result
246
+
247
+
248
+ def _render_tree_lines(
249
+ tree: Mapping[str, Any],
250
+ *,
251
+ max_depth: int = 0,
252
+ collapse_nodes: frozenset[str] = frozenset(),
253
+ ) -> str:
254
+ lines = ["project_docs/"]
255
+ _render_children(
256
+ tree,
257
+ prefix="",
258
+ output=lines,
259
+ depth=1,
260
+ rel_prefix="",
261
+ max_depth=max_depth,
262
+ collapse_nodes=collapse_nodes,
263
+ )
264
+ return "\n".join(lines)
265
+
266
+
267
+ def render_document_tree(
268
+ manifest: Mapping[str, Any],
269
+ *,
270
+ max_bytes: int = 0,
271
+ max_depth: int = 0,
272
+ collapse_threshold: int = DEFAULT_CLAUDE_COLLAPSE_THRESHOLD,
273
+ ) -> str:
274
+ """将 manifest 的文档渲染为确定性树;超过 ``max_bytes`` 预算时自动折叠/裁剪。"""
275
+
276
+ tree = _manifest_tree(manifest)
277
+ rendered = _render_tree_lines(tree, max_depth=max_depth)
278
+ if max_bytes <= 0 or len(rendered.encode("utf-8")) <= max_bytes:
279
+ return rendered
280
+
281
+ # Stage 1: fold wide homogeneous branches first while preserving top-level structure.
282
+ collapse_nodes = frozenset(
283
+ _collect_large_branches(tree, threshold=max(2, collapse_threshold))
284
+ )
285
+ if collapse_nodes:
286
+ rendered = _render_tree_lines(
287
+ tree, max_depth=max_depth, collapse_nodes=collapse_nodes
288
+ )
289
+ if len(rendered.encode("utf-8")) <= max_bytes:
290
+ return rendered
291
+
292
+ # Stage 2: progressively tighten depth until the tree fits within max_bytes.
293
+ deepest = _tree_max_depth(tree)
294
+ upper_depth = min(deepest, max_depth) if max_depth > 0 else deepest
295
+ for depth_cap in range(max(1, upper_depth - 1), 0, -1):
296
+ rendered = _render_tree_lines(
297
+ tree, max_depth=depth_cap, collapse_nodes=collapse_nodes
298
+ )
299
+ if len(rendered.encode("utf-8")) <= max_bytes:
300
+ return rendered
301
+
302
+ # Stage 3: hard cap at top-level lines if even depth=1 exceeds max_bytes.
303
+ lines = rendered.splitlines()
304
+ kept = [lines[0]]
305
+ used = len(lines[0].encode("utf-8"))
306
+ omitted = 0
307
+ footer_reserve = 128
308
+ for line in lines[1:]:
309
+ line_bytes = len(line.encode("utf-8")) + 1
310
+ if used + line_bytes + footer_reserve <= max_bytes:
311
+ kept.append(line)
312
+ used += line_bytes
313
+ else:
314
+ omitted += 1
315
+ if omitted:
316
+ kept.append(
317
+ f"└── ... (其余 {omitted} 项超出 {max_bytes} B 预算已省略,请用 load_docs.py 按需查看)"
318
+ )
319
+ return "\n".join(kept)
320
+
321
+
322
+ def render_doc_tree_section(
323
+ manifest: Mapping[str, Any],
324
+ *,
325
+ max_bytes: int = DEFAULT_CLAUDE_MAX_BYTES,
326
+ max_depth: int = DEFAULT_CLAUDE_MAX_DEPTH,
327
+ collapse_threshold: int = DEFAULT_CLAUDE_COLLAPSE_THRESHOLD,
328
+ ) -> str:
329
+ last_synced = manifest.get("last_synced")
330
+ if not isinstance(last_synced, str) or not last_synced:
331
+ raise ManifestValidationError("manifest last_synced must be non-empty text")
332
+ producer = manifest.get("producer")
333
+ if not isinstance(producer, Mapping):
334
+ raise ManifestValidationError("manifest producer must be an object")
335
+ producer_name = producer.get("name")
336
+ producer_version = producer.get("version")
337
+ if not isinstance(producer_name, str) or not isinstance(producer_version, str):
338
+ raise ManifestValidationError("manifest producer name/version must be text")
339
+
340
+ tree = render_document_tree(
341
+ manifest,
342
+ max_bytes=max_bytes,
343
+ max_depth=max_depth,
344
+ collapse_threshold=collapse_threshold,
345
+ )
346
+ return "\n".join(
347
+ [
348
+ section_start(DOC_TREE_SECTION),
349
+ f"<!-- Last synced: {last_synced} by {producer_name} v{producer_version} -->",
350
+ "",
351
+ "## 项目文档体系 (Documentation Tree)",
352
+ "",
353
+ "自动生成的项目文档集中在 `project_docs/`,目录结构镜像项目源码。",
354
+ "每个 `.md` 文件描述对应目录的内容(文件清单、关键符号、依赖关系、系统角色等)。",
355
+ "",
356
+ "**使用方式**:",
357
+ "- 从下方文档树中定位目标目录",
358
+ "- 读取 `project_docs/` 下对应的 `.md` 文件",
359
+ "- 每个 `.md` 顶部有面包屑导航,`## 依赖关系` 展示上下游模块",
360
+ "- 叶节点 `.md` 包含对应目录的代码级详情",
361
+ "",
362
+ "### 文档树 (project_docs/)",
363
+ "",
364
+ "```",
365
+ tree,
366
+ "```",
367
+ "",
368
+ "状态: ✅ 完整 🔶 开发中 ⬜ 占位 📦 历史存档 ❓ 未知",
369
+ "",
370
+ section_end(DOC_TREE_SECTION),
371
+ ]
372
+ )
373
+
374
+
375
+ def replace_doc_tree_section(
376
+ content: str,
377
+ manifest: Mapping[str, Any],
378
+ *,
379
+ max_bytes: int = DEFAULT_CLAUDE_MAX_BYTES,
380
+ max_depth: int = DEFAULT_CLAUDE_MAX_DEPTH,
381
+ collapse_threshold: int = DEFAULT_CLAUDE_COLLAPSE_THRESHOLD,
382
+ ) -> str:
383
+ """只替换 doc-tree 区块,保留其他 CLAUDE 内容逐字不变。"""
384
+
385
+ positions = validate_required_sections(content)
386
+ start_pos, _, _, end_after = positions[DOC_TREE_SECTION]
387
+ newline = "\r\n" if "\r\n" in content else "\n"
388
+ rendered = render_doc_tree_section(
389
+ manifest,
390
+ max_bytes=max_bytes,
391
+ max_depth=max_depth,
392
+ collapse_threshold=collapse_threshold,
393
+ ).replace("\n", newline)
394
+ return content[:start_pos] + rendered + content[end_after:]
395
+
396
+
397
+ def update_claude_doc_index(
398
+ claude_path: str | Path,
399
+ manifest: Mapping[str, Any],
400
+ *,
401
+ apply: bool = False,
402
+ lock_timeout: float = 10.0,
403
+ max_bytes: int | None = None,
404
+ max_depth: int | None = None,
405
+ collapse_threshold: int | None = None,
406
+ ) -> dict[str, Any]:
407
+ """生成候选 CLAUDE 内容;显式 apply 在根锁内重新读取后发布。"""
408
+
409
+ path = Path(claude_path).resolve(strict=True)
410
+ cfg = load_project_config(path.parent).claude_index
411
+ effective_max_bytes = cfg.max_bytes if max_bytes is None else max_bytes
412
+ effective_max_depth = cfg.max_depth if max_depth is None else max_depth
413
+ effective_collapse = (
414
+ cfg.collapse_threshold if collapse_threshold is None else collapse_threshold
415
+ )
416
+
417
+ def prepare() -> tuple[str, bool]:
418
+ current = read_utf8(path)
419
+ candidate = replace_doc_tree_section(
420
+ current,
421
+ manifest,
422
+ max_bytes=effective_max_bytes,
423
+ max_depth=effective_max_depth,
424
+ collapse_threshold=effective_collapse,
425
+ )
426
+ return candidate, candidate != current
427
+
428
+ if apply:
429
+ with project_sync_lock(path.parent, timeout=lock_timeout):
430
+ candidate, changed = prepare()
431
+ if changed:
432
+ atomic_write_utf8(path, candidate)
433
+ else:
434
+ candidate, changed = prepare()
435
+ return {"path": path.as_posix(), "changed": changed, "content": candidate}
436
+
437
+
438
+ def _parser() -> argparse.ArgumentParser:
439
+ parser = argparse.ArgumentParser(description="生成 CLAUDE.md 文档树区块")
440
+ parser.add_argument("--claude", default="CLAUDE.md", help="根 CLAUDE.md")
441
+ parser.add_argument("--manifest", default="project_docs/_manifest.json")
442
+ parser.add_argument("--project-docs", default="project_docs")
443
+ parser.add_argument(
444
+ "--max-bytes",
445
+ type=int,
446
+ default=None,
447
+ help="文档树最大字节预算(0=不限,默认读 .projdoc.toml 或 24576)",
448
+ )
449
+ parser.add_argument(
450
+ "--max-depth",
451
+ type=int,
452
+ default=None,
453
+ help="文档树最大展开深度(0=仅按预算裁剪)",
454
+ )
455
+ parser.add_argument(
456
+ "--collapse-threshold",
457
+ type=int,
458
+ default=None,
459
+ help="超预算时优先折叠的子目录数阈值(默认 20)",
460
+ )
461
+ parser.add_argument("--apply", action="store_true", help="原子写入 CLAUDE.md")
462
+ parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
463
+ return parser
464
+
465
+
466
+ def main(argv: Sequence[str] | None = None) -> int:
467
+ configure_stdio_utf8()
468
+ args = _parser().parse_args(argv)
469
+ try:
470
+ manifest = load_manifest(args.manifest, docs_root=args.project_docs)
471
+ result = update_claude_doc_index(
472
+ args.claude,
473
+ manifest,
474
+ apply=args.apply,
475
+ max_bytes=args.max_bytes,
476
+ max_depth=args.max_depth,
477
+ collapse_threshold=args.collapse_threshold,
478
+ )
479
+ output = {
480
+ "ok": True,
481
+ "changed": result["changed"],
482
+ "applied": bool(args.apply and result["changed"]),
483
+ "path": result["path"],
484
+ }
485
+ if args.json:
486
+ print(stable_json_dumps(output), end="")
487
+ else:
488
+ action = (
489
+ "已更新"
490
+ if output["applied"]
491
+ else "需要更新" if output["changed"] else "无变化"
492
+ )
493
+ print(f"CLAUDE 文档树: {action}")
494
+ return 0
495
+ except (OSError, ClaudeIndexError, ProjectDocsContractError) as exc:
496
+ if args.json:
497
+ print(stable_json_dumps({"ok": False, "error": str(exc)}), end="")
498
+ else:
499
+ print(f"ERROR: {exc}", file=sys.stderr)
500
+ return 2
501
+
502
+
503
+ if __name__ == "__main__":
504
+ raise SystemExit(main())