@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.
- package/LICENSE +21 -0
- package/README.md +290 -3
- package/README.zh-CN.md +258 -0
- package/cordis.patch.yml +8 -0
- package/icon.svg +11 -0
- package/index.js +164 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +59 -4
- package/skills/proj-doc-builder/SKILL.md +412 -0
- package/skills/proj-doc-builder/references/audit_script.md +103 -0
- package/skills/proj-doc-builder/references/batch-generation.md +55 -0
- package/skills/proj-doc-builder/references/checklist.md +90 -0
- package/skills/proj-doc-builder/references/exclusions.md +79 -0
- package/skills/proj-doc-builder/references/linking.md +83 -0
- package/skills/proj-doc-builder/references/migration.md +32 -0
- package/skills/proj-doc-builder/references/phase4.md +200 -0
- package/skills/proj-doc-builder/references/templates.md +212 -0
- package/skills/proj-doc-builder/tests/claims.json +76 -0
- package/skills/proj-doc-builder/tests/conftest.py +23 -0
- package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
- package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
- package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
- package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
- package/skills/proj-doc-builder/tests/test_load_docs.py +353 -0
- package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
- package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
- package/skills/proj-doc-builder/tests/test_project_docs_contract.py +812 -0
- package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
- package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
- package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
- package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
- package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
- package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
- package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
- package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
- package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
- package/skills/proj-doc-builder/tools/_paths.py +39 -0
- package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
- package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
- package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
- package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
- package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
- package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
- package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
- package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
- package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
- package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
- package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
- package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
- package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
- package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
- package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
- package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
- package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Path bootstrap for the layered ``tools`` layout.
|
|
3
|
+
|
|
4
|
+
Modules live in subpackages (``core``, ``scan``, ``validate``, ``pipeline``,
|
|
5
|
+
``reader``) but keep flat sibling imports (`import scan_dirs`,
|
|
6
|
+
`import project_docs_contract as contract`, ...). Every CLI entry script and
|
|
7
|
+
the test ``conftest.py`` call :func:`install` so those imports resolve no matter
|
|
8
|
+
which directory the process was started from.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
_TOOLS_ROOT = Path(__file__).resolve().parent
|
|
17
|
+
# ``phase4`` is a real package imported as ``import phase4``; only the tools root
|
|
18
|
+
# needs to be on the path for it. Its modules are never imported flat, so adding
|
|
19
|
+
# the directory itself would inject ``engine``/``journal``/... into the top-level
|
|
20
|
+
# namespace for no reason.
|
|
21
|
+
_SUBPACKAGES = ("core", "scan", "validate", "pipeline", "reader")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def install(tools_root: str | Path | None = None) -> Path:
|
|
25
|
+
"""Insert the tools root and every subpackage dir at the front of ``sys.path``.
|
|
26
|
+
|
|
27
|
+
Idempotent. Returns the effective tools root so callers can reuse it.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
root = Path(tools_root).resolve() if tools_root else _TOOLS_ROOT
|
|
31
|
+
for sub in _SUBPACKAGES:
|
|
32
|
+
candidate = root / sub
|
|
33
|
+
if candidate.is_dir():
|
|
34
|
+
text = str(candidate)
|
|
35
|
+
if text not in sys.path:
|
|
36
|
+
sys.path.insert(0, text)
|
|
37
|
+
if str(root) not in sys.path:
|
|
38
|
+
sys.path.insert(0, str(root))
|
|
39
|
+
return root
|
|
@@ -0,0 +1,504 @@
|
|
|
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())
|