@walvka-code/proj-doc-builder 0.0.0-stage → 4.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -3
  3. package/README.zh-CN.md +258 -0
  4. package/cordis.patch.yml +8 -0
  5. package/icon.svg +11 -0
  6. package/index.js +164 -0
  7. package/locale/en.json +6 -0
  8. package/locale/zh.json +6 -0
  9. package/package.json +59 -4
  10. package/skills/proj-doc-builder/SKILL.md +412 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +103 -0
  12. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  13. package/skills/proj-doc-builder/references/checklist.md +90 -0
  14. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  15. package/skills/proj-doc-builder/references/linking.md +83 -0
  16. package/skills/proj-doc-builder/references/migration.md +32 -0
  17. package/skills/proj-doc-builder/references/phase4.md +200 -0
  18. package/skills/proj-doc-builder/references/templates.md +212 -0
  19. package/skills/proj-doc-builder/tests/claims.json +76 -0
  20. package/skills/proj-doc-builder/tests/conftest.py +23 -0
  21. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  22. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  23. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  24. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  25. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -0
  26. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  27. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  28. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +812 -0
  29. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  30. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  31. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  32. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  33. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  34. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  35. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  36. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  37. package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
  38. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  39. package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
  40. package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
  41. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  42. package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
  43. package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
  44. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
  45. package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
  46. package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
  47. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
  48. package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
  49. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  50. package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
  51. package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
  52. package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
  53. package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
  54. package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
  55. package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
@@ -0,0 +1,654 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Verify and load generated ``project_docs`` documentation for AI consumption.
3
+
4
+ Three modes, all **verify before serving**:
5
+
6
+ ``brief``
7
+ A fast orientation for a fresh conversation: the project abstract (from the
8
+ root ``index.md`` 概述), a one-line role summary per document, and a map of
9
+ the top-level subsystems. Bounded by ``--max-chars`` so it stays cheap.
10
+
11
+ ``overview``
12
+ Verified manifest metadata + rendered document tree + per-document
13
+ title/status/bytes and (optionally) its section names. Small by default so a
14
+ fresh agent conversation can load the shape of a whole project cheaply.
15
+
16
+ ``target``
17
+ One verified document — the whole file, or a single ``##`` section.
18
+
19
+ This tool is a *reader*: it never writes. It reuses
20
+ ``project_docs_contract`` so readers and writers share one set of path, link,
21
+ manifest and hashing rules instead of drifting apart.
22
+
23
+ Exit codes:
24
+ 0 loaded and verified
25
+ 1 the manifest does not match the documents (stale index), or the requested
26
+ target/section is not registered
27
+ 2 usage, path-safety or encoding error
28
+ """
29
+
30
+ from __future__ import annotations
31
+ import sys as _bootstrap_sys
32
+ from pathlib import Path as _bootstrap_path
33
+ _bootstrap_sys.dont_write_bytecode = True
34
+ _bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
35
+ import _paths # noqa: E402
36
+ _paths.install()
37
+
38
+ import argparse
39
+ import re
40
+ import sys
41
+ from pathlib import Path
42
+ from typing import Any, Mapping, Sequence
43
+
44
+ import claude_doc_index
45
+ import proj_doc_config
46
+ import project_docs_contract as contract
47
+
48
+ EXIT_OK = 0
49
+ EXIT_STALE_OR_MISSING = 1
50
+ EXIT_INPUT_ERROR = 2
51
+
52
+ SCHEMA_VERSION = 1
53
+ DOCS_DIRNAME = "project_docs"
54
+ OVERVIEW_SECTION = "概述"
55
+ _SENTENCE_END_RE = re.compile(r"(?<=[。!?;!?;])")
56
+ _INLINE_MARKUP_RE = re.compile(r"[`*_]{1,3}")
57
+ _SECTION_RE = re.compile(r"^##[ \t]+(?P<title>\S.*?)[ \t]*$", re.MULTILINE)
58
+
59
+
60
+ def _docs_root(project_root: str | Path) -> Path:
61
+ """Accept either the project root or the ``project_docs`` directory itself."""
62
+
63
+ root = Path(project_root)
64
+ candidate = root / DOCS_DIRNAME if (root / DOCS_DIRNAME).is_dir() else root
65
+ return contract.resolve_docs_root(candidate)
66
+
67
+
68
+ def _text_result(mode: str, code: str, message: str) -> dict[str, Any]:
69
+ return {
70
+ "schema_version": SCHEMA_VERSION,
71
+ "ok": False,
72
+ "mode": mode,
73
+ "verified": False,
74
+ "errors": [{"code": code, "message": message}],
75
+ }
76
+
77
+
78
+ def _load_verified_manifest(
79
+ docs_root: Path,
80
+ mode: str,
81
+ *,
82
+ target_paths: Sequence[str] | None = None,
83
+ ) -> tuple[dict[str, Any] | None, dict[str, Any] | None, int]:
84
+ """Return ``(manifest, error_result, exit_code)``; exactly one is non-None."""
85
+
86
+ try:
87
+ if target_paths is not None:
88
+ manifest = contract.load_manifest(
89
+ docs_root,
90
+ verify_files=True,
91
+ verify_complete_set=False,
92
+ target_paths=target_paths,
93
+ )
94
+ else:
95
+ manifest = contract.load_manifest(
96
+ docs_root,
97
+ verify_files=True,
98
+ verify_complete_set=True,
99
+ )
100
+ except FileNotFoundError:
101
+ return None, _text_result(
102
+ mode,
103
+ "manifest-missing",
104
+ f"no {contract.MANIFEST_FILENAME} in {docs_root}; run the synchronizer first",
105
+ ), EXIT_STALE_OR_MISSING
106
+ except (
107
+ contract.ManifestFileMismatchError,
108
+ contract.ManifestValidationError,
109
+ contract.ManifestSchemaError,
110
+ ) as exc:
111
+ return None, _text_result(
112
+ mode,
113
+ "manifest-stale",
114
+ "manifest does not match the documents on disk, refusing to serve a "
115
+ f"stale index ({exc})",
116
+ ), EXIT_STALE_OR_MISSING
117
+ except contract.ProjectDocsContractError as exc:
118
+ return None, _text_result(mode, "manifest-invalid", str(exc)), EXIT_STALE_OR_MISSING
119
+ except (OSError, ValueError) as exc:
120
+ return None, _text_result(mode, "manifest-unreadable", str(exc)), EXIT_STALE_OR_MISSING
121
+ return manifest, None, EXIT_OK
122
+
123
+
124
+ def split_sections(content: str) -> list[dict[str, str]]:
125
+ """Split Markdown into ``##`` sections, preserving order and body text."""
126
+
127
+ matches = list(_SECTION_RE.finditer(content))
128
+ sections: list[dict[str, str]] = []
129
+ for index, match in enumerate(matches):
130
+ title = match.group("title").strip()
131
+ start = match.end()
132
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(content)
133
+ sections.append({"title": title, "body": content[start:end].strip()})
134
+ return sections
135
+
136
+
137
+ def _normalize_target(value: str) -> str:
138
+ """Map a source directory, a document path, or a project-relative path to a doc path."""
139
+
140
+ raw = value.strip().replace("\\", "/")
141
+ if raw.startswith("./"):
142
+ raw = raw[2:]
143
+ if raw.startswith(f"{DOCS_DIRNAME}/"):
144
+ raw = raw[len(DOCS_DIRNAME) + 1 :]
145
+ if raw in {"", ".", "/"}:
146
+ raw = "index.md"
147
+ elif not raw.endswith(".md"):
148
+ raw = raw.rstrip("/") + ".md"
149
+ return contract.validate_manifest_relative_path(raw).as_posix()
150
+
151
+
152
+ def _entry_by_path(manifest: Mapping[str, Any], relative: str) -> dict[str, Any] | None:
153
+ entries = manifest.get("files", [])
154
+ folded = relative.casefold()
155
+ for entry in entries:
156
+ if isinstance(entry, Mapping) and str(entry.get("path", "")).casefold() == folded:
157
+ return dict(entry)
158
+ return None
159
+
160
+
161
+ def overview(
162
+ manifest: Mapping[str, Any],
163
+ docs_root: Path,
164
+ *,
165
+ limit: int = 80,
166
+ sections: int = 6,
167
+ include_tree: bool = True,
168
+ ) -> dict[str, Any]:
169
+ """Verified project shape: tree, counts, and per-document metadata."""
170
+
171
+ entries = [dict(item) for item in manifest.get("files", []) if isinstance(item, Mapping)]
172
+ entries.sort(key=lambda item: str(item.get("path", "")))
173
+ returned = entries if limit <= 0 else entries[:limit]
174
+
175
+ documents: list[dict[str, Any]] = []
176
+ for entry in returned:
177
+ relative = str(entry.get("path", ""))
178
+ item = {
179
+ "path": relative,
180
+ "title": entry.get("title"),
181
+ "status": entry.get("status"),
182
+ "bytes": entry.get("bytes"),
183
+ "depth": entry.get("depth"),
184
+ }
185
+ if sections > 0:
186
+ try:
187
+ content = contract.read_project_document(docs_root, relative)
188
+ except contract.ProjectDocsContractError:
189
+ content = ""
190
+ item["sections"] = [item_["title"] for item_ in split_sections(content)][:sections]
191
+ documents.append(item)
192
+
193
+ contract_versions = _contract_versions(entries)
194
+ result: dict[str, Any] = {
195
+ "schema_version": SCHEMA_VERSION,
196
+ "ok": True,
197
+ "mode": "overview",
198
+ "verified": True,
199
+ "docs_root": DOCS_DIRNAME,
200
+ "manifest": {
201
+ "schema_version": manifest.get("schema_version"),
202
+ "generation_id": manifest.get("generation_id"),
203
+ "last_synced": manifest.get("last_synced"),
204
+ "total": manifest.get("total"),
205
+ "depth_counts": manifest.get("depth_counts"),
206
+ "doc_contract_version": contract_versions[-1] if contract_versions else None,
207
+ "doc_contract_versions": contract_versions,
208
+ },
209
+ "counts": {
210
+ "documents": len(entries),
211
+ "returned": len(documents),
212
+ },
213
+ "documents": documents,
214
+ }
215
+ if include_tree:
216
+ try:
217
+ idx_cfg = proj_doc_config.load_project_config(docs_root.parent).claude_index
218
+ result["tree"] = claude_doc_index.render_document_tree(
219
+ manifest,
220
+ max_bytes=idx_cfg.max_bytes,
221
+ max_depth=idx_cfg.max_depth,
222
+ collapse_threshold=idx_cfg.collapse_threshold,
223
+ )
224
+ except (OSError, proj_doc_config.ConfigError):
225
+ result["tree"] = claude_doc_index.render_document_tree(manifest)
226
+ if len(documents) < len(entries):
227
+ result["omitted"] = {
228
+ "documents": len(entries) - len(documents),
229
+ "reason": f"limit={limit}; pass --limit 0 for every document",
230
+ }
231
+ return result
232
+
233
+
234
+ def _plain_text(value: str) -> str:
235
+ """Strip inline Markdown emphasis/code marks and collapse whitespace."""
236
+
237
+ return re.sub(r"\s+", " ", _INLINE_MARKUP_RE.sub("", value)).strip()
238
+
239
+
240
+ def _condense(value: str, max_chars: int) -> str:
241
+ """Trim to whole sentences within ``max_chars`` (hard cut only as a fallback)."""
242
+
243
+ text = _plain_text(value)
244
+ if max_chars <= 0 or len(text) <= max_chars:
245
+ return text
246
+ kept = ""
247
+ for part in (part for part in _SENTENCE_END_RE.split(text) if part.strip()):
248
+ if len(kept) + len(part) > max_chars:
249
+ if not kept:
250
+ # The very first sentence already overflows: hard-cut it.
251
+ return text[: max(1, max_chars - 1)].rstrip() + "…"
252
+ break
253
+ kept += part
254
+ if not kept:
255
+ return text[: max(1, max_chars - 1)].rstrip() + "…"
256
+ return kept.rstrip() + "…" if len(kept) < len(text) else kept.rstrip()
257
+
258
+
259
+ def _section_body(content: str, title: str) -> str:
260
+ wanted = title.casefold()
261
+ for item in split_sections(content):
262
+ if item["title"].casefold() == wanted:
263
+ return item["body"]
264
+ return ""
265
+
266
+
267
+ def _version_key(value: str) -> tuple[tuple[int, object], ...]:
268
+ """Order dotted version strings numerically when every part is an integer."""
269
+
270
+ key: list[tuple[int, object]] = []
271
+ for chunk in str(value).split("."):
272
+ key.append((0, int(chunk)) if chunk.isdigit() else (1, chunk))
273
+ return tuple(key)
274
+
275
+
276
+ def _contract_versions(entries: Sequence[Mapping[str, Any]]) -> list[str]:
277
+ """Distinct per-document ``doc_contract_version`` values, oldest first.
278
+
279
+ The manifest records the contract version on each file entry (so unchanged
280
+ documents keep the version they were written under), never at top level.
281
+ """
282
+
283
+ seen = {
284
+ str(entry.get("doc_contract_version"))
285
+ for entry in entries
286
+ if entry.get("doc_contract_version") not in (None, "")
287
+ }
288
+ return sorted(seen, key=_version_key)
289
+
290
+
291
+ def _document_summary(docs_root: Path, relative: str, summary_chars: int) -> str:
292
+ try:
293
+ content = contract.read_project_document(docs_root, relative)
294
+ except contract.ProjectDocsContractError:
295
+ return ""
296
+ body = _section_body(content, OVERVIEW_SECTION)
297
+ if not body:
298
+ # No 概述 section: fall back to the leading prose before the first table.
299
+ body = content.split("\n|", 1)[0]
300
+ return _condense(body, summary_chars)
301
+
302
+
303
+ def brief(
304
+ manifest: Mapping[str, Any],
305
+ docs_root: Path,
306
+ *,
307
+ limit: int = 0,
308
+ summary_chars: int = 240,
309
+ max_chars: int = 16000,
310
+ ) -> dict[str, Any]:
311
+ """Cheap orientation pass: project abstract plus one-line roles per document."""
312
+
313
+ entries = [dict(item) for item in manifest.get("files", []) if isinstance(item, Mapping)]
314
+ entries.sort(key=lambda item: str(item.get("path", "")))
315
+ abstract_path = next(
316
+ (str(entry.get("path", "")) for entry in entries if str(entry.get("path", "")) == "index.md"),
317
+ None,
318
+ )
319
+ abstract = (
320
+ _document_summary(docs_root, abstract_path, max(400, summary_chars * 2))
321
+ if abstract_path is not None
322
+ else ""
323
+ )
324
+
325
+ selected = entries if limit <= 0 else entries[:limit]
326
+ documents: list[dict[str, Any]] = []
327
+ used = len(abstract)
328
+ omitted_for_budget = 0
329
+ for entry in selected:
330
+ relative = str(entry.get("path", ""))
331
+ cost = len(relative) + summary_chars + 32
332
+ if used + cost > max_chars and documents:
333
+ omitted_for_budget = len(selected) - len(documents)
334
+ break
335
+ summary = _document_summary(docs_root, relative, summary_chars)
336
+ used += len(relative) + len(summary) + 32
337
+ documents.append(
338
+ {
339
+ "path": relative,
340
+ "title": entry.get("title"),
341
+ "status": entry.get("status"),
342
+ "depth": entry.get("depth"),
343
+ "summary": summary,
344
+ }
345
+ )
346
+
347
+ subsystems = [item for item in documents if (item.get("depth") or 0) <= 1]
348
+ contract_versions = _contract_versions(entries)
349
+ result: dict[str, Any] = {
350
+ "schema_version": SCHEMA_VERSION,
351
+ "ok": True,
352
+ "mode": "brief",
353
+ "verified": True,
354
+ "docs_root": DOCS_DIRNAME,
355
+ "manifest": {
356
+ "schema_version": manifest.get("schema_version"),
357
+ "generation_id": manifest.get("generation_id"),
358
+ "last_synced": manifest.get("last_synced"),
359
+ "total": manifest.get("total"),
360
+ "depth_counts": manifest.get("depth_counts"),
361
+ "doc_contract_version": contract_versions[-1] if contract_versions else None,
362
+ "doc_contract_versions": contract_versions,
363
+ },
364
+ "abstract": abstract,
365
+ "counts": {
366
+ "documents": len(entries),
367
+ "summarized": len(documents),
368
+ },
369
+ "subsystems": subsystems,
370
+ "documents": documents,
371
+ "hints": {
372
+ "drill_down": "--mode target --target <doc path> [--section <## title>]",
373
+ "full_shape": "--mode overview --limit 0 --sections 0",
374
+ "refresh": "--mode brief after the synchronizer runs; stale manifests are refused",
375
+ },
376
+ }
377
+ if omitted_for_budget:
378
+ result["omitted"] = {
379
+ "documents": omitted_for_budget,
380
+ "reason": f"max_chars={max_chars}; raise --max-chars for every summary",
381
+ }
382
+ elif len(documents) < len(entries):
383
+ result["omitted"] = {
384
+ "documents": len(entries) - len(documents),
385
+ "reason": f"limit={limit}; pass --limit 0 for every document",
386
+ }
387
+ return result
388
+
389
+
390
+ def target(
391
+ manifest: Mapping[str, Any],
392
+ docs_root: Path,
393
+ requested: str,
394
+ *,
395
+ section: str | None = None,
396
+ ) -> tuple[dict[str, Any], int]:
397
+ """Load one verified document, optionally narrowed to a single ``##`` section."""
398
+
399
+ try:
400
+ relative = _normalize_target(requested)
401
+ except (contract.PathValidationError, ValueError) as exc:
402
+ return _text_result("target", "unsafe-target", str(exc)), EXIT_INPUT_ERROR
403
+
404
+ entry = _entry_by_path(manifest, relative)
405
+ if entry is None:
406
+ return _text_result(
407
+ "target",
408
+ "target-not-registered",
409
+ f"{relative} is not registered in the manifest; "
410
+ "run --dry-run to see the current worklist",
411
+ ), EXIT_STALE_OR_MISSING
412
+
413
+ canonical = str(entry["path"])
414
+ try:
415
+ content = contract.read_project_document(docs_root, canonical)
416
+ except contract.ProjectDocsContractError as exc:
417
+ return _text_result("target", "target-unreadable", str(exc)), EXIT_INPUT_ERROR
418
+
419
+ result: dict[str, Any] = {
420
+ "schema_version": SCHEMA_VERSION,
421
+ "ok": True,
422
+ "mode": "target",
423
+ "verified": True,
424
+ "doc": {
425
+ "path": canonical,
426
+ "title": entry.get("title"),
427
+ "status": entry.get("status"),
428
+ "bytes": entry.get("bytes"),
429
+ "sha256": entry.get("sha256"),
430
+ "synced_at": entry.get("synced_at"),
431
+ },
432
+ "available_sections": [item["title"] for item in split_sections(content)],
433
+ }
434
+
435
+ if section is None:
436
+ result["content"] = content
437
+ return result, EXIT_OK
438
+
439
+ wanted = section.strip().casefold()
440
+ for item in split_sections(content):
441
+ if item["title"].casefold() == wanted:
442
+ result["section"] = item["title"]
443
+ result["content"] = item["body"]
444
+ return result, EXIT_OK
445
+ failure = _text_result(
446
+ "target",
447
+ "section-not-found",
448
+ f"no '## {section}' section in {canonical}",
449
+ )
450
+ failure["available_sections"] = result["available_sections"]
451
+ return failure, EXIT_STALE_OR_MISSING
452
+
453
+
454
+ def execute(
455
+ project_root: str | Path,
456
+ *,
457
+ mode: str = "overview",
458
+ requested: str | None = None,
459
+ section: str | None = None,
460
+ limit: int = 80,
461
+ sections: int = 6,
462
+ include_tree: bool = True,
463
+ summary_chars: int = 240,
464
+ max_chars: int = 16000,
465
+ ) -> tuple[dict[str, Any], int]:
466
+ """Run one load: verify the manifest, then serve the requested view."""
467
+
468
+ try:
469
+ docs_root = _docs_root(project_root)
470
+ except contract.ProjectDocsContractError as exc:
471
+ return _text_result(mode, "docs-root-invalid", str(exc)), EXIT_INPUT_ERROR
472
+ except OSError as exc:
473
+ return _text_result(mode, "project-root-invalid", str(exc)), EXIT_INPUT_ERROR
474
+
475
+ if mode == "target":
476
+ if requested is None:
477
+ return _text_result(mode, "target-required", "--target is required for target mode"), EXIT_INPUT_ERROR
478
+ try:
479
+ normalized_target = _normalize_target(requested)
480
+ except (contract.PathValidationError, ValueError) as exc:
481
+ return _text_result("target", "unsafe-target", str(exc)), EXIT_INPUT_ERROR
482
+ manifest, error, exit_code = _load_verified_manifest(
483
+ docs_root,
484
+ mode,
485
+ target_paths=(normalized_target,),
486
+ )
487
+ if manifest is None:
488
+ assert error is not None
489
+ return error, exit_code
490
+ return target(manifest, docs_root, requested, section=section)
491
+
492
+ if mode == "brief":
493
+ manifest, error, exit_code = _load_verified_manifest(docs_root, mode)
494
+ if manifest is None:
495
+ assert error is not None
496
+ return error, exit_code
497
+ return brief(
498
+ manifest,
499
+ docs_root,
500
+ limit=limit,
501
+ summary_chars=summary_chars,
502
+ max_chars=max_chars,
503
+ ), EXIT_OK
504
+
505
+ if mode != "overview":
506
+ return _text_result(mode, "unknown-mode", f"unsupported mode {mode!r}"), EXIT_INPUT_ERROR
507
+
508
+ manifest, error, exit_code = _load_verified_manifest(docs_root, mode)
509
+ if manifest is None:
510
+ assert error is not None
511
+ return error, exit_code
512
+
513
+ return overview(
514
+ manifest,
515
+ docs_root,
516
+ limit=limit,
517
+ sections=sections,
518
+ include_tree=include_tree,
519
+ ), EXIT_OK
520
+
521
+
522
+ def _parser() -> argparse.ArgumentParser:
523
+ parser = argparse.ArgumentParser(
524
+ description="Verify and load generated project_docs documentation",
525
+ )
526
+ parser.add_argument("root", nargs="?", default=".", help="project root or project_docs")
527
+ parser.add_argument(
528
+ "--mode",
529
+ choices=("brief", "overview", "target"),
530
+ default="overview",
531
+ help="brief = fast orientation; overview = project shape; target = one document",
532
+ )
533
+ parser.add_argument(
534
+ "--target",
535
+ "-t",
536
+ default=None,
537
+ help="source directory, document path, or project-relative path",
538
+ )
539
+ parser.add_argument(
540
+ "--section",
541
+ "-s",
542
+ default=None,
543
+ help="with --target: return only this '##' section",
544
+ )
545
+ parser.add_argument(
546
+ "--limit",
547
+ type=int,
548
+ default=80,
549
+ help="max documents in overview (0 = all)",
550
+ )
551
+ parser.add_argument(
552
+ "--sections",
553
+ type=int,
554
+ default=6,
555
+ help="max section names per document in overview (0 = none)",
556
+ )
557
+ parser.add_argument("--no-tree", action="store_true", help="omit the rendered tree")
558
+ parser.add_argument(
559
+ "--summary-chars",
560
+ type=int,
561
+ default=240,
562
+ help="brief: max characters of the 概述 kept per document (0 = whole 概述)",
563
+ )
564
+ parser.add_argument(
565
+ "--max-chars",
566
+ type=int,
567
+ default=16000,
568
+ help="brief: total character budget for all summaries (0 = unlimited)",
569
+ )
570
+ parser.add_argument("--json", action="store_true", help="emit exactly one JSON document")
571
+ return parser
572
+
573
+
574
+ def _emit(result: Mapping[str, Any], *, as_json: bool) -> None:
575
+ if as_json:
576
+ sys.stdout.write(contract.stable_json_dumps(dict(result)))
577
+ return
578
+ if not result.get("ok"):
579
+ for error in result.get("errors", []):
580
+ print(f"ERROR [{error['code']}]: {error['message']}", file=sys.stderr)
581
+ return
582
+ if result.get("mode") == "brief":
583
+ manifest = result["manifest"]
584
+ print(
585
+ f"工程速览 documents: {result['counts']['documents']} "
586
+ f"(summarized {result['counts']['summarized']}) "
587
+ f"generation: {manifest.get('generation_id')} "
588
+ f"contract: {', '.join(result['manifest']['doc_contract_versions']) or 'unknown'}"
589
+ )
590
+ if result.get("abstract"):
591
+ print("\n摘要:")
592
+ print(result["abstract"])
593
+ print("\n## 顶层子系统")
594
+ for item in result.get("subsystems", []):
595
+ print(f"- {item['path']} — {item['title']} {item['status'] or ''}")
596
+ if item.get("summary"):
597
+ print(f" {item['summary']}")
598
+ deeper = [
599
+ item for item in result.get("documents", []) if item not in result.get("subsystems", [])
600
+ ]
601
+ if deeper:
602
+ print(f"\n## 其余文档 ({len(deeper)})")
603
+ for item in deeper:
604
+ print(f"- {item['path']} — {item['title']} {item['status'] or ''}")
605
+ if item.get("summary"):
606
+ print(f" {item['summary']}")
607
+ if result.get("omitted"):
608
+ print(
609
+ f"\n(省略 {result['omitted']['documents']} 篇: {result['omitted']['reason']})"
610
+ )
611
+ hints = result.get("hints") or {}
612
+ if hints:
613
+ print("\n深入:")
614
+ for line in hints.values():
615
+ print(f" {line}")
616
+ return
617
+ if result.get("mode") == "overview":
618
+ manifest = result["manifest"]
619
+ print(
620
+ f"documents: {result['counts']['documents']} "
621
+ f"(returned {result['counts']['returned']}) "
622
+ f"generation: {manifest['generation_id']}"
623
+ )
624
+ print(result.get("tree", ""))
625
+ for item in result["documents"]:
626
+ sections = ", ".join(item.get("sections") or [])
627
+ print(f"- {item['path']} — {item['title']} {item['status']}")
628
+ if sections:
629
+ print(f" sections: {sections}")
630
+ return
631
+ print(result.get("content", ""))
632
+
633
+
634
+ def main(argv: Sequence[str] | None = None) -> int:
635
+ contract.configure_stdio_utf8()
636
+ args = _parser().parse_args(argv)
637
+ result, exit_code = execute(
638
+ args.root,
639
+ mode=args.mode,
640
+ requested=args.target,
641
+ section=args.section,
642
+ limit=args.limit,
643
+ sections=args.sections,
644
+ include_tree=not args.no_tree,
645
+ summary_chars=args.summary_chars,
646
+ max_chars=args.max_chars,
647
+ )
648
+ result["exit_code"] = exit_code
649
+ _emit(result, as_json=args.json)
650
+ return exit_code
651
+
652
+
653
+ if __name__ == "__main__":
654
+ raise SystemExit(main())