@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,212 @@
1
+ # 文档模板 (Phase 2.6)
2
+
3
+ proj-doc-builder v4.5 使用以下模板。Agent 在 Phase 2 生成文档时应严格遵循。
4
+
5
+ > **v4.5 变更**:standard 模板由「概述 + 8 节」扩展为「深度概述 + 11 节」,新增
6
+ > **数据与状态**、**性能与资源特征**、**变更与迁移注意** 三节。doc_contract_version
7
+ > 由 4.1 升为 4.2;旧文档由 `--upgrade-plan` 报告,未变化的历史文档只审计不阻断。
8
+
9
+ ---
10
+
11
+ ## 文件清单铁律
12
+
13
+ > **所有模板共通的强制性规则——违反即质量门控失败。**
14
+
15
+ 1. **每个文件都必须列出**:源码目录中的每个直接普通文件在表格中恰好一行。
16
+ 2. **"关键内容"列禁止泛化**:严禁写"Python 源码"、"文件资源"、"杂项文件"等无信息量描述。
17
+ - Python 文件:列核心 class / function 名称与签名(通过 AST 提取)
18
+ - YAML/JSON 配置:列顶层 key 与用途
19
+ - Markdown 文档:列文档主题
20
+ - 头文件(.h):列核心宏定义、结构体或函数声明
21
+ - C 源文件(.c):列核心函数名
22
+ - 二进制/不可读文件:注明"非文本文件,未自动分析"
23
+ 3. **文件计数一致**:概述中提到的文件数必须等于表格行数。
24
+ 4. **按文件名字母序排列**。
25
+ 5. **空目录降级**:如果源码目录为空(0 个直接文件且 0 个子目录),文档必须使用 placeholder 模板。
26
+ 6. **规模可读**:每行"关键内容"至少给出一个可定位的符号/结构/配置 key,不得只写角色词。
27
+
28
+ ---
29
+
30
+ ## 概述铁律
31
+
32
+ > **概述是文档的信息密度核心——AI 和人类读者首先看的就是概述。**
33
+ > v4.5 起标准概述为 **8–10 句**,须覆盖六个角度;少于 8 句视为信息不足。
34
+
35
+ 1. **禁止模板套话**:严禁使用以下泛化句式(自动检测黑名单):
36
+ - "本目录(X)是 V4 工程中 X 模块的组成单元,承载对应的实现或数据"
37
+ - "构成该单元的主体内容"
38
+ - "该单元与工程内相邻模块通过既有接口与文档契约交互,服务算法对通与测试回归目标"
39
+ - "下辖 N 个子目录,覆盖相关主题域的细分实现"
40
+ - "提供目录归属、公共基础设施与配置支撑"
41
+ - "输出对应的代码或数据产物"
42
+ 2. **六角度必须真实**(8–10 句覆盖):
43
+ - **定位**:目录在工程架构中的确切位置与角色(不是"组成单元")
44
+ - **输入**:从哪些上游模块/数据源、以何种格式接收数据
45
+ - **核心处理**:执行的核心算法/流程,以及并发模型或时序约束
46
+ - **输出**:向下游/调用方交付的数据结构与业务契约
47
+ - **边界**:明确的非职责(本目录不做什么),避免读者误判归属
48
+ - **失败模式**:关键失败路径、降级或熔断策略
49
+ 3. **信息密度要求**:概述至少包含 **4 个具体实体名称**(类名、函数名、标准编号、配置 key、文件名等)。
50
+ 4. **父目录概述**:如果目录无直接文件、只有子目录,概述必须列出各子目录的文件计数与核心职责。
51
+ 5. **不堆砌**:不得为凑句数重复同一事实;一句只承载一个新增信息。
52
+
53
+ ---
54
+
55
+ ## 模板 1: 标准目录(含实质文件)
56
+
57
+ ```markdown
58
+ # <folder_name> — <一句话角色定位>
59
+
60
+ <!-- DOC-PATH: project_docs/<relpath>/<folder_name>.md -->
61
+ <!-- AUTO-GENERATED v3.0: folder-doc START -->
62
+ <!-- Last synced: <ISO8601> by proj-doc-builder v4.5 -->
63
+
64
+ **导航**: <parent_breadcrumb> > **<folder_name>**
65
+
66
+ ## 概述
67
+
68
+ <8-10 句高信息密度实质描述,按「定位 → 输入 → 核心处理 → 输出 → 边界 → 失败模式」
69
+ 六角度展开,至少出现 4 个具体实体名。严禁空话套话。>
70
+
71
+ ## 文件清单
72
+
73
+ | 文件 | 用途 | 关键内容 |
74
+ |------|------|---------|
75
+ | `__init__.py` | <包入口,导出 N 个符号> | `__all__` 包含: A, B, C |
76
+ | `<core_file.py>` | <一句话> | 类: `ClassName`, 函数: `func_name()` |
77
+
78
+ > 每个文件都要列出。如果是二进制文件,注明"非文本文件,未自动分析"。
79
+
80
+ ## 关键符号
81
+
82
+ <仅 Python 包(有 __init__.py)的目录才需要此节。必须通过 AST 真实性核验,严禁虚构不存在的符号。>
83
+
84
+ | 符号 | 类型 | 定义位置 | 说明 |
85
+ |------|------|---------|------|
86
+ | `ClassName` | class | `<file>.py:L行号` | <核心能力 + 对外核心方法完整签名,如 `def run(self, ctx: Context) -> Result`> |
87
+ | `function_name` | function | `<file>.py:L行号` | <完整签名 + 核心业务用途,如 `def calc(v: float) -> float`> |
88
+
89
+ <≤10 文件的叶子目录:列出全部符号。>10 文件:列出最重要的 10 个。父目录:列出各子模块暴露的公共接口。>
90
+
91
+ ## 子目录
92
+
93
+ <如果该目录有子目录>
94
+
95
+ | 子目录 | 用途 | 文档 |
96
+ |--------|------|------|
97
+ | `<subdir1/>` | <一句话> | [<subdir1>.md](relative-link) |
98
+ | `<subdir2/>` | <一句话> | [<subdir2>.md](relative-link) |
99
+
100
+ ## 依赖关系
101
+
102
+ | 方向 | 模块 | 关系 | 文档 |
103
+ |------|------|------|------|
104
+ | ⬆ 上游 | <module> | <明确依赖的上游类名/方法与能力契约> | [link] |
105
+ | ⬇ 下游 | <module> | <明确交付的下游模块与数据结构> | [link] |
106
+ | ↔ 同级 | <module> | <同层协作关系与共享状态总线> | [link] |
107
+
108
+ ## 系统角色
109
+
110
+ <详细说明该目录在整个项目架构中的位置与数据流向。推荐附带极简 ASCII 数据流图:>
111
+
112
+ ```text
113
+ [上游数据源/模块] ──(输入契约)──> [当前模块核心处理] ──(输出契约)──> [下游消费模块]
114
+ ```
115
+
116
+ 必须包含以下至少一项:
117
+ - 在系统分层架构(如 L0~L6)中属于哪一层,上下游交互约束
118
+ - 核心处理模式(如快慢双轨解耦、原子事务、事件流总线)
119
+ - 确切的数据输入源与输出流向
120
+
121
+ ## 数据与状态
122
+
123
+ <说明本目录读写的持久化数据、运行时状态、缓存与生命周期。至少覆盖:
124
+ 1. 写入/读取的文件或数据库(相对路径 + 作用),如 `_scan_state.json`、`.projdoc.toml`;
125
+ 2. 进程内状态(全局单例、缓存、锁)与跨进程状态(文件锁、日志、journal);
126
+ 3. 状态的生命周期:何时创建、何时清理、失败后如何回滚或恢复。
127
+ 如本目录不涉及持久化或状态,写:本节不适用:<一行具体理由>。>
128
+
129
+ ## 性能与资源特征
130
+
131
+ <量化或半量化说明成本特征,避免"性能良好"之类空话。至少覆盖一项:
132
+ 1. 时间复杂度或算法量级(如 O(n log n) 的全树扫描、单次遍历去重);
133
+ 2. 内存/磁盘占用特征(如一次性载入整个 manifest、流式处理大文件);
134
+ 3. IO 与并发约束(如目录 fsync 次数、文件锁粒度、并行 worker 上限)。
135
+ 如确无性能敏感点,写:本节不适用:<一行具体理由>,并说明数据规模上限。>
136
+
137
+ ## 变更与迁移注意
138
+
139
+ <记录升级/迁移时必须知道的事实,避免"无"字敷衍。至少覆盖一项:
140
+ 1. 对外契约变化(配置 key、CLI 参数、manifest 字段、文档格式)及其向后兼容策略;
141
+ 2. 数据迁移路径(旧格式 → 新格式的转换命令或脚本),如 `--migrate-manifest`;
142
+ 3. 已知的破坏性改动与规避方式。
143
+ 如本目录自首版以来无契约变化,写:本节不适用:<一行具体理由>。>
144
+
145
+ ## 使用示例
146
+
147
+ ```python
148
+ # 最小调用闭环代码示例
149
+ from ashare.module import CoreEngine
150
+ engine = CoreEngine()
151
+ result = engine.execute(data)
152
+ ```
153
+
154
+ > **防坑与熔断约束**:<记录模块专属的踩坑经验、反爬限制、并发无锁注意事项或降级熔断机制。如无对外 API 则注明:本节不适用:本目录为内部实现,无对外 API。>
155
+
156
+ ## 状态
157
+
158
+ <当前状态:✅ 完整 / 🔶 开发中 / ⬜ 占位 / 📦 历史存档 / ❓ 未知,以及简短说明>
159
+
160
+ <!-- AUTO-GENERATED v3.0: folder-doc END -->
161
+ ```
162
+
163
+ ### 变体
164
+
165
+ **叶子目录**(无子目录):省略"子目录"节。
166
+ **边界目录**(含自身 CLAUDE.md):概述末尾追加 `> **边界目录**:本目录有独立的 CLAUDE.md,此处仅列概要。`,不递归进入子目录。
167
+ **纯 C 头文件目录**(无 Python `__init__.py`):省略"关键符号"节,但在文件清单的"关键内容"列中列出核心宏定义、结构体名或函数签名。
168
+ **历史存档目录**(归档报告、冻结会话证据、旧版本快照等):状态段使用 `📦 历史存档 — <归档内容与来源说明>`,不得为通过校验而将历史归档标为 `✅ 完整` 或 `⬜ 占位 — 待实现`。
169
+ **纯文档/配置目录**(无源码、无可执行逻辑):仍需保留「数据与状态」「变更与迁移注意」两节;「性能与资源特征」可写 `本节不适用:<理由>`。
170
+
171
+ ---
172
+
173
+ ## 模板 2: 占位目录
174
+
175
+ ```markdown
176
+ # <folder_name> — <一句话用途>
177
+
178
+ <!-- DOC-PATH: project_docs/<relpath>/<folder_name>.md -->
179
+ <!-- AUTO-GENERATED v3.0: folder-doc START -->
180
+ <!-- Last synced: <ISO8601> by proj-doc-builder v4.5 -->
181
+
182
+ **导航**: <parent_breadcrumb> > **<folder_name>**
183
+
184
+ ## 概述
185
+
186
+ <1-2 句话简要描述预期用途>。当前目录为占位,待后续实现。
187
+
188
+ > 占位 profile 允许简短概述;不得为通过校验而虚构实现、符号或依赖。
189
+
190
+ ## 文件清单
191
+
192
+ | 文件 | 用途 |
193
+ |------|------|
194
+ | `__init__.py` | 包初始化文件(空/仅含基本导入) |
195
+
196
+ ## 系统角色
197
+
198
+ > 参见 [父目录文档](../<parent>.md)。
199
+
200
+ ## 状态
201
+
202
+ ⬜ 占位 — 目录已建立,待实现。
203
+
204
+ <!-- AUTO-GENERATED v3.0: folder-doc END -->
205
+ ```
206
+
207
+ ### 占位变体
208
+
209
+ **空目录**(0 文件 0 子目录):文件清单写"(当前目录为空,无直接文件。)",状态写 `⬜ 占位 — 目录当前为空。`
210
+
211
+ > 占位目录不要求「数据与状态」「性能与资源特征」「变更与迁移注意」三节;一旦出现实质文件,
212
+ > 必须切换到 standard 模板并补齐三节。
@@ -0,0 +1,76 @@
1
+ {
2
+ "schema_version": 1,
3
+ "description": "Traceability registry: every guarantee stated in SKILL.md must (a) still appear verbatim in the named doc file and (b) be pinned by a named test function. CI fails if an anchor is edited without updating this file, or if the pinning test is renamed/removed. Add a new claim whenever SKILL.md gains a hard guarantee.",
4
+ "claims": [
5
+ {
6
+ "id": "dry-run-default",
7
+ "doc": "SKILL.md",
8
+ "anchor": "默认先 dry-run;只有所有闸门通过后才运行 coordinator `--apply`。",
9
+ "test_module": "test_sync_project_docs.py",
10
+ "test_function": "test_dry_run_passes_all_gates_without_writing"
11
+ },
12
+ {
13
+ "id": "zero-change-apply-is-noop",
14
+ "doc": "SKILL.md",
15
+ "anchor": "零变化运行不得刷新 `last_synced`、manifest、CLAUDE 或 scan state。",
16
+ "test_module": "test_sync_project_docs.py",
17
+ "test_function": "test_apply_publishes_v2_state_and_second_run_is_noop"
18
+ },
19
+ {
20
+ "id": "pending-journal-blocks-until-recover",
21
+ "doc": "SKILL.md",
22
+ "anchor": "pending Phase 4 journal 必须先通过显式 `--recover` 处理",
23
+ "test_module": "test_phase4_exit.py",
24
+ "test_function": "test_recover_is_blocked_by_every_coordinator_pending_form"
25
+ },
26
+ {
27
+ "id": "phase4-report-only",
28
+ "doc": "SKILL.md",
29
+ "anchor": "Phase 4 默认只报告。不得自动删除文档",
30
+ "test_module": "test_phase4_exit.py",
31
+ "test_function": "test_recover_without_journal_is_successful_noop"
32
+ },
33
+ {
34
+ "id": "no-symlink-follow",
35
+ "doc": "SKILL.md",
36
+ "anchor": "不跟随 symlink、junction 或 reparse point;路径身份不能证明时 fail closed。",
37
+ "test_module": "test_link_tools.py",
38
+ "test_function": "test_link_check_rejects_symlink_escape"
39
+ },
40
+ {
41
+ "id": "strict-utf8",
42
+ "doc": "SKILL.md",
43
+ "anchor": "所有文本严格 UTF-8;Python 文件首行必须是 `# -*- coding: utf-8 -*-`。",
44
+ "test_module": "test_project_docs_contract.py",
45
+ "test_function": "test_build_manifest_rejects_non_utf8_document"
46
+ },
47
+ {
48
+ "id": "manifest-path-rules",
49
+ "doc": "SKILL.md",
50
+ "anchor": "manifest path 仅允许相对 POSIX 小写 `.md` 路径",
51
+ "test_module": "test_project_docs_contract.py",
52
+ "test_function": "test_invalid_manifest_paths"
53
+ },
54
+ {
55
+ "id": "init-creates-claude-skeleton",
56
+ "doc": "SKILL.md",
57
+ "anchor": "并生成根 `CLAUDE.md` 六大区块骨架(仅当文件不存在;已有文件原样保留)。",
58
+ "test_module": "test_v41_upgrades.py",
59
+ "test_function": "test_init_project_creates_the_six_marker_claude_md"
60
+ },
61
+ {
62
+ "id": "full-is-final-gate",
63
+ "doc": "SKILL.md",
64
+ "anchor": "`--full` 强制校验全部文档(`scope = \"all-documents\"`),并要求全量文件清单审计,是发布前的终审档位。",
65
+ "test_module": "test_v45_upgrades.py",
66
+ "test_function": "test_full_blocks_critical_failure_on_unchanged_document"
67
+ },
68
+ {
69
+ "id": "loader-verifies-before-serving",
70
+ "doc": "SKILL.md",
71
+ "anchor": "加载器(只读):先校验 manifest 与文档完全一致,再输出工程速览",
72
+ "test_module": "test_load_docs.py",
73
+ "test_function": "test_brief_refuses_a_stale_manifest"
74
+ }
75
+ ]
76
+ }
@@ -0,0 +1,23 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Test import setup for the layered, standalone proj-doc-builder tools."""
3
+
4
+ import os
5
+ import sys
6
+ from pathlib import Path as _Path
7
+
8
+ # Keep byte-code caches out of the source tree. Two layers are needed:
9
+ # * this interpreter must not compile tool modules while importing them, and
10
+ # * every child interpreter spawned by a test (crash-injection scripts, CLI
11
+ # subprocesses) inherits the switch through the environment.
12
+ # pytest itself may still cache this conftest.py; run `python -B -m pytest`
13
+ # when a completely cache-free tree matters.
14
+ sys.dont_write_bytecode = True
15
+ os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
16
+
17
+ TOOLS_DIR = _Path(__file__).resolve().parents[1] / "tools"
18
+ if str(TOOLS_DIR) not in sys.path:
19
+ sys.path.insert(0, str(TOOLS_DIR))
20
+
21
+ import _paths # noqa: E402
22
+
23
+ _paths.install(TOOLS_DIR)
@@ -0,0 +1,81 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Traceability gate: every guarantee in ``claims.json`` must still be present
3
+ verbatim in its named doc file *and* pinned by a named test function.
4
+
5
+ This is the mechanical closure for the review-loop failure mode where "I read
6
+ the code again and found nothing new" — the author's blind spots repeat each
7
+ round. The registry ties a documented sentence to an executable test, so
8
+ editing the sentence (without updating the registry) or renaming the test
9
+ (without updating the registry) fails CI. Add a claim whenever SKILL.md gains
10
+ a hard guarantee.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import json
17
+ from pathlib import Path
18
+
19
+ import pytest
20
+
21
+ _SKILL_DIR = Path(__file__).resolve().parents[1]
22
+ _REGISTRY = _SKILL_DIR / "tests" / "claims.json"
23
+
24
+
25
+ def _load_claims() -> list[dict]:
26
+ payload = json.loads(_REGISTRY.read_text(encoding="utf-8"))
27
+ claims = payload["claims"]
28
+ assert isinstance(claims, list) and claims, "claims.json has no claims"
29
+ return claims
30
+
31
+
32
+ def _test_functions(module_path: Path) -> set[str]:
33
+ tree = ast.parse(module_path.read_text(encoding="utf-8"), filename=str(module_path))
34
+ return {
35
+ node.name
36
+ for node in ast.walk(tree)
37
+ if isinstance(node, ast.FunctionDef) and node.name.startswith("test_")
38
+ }
39
+
40
+
41
+ CLAIMS = _load_claims()
42
+
43
+
44
+ def test_registry_claims_are_unique() -> None:
45
+ ids = [c["id"] for c in CLAIMS]
46
+ assert len(ids) == len(set(ids)), f"duplicate claim ids: {ids}"
47
+
48
+
49
+ def test_registry_has_at_least_ten_pinned_guarantees() -> None:
50
+ assert len(CLAIMS) >= 10, (
51
+ f"registry shrank to {len(CLAIMS)} claims; the review loop's closure "
52
+ "depends on every hard guarantee being pinned — do not drop claims"
53
+ )
54
+
55
+
56
+ @pytest.mark.parametrize("claim", CLAIMS, ids=lambda c: c["id"])
57
+ def test_claim_anchor_is_present_in_doc(claim: dict) -> None:
58
+ doc_path = _SKILL_DIR / claim["doc"]
59
+ assert doc_path.is_file(), f"claim {claim['id']}: doc {claim['doc']} missing"
60
+ text = doc_path.read_text(encoding="utf-8")
61
+ assert claim["anchor"] in text, (
62
+ f"claim {claim['id']}: anchor not found verbatim in {claim['doc']}.\n"
63
+ f" expected: {claim['anchor']!r}\n"
64
+ " If you edited this sentence, update claims.json to match (the "
65
+ "registry is the source of truth for the guarantee's wording)."
66
+ )
67
+
68
+
69
+ @pytest.mark.parametrize("claim", CLAIMS, ids=lambda c: c["id"])
70
+ def test_claim_is_pinned_by_a_live_test_function(claim: dict) -> None:
71
+ module_path = _SKILL_DIR / "tests" / claim["test_module"]
72
+ assert module_path.is_file(), (
73
+ f"claim {claim['id']}: test module {claim['test_module']} missing"
74
+ )
75
+ funcs = _test_functions(module_path)
76
+ assert claim["test_function"] in funcs, (
77
+ f"claim {claim['id']}: test function {claim['test_function']!r} not "
78
+ f"defined in {claim['test_module']}. If you renamed or deleted it, "
79
+ "either restore it or re-point the claim in claims.json to its "
80
+ "replacement (the guarantee must remain pinned by an executable test)."
81
+ )
@@ -0,0 +1,157 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Tests for deterministic CLAUDE document-tree generation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ import claude_doc_index as indexer
11
+
12
+ SYNCED = "2026-07-30T09:00:00+08:00"
13
+
14
+
15
+ def _manifest() -> dict:
16
+ return {
17
+ "schema_version": 2,
18
+ "producer": {"name": "proj-doc-builder", "version": "4.0"},
19
+ "last_synced": SYNCED,
20
+ "files": [
21
+ {
22
+ "path": "alpha/child.md",
23
+ "title": "child — 子文档",
24
+ "status": "🔶",
25
+ },
26
+ {
27
+ "path": "alpha.md",
28
+ "title": "alpha — 主模块",
29
+ "status": "✅",
30
+ },
31
+ {
32
+ "path": "Beta.md",
33
+ "title": "Beta",
34
+ "status": "⬜",
35
+ },
36
+ ],
37
+ }
38
+
39
+
40
+ def _claude(newline: str = "\n") -> str:
41
+ blocks = ["# CLAUDE.md", "manual-before"]
42
+ for section in indexer.REQUIRED_SECTIONS:
43
+ blocks.extend(
44
+ [
45
+ indexer.section_start(section),
46
+ f"old-{section}",
47
+ indexer.section_end(section),
48
+ f"manual-after-{section}",
49
+ ]
50
+ )
51
+ return newline.join(blocks) + newline
52
+
53
+
54
+ def test_render_tree_is_complete_and_deterministic() -> None:
55
+ rendered = indexer.render_document_tree(_manifest())
56
+ assert rendered.splitlines() == [
57
+ "project_docs/",
58
+ "├── alpha — 主模块 ✅",
59
+ "│ └── child — 子文档 🔶",
60
+ "└── Beta ⬜",
61
+ ]
62
+ assert indexer.render_document_tree(_manifest()) == rendered
63
+
64
+
65
+ def test_tree_merges_case_only_file_directory_spelling() -> None:
66
+ manifest = _manifest()
67
+ manifest["files"].extend(
68
+ [
69
+ {
70
+ "path": "pkg/Worker_Node/RSA.md",
71
+ "title": "RSA",
72
+ "status": "✅",
73
+ },
74
+ {
75
+ "path": "pkg/worker_node.md",
76
+ "title": "Worker_Node — 装配测试",
77
+ "status": "✅",
78
+ },
79
+ ]
80
+ )
81
+ rendered = indexer.render_document_tree(manifest)
82
+ assert "Worker_Node — 装配测试 ✅" in rendered
83
+ assert "└── RSA ✅" in rendered
84
+ assert "worker_node — Worker_Node" not in rendered
85
+
86
+
87
+ def test_replace_changes_only_doc_tree_block() -> None:
88
+ original = _claude()
89
+ updated = indexer.replace_doc_tree_section(original, _manifest())
90
+
91
+ assert "old-doc-tree-instruction" not in updated
92
+ assert "old-project-overview" in updated
93
+ assert "manual-before" in updated
94
+ assert f"Last synced: {SYNCED}" in updated
95
+ for section in indexer.REQUIRED_SECTIONS:
96
+ assert updated.count(indexer.section_start(section)) == 1
97
+ assert updated.count(indexer.section_end(section)) == 1
98
+
99
+
100
+ def test_replace_preserves_crlf_outside_replaced_block() -> None:
101
+ original = _claude("\r\n")
102
+ updated = indexer.replace_doc_tree_section(original, _manifest())
103
+ assert "\r\nmanual-after-doc-tree-instruction\r\n" in updated
104
+ assert "\n" in updated
105
+ assert updated.replace("\r\n", "").find("\n") == -1
106
+
107
+
108
+ def test_marker_missing_duplicate_and_reversed_fail_closed() -> None:
109
+ original = _claude()
110
+ with pytest.raises(indexer.ClaudeIndexError, match="START=0"):
111
+ indexer.validate_required_sections(
112
+ original.replace(indexer.section_start("architecture"), "")
113
+ )
114
+ with pytest.raises(indexer.ClaudeIndexError, match="START=2"):
115
+ indexer.validate_required_sections(
116
+ original + indexer.section_start("architecture")
117
+ )
118
+ start = indexer.section_start("dependencies")
119
+ end = indexer.section_end("dependencies")
120
+ reversed_content = original.replace(
121
+ f"{start}\nold-dependencies\n{end}",
122
+ f"{end}\nold-dependencies\n{start}",
123
+ )
124
+ with pytest.raises(indexer.ClaudeIndexError, match="precedes"):
125
+ indexer.validate_required_sections(reversed_content)
126
+
127
+
128
+ def test_update_is_dry_run_by_default_and_idempotent(tmp_path: Path) -> None:
129
+ path = tmp_path / "CLAUDE.md"
130
+ path.write_text(_claude(), encoding="utf-8")
131
+ before = path.read_bytes()
132
+
133
+ dry = indexer.update_claude_doc_index(path, _manifest())
134
+ assert dry["changed"] is True
135
+ assert path.read_bytes() == before
136
+
137
+ applied = indexer.update_claude_doc_index(path, _manifest(), apply=True)
138
+ assert applied["changed"] is True
139
+ second = indexer.update_claude_doc_index(path, _manifest())
140
+ assert second["changed"] is False
141
+
142
+
143
+ def test_render_tree_pins_index_first() -> None:
144
+ manifest = _manifest()
145
+ manifest["files"].append(
146
+ {
147
+ "path": "index.md",
148
+ "title": "index — 项目全息总览",
149
+ "status": "✅",
150
+ }
151
+ )
152
+ rendered = indexer.render_document_tree(manifest)
153
+ lines = rendered.splitlines()
154
+ assert lines[0] == "project_docs/"
155
+ assert lines[1] == "├── index — 项目全息总览 ✅"
156
+ assert "├── alpha — 主模块 ✅" in lines
157
+