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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +271 -2
  3. package/README.zh-CN.md +240 -0
  4. package/cordis.patch.yml +8 -0
  5. package/icon.svg +11 -0
  6. package/index.js +164 -0
  7. package/locale/en.json +6 -0
  8. package/locale/zh.json +6 -0
  9. package/package.json +55 -4
  10. package/skills/proj-doc-builder/SKILL.md +350 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +96 -0
  12. package/skills/proj-doc-builder/references/checklist.md +80 -0
  13. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  14. package/skills/proj-doc-builder/references/linking.md +83 -0
  15. package/skills/proj-doc-builder/references/migration.md +32 -0
  16. package/skills/proj-doc-builder/references/phase4.md +200 -0
  17. package/skills/proj-doc-builder/references/templates.md +172 -0
  18. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  19. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  20. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  21. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  22. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  23. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  24. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  25. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  26. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  27. package/skills/proj-doc-builder/tests/conftest.py +11 -0
  28. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  29. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  30. package/skills/proj-doc-builder/tests/test_load_docs.py +248 -0
  31. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  32. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  33. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +781 -0
  34. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  35. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  36. package/skills/proj-doc-builder/tests/test_validate_doc.py +555 -0
  37. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  38. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  39. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  40. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  41. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  42. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  43. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  44. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  45. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
  46. package/skills/proj-doc-builder/tools/claude_doc_index.py +298 -0
  47. package/skills/proj-doc-builder/tools/compute_link.py +233 -0
  48. package/skills/proj-doc-builder/tools/link_check.py +152 -0
  49. package/skills/proj-doc-builder/tools/load_docs.py +380 -0
  50. package/skills/proj-doc-builder/tools/normalize_markers.py +205 -0
  51. package/skills/proj-doc-builder/tools/phase4/__init__.py +57 -0
  52. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +18 -0
  53. package/skills/proj-doc-builder/tools/phase4/engine.py +20 -0
  54. package/skills/proj-doc-builder/tools/phase4/journal.py +22 -0
  55. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +20 -0
  56. package/skills/proj-doc-builder/tools/phase4_exit.py +8459 -0
  57. package/skills/proj-doc-builder/tools/project_docs_contract.py +2318 -0
  58. package/skills/proj-doc-builder/tools/scan_dirs.py +2405 -0
  59. package/skills/proj-doc-builder/tools/sync_project_docs.py +3639 -0
  60. package/skills/proj-doc-builder/tools/validate_doc.py +1299 -0
package/index.js ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Bundled `proj-doc-builder` skill provider for DeepSeek Harness.
3
+ *
4
+ * This package ships the skill (SKILL.md, tools/, references/, tests/) inside
5
+ * `skills/proj-doc-builder/`. The provider reads the Markdown body at load time
6
+ * and reports the skill directory as its resource base, so every relative path
7
+ * in the instructions resolves beside the installed package instead of a
8
+ * project-local `.dsh/skills/proj-doc-builder/` checkout.
9
+ *
10
+ * Rank 600 is the bundled rank: a project-local or user-level copy of the same
11
+ * skill still wins, which is what lets a repository pin its own version.
12
+ *
13
+ * @module @walvka-code/proj-doc-builder
14
+ */
15
+ import { readFile } from "node:fs/promises";
16
+ import { dirname, join } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ /** Cordis plugin name. */
20
+ export const name = "proj-doc-builder";
21
+
22
+ /** Service required by this bundled provider. */
23
+ export const inject = ["skills"];
24
+
25
+ /** Registry provider name; unique across mounted skill providers. */
26
+ const PROVIDER_NAME = "proj-doc-builder";
27
+
28
+ /** Standard precedence rank for packaged skill providers and local bundled roots. */
29
+ const BUNDLED_SKILL_RANK = 600;
30
+
31
+ const SKILL_DIR = join(dirname(fileURLToPath(import.meta.url)), "skills", "proj-doc-builder");
32
+ const SKILL_FILE = join(SKILL_DIR, "SKILL.md");
33
+
34
+ /** Used only when SKILL.md frontmatter cannot be read, so the catalog never loses the skill. */
35
+ const DESCRIPTION_FALLBACK =
36
+ "Safely scan, validate, and synchronize AI-readable project documentation, the manifest and the CLAUDE document tree.";
37
+
38
+ /**
39
+ * Strip one pair of matching quotes from a scalar.
40
+ * @param {string} value - raw frontmatter scalar.
41
+ * @returns {string} unquoted scalar.
42
+ */
43
+ function unquote(value) {
44
+ const match = /^(['"])([\s\S]*)\1$/.exec(value);
45
+ return match ? match[2] : value;
46
+ }
47
+
48
+ /**
49
+ * Parse the flat YAML frontmatter this skill declares.
50
+ *
51
+ * Only top-level `key: value` pairs and folded (`>`) or literal (`|`) block
52
+ * scalars are modelled; nested mappings are ignored, which is enough for the
53
+ * `name`, `description` and invocation keys the skill registry consumes.
54
+ *
55
+ * @param {string} text - complete SKILL.md source.
56
+ * @returns {{ meta: Record<string, string>, body: string }} parsed metadata and the Markdown body.
57
+ */
58
+ export function parseFrontMatter(text) {
59
+ const source = text.replace(/^\uFEFF/, "");
60
+ const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?/.exec(source);
61
+ if (!match) return { meta: {}, body: source };
62
+
63
+ /** @type {Record<string, string>} */
64
+ const meta = {};
65
+ let blockKey = null;
66
+ for (const line of match[1].split(/\r?\n/)) {
67
+ if (!line.trim()) continue;
68
+ const pair = /^([A-Za-z0-9_-]+):(.*)$/.exec(line);
69
+ if (pair) {
70
+ const [, key, rest] = pair;
71
+ const value = rest.trim();
72
+ if (value === ">" || value === "|" || value === ">-" || value === "|-") {
73
+ blockKey = key;
74
+ meta[key] = "";
75
+ } else if (value === "") {
76
+ blockKey = null;
77
+ meta[key] = "";
78
+ } else {
79
+ blockKey = null;
80
+ meta[key] = unquote(value);
81
+ }
82
+ continue;
83
+ }
84
+ if (blockKey && /^\s+\S/.test(line)) {
85
+ const piece = line.trim();
86
+ meta[blockKey] = meta[blockKey] ? `${meta[blockKey]} ${piece}` : piece;
87
+ }
88
+ }
89
+ for (const key of Object.keys(meta)) meta[key] = meta[key].replace(/\s+/g, " ").trim();
90
+ return { meta, body: source.slice(match[0].length) };
91
+ }
92
+
93
+ /**
94
+ * Resolve invocation controls from frontmatter flags.
95
+ * @param {Record<string, string>} meta - parsed frontmatter.
96
+ * @returns {{ modelInvocable: boolean, userInvocable: boolean }} invocation policy.
97
+ */
98
+ function invocationOf(meta) {
99
+ const flag = (key, fallback) => {
100
+ const value = meta[key];
101
+ if (value === undefined || value === "") return fallback;
102
+ return value === "true";
103
+ };
104
+ return {
105
+ modelInvocable: !flag("disable-model-invocation", false),
106
+ userInvocable: flag("user-invocable", true),
107
+ };
108
+ }
109
+
110
+ /** @type {{ meta: Record<string, string>, body: string } | undefined} */
111
+ let cachedSkill;
112
+
113
+ /**
114
+ * Read and cache SKILL.md.
115
+ * @param {{ signal?: AbortSignal }} [options] - lookup options.
116
+ * @returns {Promise<{ meta: Record<string, string>, body: string }>} parsed skill.
117
+ */
118
+ async function loadSkill(options) {
119
+ options?.signal?.throwIfAborted?.();
120
+ if (!cachedSkill) {
121
+ cachedSkill = parseFrontMatter(await readFile(SKILL_FILE, "utf8"));
122
+ }
123
+ return cachedSkill;
124
+ }
125
+
126
+ /**
127
+ * Build the registry-facing summary of one parsed skill.
128
+ * @param {Record<string, string>} meta - parsed frontmatter.
129
+ * @returns {object} skill candidate without `rank`/`locator`.
130
+ */
131
+ function summaryOf(meta) {
132
+ return {
133
+ name: meta.name || PROVIDER_NAME,
134
+ description: meta.description || DESCRIPTION_FALLBACK,
135
+ invocation: invocationOf(meta),
136
+ source: "bundled",
137
+ provider: PROVIDER_NAME,
138
+ resourceBase: { kind: "directory", path: SKILL_DIR },
139
+ };
140
+ }
141
+
142
+ /** @type {import('@deepseek-ai/dsh-skill').SkillProvider} */
143
+ const provider = {
144
+ name: PROVIDER_NAME,
145
+ async list(options = {}) {
146
+ if (options.signal?.aborted) return [];
147
+ const { meta } = await loadSkill(options);
148
+ return [{ ...summaryOf(meta), rank: BUNDLED_SKILL_RANK, locator: SKILL_FILE }];
149
+ },
150
+ async get(_candidate, options = {}) {
151
+ if (options.signal?.aborted) return undefined;
152
+ const { meta, body } = await loadSkill(options);
153
+ return { ...summaryOf(meta), content: body };
154
+ },
155
+ };
156
+
157
+ /**
158
+ * Register the bundled provider on `ctx.skills`.
159
+ * @param {import('@deepseek-ai/cordis').Context} ctx - owning context.
160
+ * @returns {void}
161
+ */
162
+ export function apply(ctx) {
163
+ ctx.skills.registerProvider(() => provider);
164
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "proj_doc_builder",
4
+ "description": "Scan, validate and publish AI-readable project documentation with a committed scan state."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "proj_doc_builder 文档同步",
4
+ "description": "扫描、校验并发布 AI 可读的项目文档,附带已提交的扫描基线。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@walvka-code/proj-doc-builder",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.0.0",
4
+ "description": "DeepSeek Harness bundle for the proj-doc-builder skill: scan, validate and publish AI-readable project documentation with committed scan state.",
5
+ "icon": "./icon.svg",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./skills/*": "./skills/*",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "cordis.patch.yml",
18
+ "icon.svg",
19
+ "locale/*.json",
20
+ "README.md",
21
+ "skills/**/*"
22
+ ],
23
+ "keywords": [
24
+ "dsh-bundle",
25
+ "dsh-skill",
26
+ "project-docs",
27
+ "documentation",
28
+ "sync"
29
+ ],
30
+ "license": "MIT",
31
+ "author": "walvka-code",
32
+ "homepage": "https://github.com/walvka-code/proj-doc-builder#readme",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/walvka-code/proj-doc-builder.git"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/walvka-code/proj-doc-builder/issues"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "engines": {
44
+ "node": ">=20",
45
+ "dsh": ">=0.2.1-rc.5"
46
+ },
47
+ "dsh": {
48
+ "bundle": {
49
+ "patch": "./cordis.patch.yml"
50
+ }
51
+ },
52
+ "scripts": {
53
+ "check": "node scripts/check-bundle.mjs",
54
+ "test": "node --test",
55
+ "release": "node scripts/release.mjs"
56
+ }
57
+ }
@@ -0,0 +1,350 @@
1
+ ---
2
+ name: proj-doc-builder
3
+ description: >
4
+ Safely scan, validate, and synchronize AI-readable project documentation,
5
+ manifest v2, the CLAUDE document-tree index, and committed scan state. Use
6
+ when the user asks to sync, refresh, generate, or validate project docs.
7
+ 也是「文档同步手册」:`project_docs/` 的定位(索引而非权威)、权威顺序、
8
+ 以及「发现漂移要登记而不是粉饰」的纪律。
9
+ Triggers: "同步文档", "project_docs", "文档树", "CLAUDE.md", "generate docs",
10
+ "sync docs", "validate docs", "文档漂移", "权威顺序", "索引不是权威"
11
+ version: "4.0"
12
+ disable-model-invocation: false
13
+ user-invocable: true
14
+ allowed-tools:
15
+ - Bash
16
+ - Read
17
+ - Write
18
+ - Glob
19
+ - Grep
20
+ ---
21
+
22
+ # proj_doc_builder v4.0 — 分阶段生成与确定性发布
23
+
24
+ > **路径约定(必读)**:下文 `<skill-dir>` 指本 `SKILL.md` 所在目录的**绝对路径**——
25
+ > 技能加载结果里的 `Base directory for this skill` 就是它。所有命令都在**项目根**执行,
26
+ > 因此脚本一律写成 `<skill-dir>/tools/xxx.py`;路径含空格时必须保留示例中的双引号。
27
+ > 技能以 DSH bundle 安装时 `<skill-dir>` 在 profile 的包目录内,以项目技能安装时它是
28
+ > `<项目根>/.dsh/skills/` 下的同名目录——两种布局下本文命令都成立。
29
+
30
+ 本 skill 分为两类工作:
31
+
32
+ 1. **模型生成/更新文档正文**:只处理 scanner 选出的新增或变化源码目录。
33
+ 2. **工具确定性收尾**:`sync_project_docs.py` 负责 staging、严格校验、manifest v2、CLAUDE 文档树、Phase 4 报告和 scan state 发布。
34
+
35
+ 协调器不生成自然语言正文。不得跳过文档更新而直接提交 scan baseline。
36
+
37
+ ## 强制安全约束
38
+
39
+ - 默认先 dry-run;只有所有闸门通过后才运行 coordinator `--apply`。
40
+ - Phase 4 默认只报告。不得自动删除文档,不得自动添加 archive 标注,不得把旧 `--auto-approve` 当作授权。
41
+ - quarantine 是独立的显式动作;一次普通 `/proj-doc-builder` 不自动执行它。
42
+ - pending Phase 4 journal 必须先通过显式 `--recover` 处理;report、apply、restore 和 coordinator 都不得绕过恢复闸门。
43
+ - 活动 Markdown 集合只排除根级 `project_docs/.quarantine(运行时生成,可能不存在)/`;`.lingma/` 和嵌套同名目录仍属于活动树。
44
+ - 所有文本严格 UTF-8;Python 文件首行必须是 `# -*- coding: utf-8 -*-`。
45
+ - manifest path 仅允许相对 POSIX 小写 `.md` 路径;禁止绝对路径、反斜杠、`..`、ADS、保留设备名和大小写冲突。
46
+ - 不跟随 symlink、junction 或 reparse point;路径身份不能证明时 fail closed。
47
+ - 不自动批量重写未变化历史文档的自然语言内容。
48
+ - 根 `CLAUDE.md` 只更新 `doc-tree-instruction` 自动区块;其余架构、命令、测试等复杂区块只校验 marker,不自动改写。
49
+ - 不执行版本控制提交(`svn commit` / `git commit`),也不创建版本控制元数据目录(如 `.git`)。
50
+
51
+ ## 工具职责
52
+
53
+ | 工具 | 职责 |
54
+ |---|---|
55
+ | `<skill-dir>/tools/project_docs_contract.py` | 路径、UTF-8、严格 JSON、链接、manifest、锁和原子写的唯一契约 |
56
+ | `<skill-dir>/tools/scan_dirs.py` | 内容哈希目录快照;生成 candidate,不提前推进 committed baseline |
57
+ | `<skill-dir>/tools/compute_link.py` | 计算或验证单个/批量相对文档链接 |
58
+ | `<skill-dir>/tools/validate_doc.py` | standard / placeholder profile 文档质量检查,只报告不修改 |
59
+ | `<skill-dir>/tools/link_check.py` | 全库只读链接检查;**不生成 manifest** |
60
+ | `<skill-dir>/tools/normalize_markers.py` | 仅规范化可精确识别的历史损坏 marker |
61
+ | `<skill-dir>/tools/claude_doc_index.py` | 只从候选 manifest 生成 `doc-tree-instruction` |
62
+ | `<skill-dir>/tools/phase4_exit.py` | fail-closed 报告、显式 quarantine、receipt restore 和持久 journal recovery;不删除活动文档 |
63
+ | `<skill-dir>/tools/sync_project_docs.py` | staging、闸门、统一根锁、发布与回滚的唯一协调器 |
64
+ | `<skill-dir>/tools/load_docs.py` | 加载器(只读):先校验 manifest 与文档完全一致,再输出工程概览或单份文档/单节——给新对话一个入口 |
65
+
66
+ 详细规则见 `references/`。
67
+
68
+ ## Phase 0:环境与输入预检
69
+
70
+ 在项目根执行 Python 工具,并先强制 UTF-8:
71
+
72
+ ```powershell
73
+ $env:PYTHONIOENCODING='utf-8'
74
+ ```
75
+
76
+ 确认:
77
+
78
+ - `project_docs/` 是项目根下的真实目录;
79
+ - 根 `CLAUDE.md` 是真实普通文件;
80
+ - 没有正在进行的其他 sync/quarantine/restore,也没有待恢复的固定 `prepared`/`ready` Phase 4 journal、legacy journal、publication temp、detached artifact 或 coordinator publish journal;
81
+ - 不读取或执行项目自有的计划/反馈目录(若存在);文档读取方在运行时严格只读,不回写业务文件。
82
+
83
+ ## Phase 1:首次 coordinator dry-run
84
+
85
+ ```powershell
86
+ python "<skill-dir>/tools/sync_project_docs.py" . --dry-run --json
87
+ ```
88
+
89
+ 退出码:
90
+
91
+ | 退出码 | 含义 |
92
+ |---:|---|
93
+ | 0 | 所有闸门通过,可发布或已无变化 |
94
+ | 1 | 文档质量、链接或 Phase 4 闸门失败 |
95
+ | 2 | 输入、schema、路径、UTF-8、锁或运行错误 |
96
+ | 3 | 发布失败;查看 `publish` 的 commit/rollback 状态 |
97
+
98
+ 从 JSON 读取:
99
+
100
+ - `scan.changes`:`new/modified/deleted/unchanged/unknown`;
101
+ - `scan.worklist.directories`:本轮需生成或复核的源码目录;
102
+ - `scan.worklist.scaffold`:包含推荐 Profile(standard/placeholder)、直接文件清单与预计算相对链接的结构化脚手架;
103
+ - `scan.candidate_generation_id`:candidate 绑定;
104
+ - `validation.blocking_failures`:变化文档的阻断错误;
105
+ - `validation.audit_failures`:未变化历史文档的非阻断审计;
106
+ - `links.broken`;
107
+ - `phase4` 分类;
108
+ - `planned_writes`。
109
+
110
+ scanner 使用直接普通文件 SHA-256;相同 size/mtime 的内容变化也会进入 `modified`。boundary 后代和其他 unknown scope 不得被当成删除依据。
111
+
112
+ ## Phase 2:生成或更新变化文档
113
+
114
+ 只处理 `scan.worklist.directories` 中的 `new` / `modified` 目录。优先参考 `scan.worklist.scaffold` 中预计算的 `recommended_profile` 与 `precomputed_links`(包含 parent/children/tests 的相对链接),降低多轮外部工具调用。目录到文档的映射为:
115
+
116
+ ```text
117
+ 源码目录: <root>/a/b/
118
+ 文档路径: <root>/project_docs/a/b.md
119
+ ```
120
+
121
+ ### 2.1 读取与分析
122
+
123
+ - 读取真实直接文件和直接子目录;
124
+ - 提取实际类、函数、常量和依赖;
125
+ - boundary 目录只写本层概要,不递归其后代;
126
+ - 二进制文件只记录文件名、类型和用途,不伪造符号。
127
+
128
+ ### 2.2 选择 profile
129
+
130
+ - **standard**:有实质源码、标准材料或有效子模块;概述 3–4 个实质句子,文件/子目录清单必须与磁盘一致。
131
+ - **placeholder**:空目录或只有无实质内容的初始化文件;允许 1–2 句概述,不要求虚构符号、依赖或长篇系统角色。
132
+
133
+ 模板见 `references/templates.md`,校验规则见 `references/checklist.md`。
134
+
135
+ ### 2.3 链接
136
+
137
+ 不得手工计算 `../`:
138
+
139
+ ```powershell
140
+ python "<skill-dir>/tools/compute_link.py" `
141
+ --project-docs project_docs `
142
+ --from <当前文档相对路径> `
143
+ --to <目标文档相对路径>
144
+ ```
145
+
146
+ 共享 resolver 支持 inline、reference-style、HTML anchor、fragment、query、extensionless `.md` 和严格 URL decode。详情见 `references/linking.md`。
147
+
148
+ ### 2.4 单文档校验
149
+
150
+ ```powershell
151
+ python "<skill-dir>/tools/validate_doc.py" `
152
+ <doc.md> --source-dir <source_dir> --strict --json
153
+ ```
154
+
155
+ 本轮变化文档的任何 FAIL 必须修复。未变化历史文档只审计和报告,不为通过校验而机械改写。
156
+
157
+ ### 2.5 删除和 unknown
158
+
159
+ - `deleted` 只进入 Phase 4 分析;不得直接删除对应文档。
160
+ - `unknown`、boundary 后代和不可信路径不得生成"源码已消失"结论。
161
+ - 未注册文档、manifest 缺失项或大小写漂移必须由 coordinator/contract 精确报告。
162
+
163
+ ### 2.6 全量文件清单审计(`--full` 模式强制步骤)
164
+
165
+ > **教训**:扫描器标记 `unchanged` 只意味着目录指纹(文件集合哈希)未变,**不代表文档内容与磁盘一致**。源码在两次同步之间新增文件后,基线指纹已包含新文件,增量扫描判 unchanged → 文档永远不会被触发重写 → 文件清单永久漏失。
166
+
167
+ 在 `--full` 模式下,**不论扫描器分类如何**,必须对全部已有文档运行文件清单审计:
168
+
169
+ 1. 对每个 `project_docs/*.md`(排除 `_*` 和 `index.md`):
170
+ - 从文档的 `## 文件清单` 表格提取已记录的文件名集合
171
+ - 从对应源码目录提取磁盘直接文件集合
172
+ - 比对差异:磁盘有但文档缺 = **漏文件**;文档有但磁盘无 = **幽灵条目**
173
+ 2. 漏文件:按 2.1-2.4 流程提取关键信息并补入表格
174
+ 3. 幽灵条目:从表格删除该行;如果源码目录已空且文档之前是 standard,降级为 placeholder
175
+ 4. 同时检查概述中的文件计数是否与实际一致
176
+
177
+ 审计脚本可参考 `references/audit_script.md` 中的 Python 模板。
178
+
179
+ ## Phase 3:全局 dry-run 闭环
180
+
181
+ 更新正文后反复运行:
182
+
183
+ ```powershell
184
+ python "<skill-dir>/tools/sync_project_docs.py" . --dry-run --json
185
+ ```
186
+
187
+ 必须同时满足:
188
+
189
+ - `ok == true`;
190
+ - 变化文档 strict 校验 0 阻断;
191
+ - `links.broken_count == 0`;
192
+ - manifest v2 candidate 覆盖完整活动 Markdown 集合;
193
+ - CLAUDE 六组 marker 唯一、成对、不交叠;
194
+ - Phase 4 无安全错误;存在 quarantine candidate 时发布照常进行但 scan baseline 冻结(见 Phase 4);
195
+ - source snapshot 在 staging 与发布前复核中保持一致;
196
+ - **`--full` 模式额外要求**:全部 366+ 份文档的文件清单与磁盘逐项核对一致(Phase 2.6 审计结果为 0 漏文件 / 0 幽灵条目)。
197
+
198
+ `link_check.py` 仅做只读链接校验:
199
+
200
+ ```powershell
201
+ python "<skill-dir>/tools/link_check.py" --project-docs project_docs --json
202
+ ```
203
+
204
+ 不得把它描述为 manifest 生成器。
205
+
206
+ ## Phase 4:report-first 退出机制
207
+
208
+ 普通同步只读取 coordinator 内嵌的 Phase 4 report。也可独立运行:
209
+
210
+ ```powershell
211
+ python "<skill-dir>/tools/phase4_exit.py" . --json
212
+ ```
213
+
214
+ 只有同时满足以下条件才可成为 quarantine candidate:
215
+
216
+ - 已在受验证 manifest 注册;
217
+ - 含精确 AUTO marker;
218
+ - 对应源码目录确认不存在;
219
+ - 使用共享 resolver 统计为零入站引用;
220
+ - 不位于 boundary/unknown scope;
221
+ - 路径、UTF-8、hash 和 generation 均可信。
222
+
223
+ “概述短”“内容为空”或“占位”不是处置理由。有引用的历史文档仅报告,工具不自动 archive。
224
+
225
+ 若 report 存在 candidate,普通 sync 可继续发布文档、marker 修复、CLAUDE 文档树和 manifest,但不推进 scan baseline(警告 `scan-baseline-frozen`)。这一设计使解除入站引用的文档编辑得以发布,避免 coordinator 闸门与 Phase 4 manifest 一致性校验相互死锁。只有用户另行明确要求 quarantine 时才运行:
226
+
227
+ ```powershell
228
+ python "<skill-dir>/tools/phase4_exit.py" . --apply --json
229
+ ```
230
+
231
+ 恢复 receipt:
232
+
233
+ ```powershell
234
+ python "<skill-dir>/tools/phase4_exit.py" . --restore <RECEIPT_ID> --json
235
+ ```
236
+
237
+ quarantine/restore 在第一次内容变更前排他发布不可变的 `.phase4-transaction.json` prepared journal;后镜像准备完成后再以 no-replace 方式发布不可变的 `.phase4-transaction-ready.json` companion,绝不原地覆盖 prepared。manifest 通过 before/after anchor 执行 no-replace CAS,是唯一 commit point。restore 使用独立 transaction anchor 发布目标,原 quarantine payload 不与目标共享 inode。若进程被强制终止,或 journal/artifact 清理失败,所有普通动作和 coordinator 都会返回 `phase4-recovery-required`。此时必须先运行:
238
+
239
+ ```powershell
240
+ python "<skill-dir>/tools/phase4_exit.py" . --recover --json
241
+ ```
242
+
243
+ 恢复只接受 journal 记录的精确 before/after 状态:manifest、活动文档、target/source、receipt、payload 或 CLAUDE 出现人工/并发变化时保留现场并 fail closed。无 pending journal 的 `--recover` 是成功 no-op。
244
+
245
+ 详情见 `references/phase4.md`。
246
+
247
+ ## Phase 5:确定性发布
248
+
249
+ 所有闸门通过后:
250
+
251
+ ```powershell
252
+ python "<skill-dir>/tools/sync_project_docs.py" . --apply --json
253
+ ```
254
+
255
+ 固定事务语义:
256
+
257
+ 1. coordinator 在 staging 前、staging 后和发布锁内检查 pending Phase 4 journal;存在或无法验证时不推进任何基线。
258
+ 2. 所有候选先在系统临时目录中完成校验;dry-run 不在项目树创建 staging、缓存或其他路径。
259
+ 3. 发布时获取项目统一根锁并重新核对文档、CLAUDE、manifest、scan state 和源码 snapshot。
260
+ 4. 在系统临时目录的项目锁域旁排他发布持久 coordinator publish journal;该 journal 不污染版本控制工作副本。
261
+ 5. 先发布精确 marker 修复和 CLAUDE 文档树。
262
+ 6. manifest 最后作为文档代际 commit point。
263
+ 7. scan state 最后提交;失败时依据 manifest/scan/artifact 的实际安装状态报告 `NOT_INSTALLED`、`UNKNOWN` 或 `PARTIALLY_INSTALLED`,不虚构已提交状态。
264
+ 8. manifest 前失败只回滚本事务仍拥有的候选内容;检测到并发修改时不覆盖并报告 rollback conflict。
265
+
266
+ 若返回 `coordinator-recovery-required`,必须运行协调器自己的恢复入口:
267
+
268
+ ```powershell
269
+ python "<skill-dir>/tools/sync_project_docs.py" . --recover --json
270
+ ```
271
+
272
+ 它与 `phase4_exit.py --recover` 是两个独立状态机:前者恢复普通 sync 发布,后者恢复 quarantine/restore。无 pending coordinator journal 时,`--recover` 是成功 no-op。
273
+
274
+ manifest schema v2 包含 `generation_id`、producer、docs root、total、depth counts、last synced,以及每份文档的 path/depth/title/status/bytes/SHA-256/synced_at。v1 仅内存兼容;未知 schema 直接拒绝。
275
+
276
+ ## Phase 6:终验与幂等
277
+
278
+ 发布后再次运行同一 dry-run:
279
+
280
+ ```powershell
281
+ python "<skill-dir>/tools/sync_project_docs.py" . --dry-run --json
282
+ ```
283
+
284
+ 预期:
285
+
286
+ - `planned_writes == []`;
287
+ - manifest `changed == false`;
288
+ - scan `commit_needed == false`;
289
+ - 0 断链;
290
+ - 无未解释的缺失、未注册、候选或 unknown 错误;
291
+ - **`--full` 模式额外要求**:重新运行全量文件清单审计脚本,确认全部文档与磁盘一致(与 Phase 2.6 使用同一脚本)。
292
+
293
+ 零变化运行不得刷新 `last_synced`、manifest、CLAUDE 或 scan state。
294
+
295
+ 最后只读执行版本控制范围检查;不提交(Git 与 SVN 各有等价命令):
296
+
297
+ ```powershell
298
+ git status
299
+ git diff
300
+ # SVN 仓库:svn status / svn diff
301
+ ```
302
+
303
+ 确认没有个人绝对路径、版本控制元数据文件、非预期自然语言重写或 quarantine 动作。
304
+
305
+ ## 完成报告
306
+
307
+ 报告至少包含:
308
+
309
+ - scanner 分类和处理目录数;
310
+ - 新建/更新文档路径;
311
+ - **文件清单审计结果**:审计的文档总数、漏文件修复数、幽灵条目清除数、空目录文档降级数;
312
+ - strict 与历史审计结果;
313
+ - marker 精确修复数;
314
+ - manifest schema/generation/total/depth counts;
315
+ - CLAUDE 文档树是否变化;
316
+ - 链接数量与断链数;
317
+ - Phase 4 candidates/blocked/missing/unregistered,以及 pending/recovered journal 状态;
318
+ - publish commit point、scan state 和 rollback/partial 状态;
319
+ - 第二次 dry-run 是否完全无变化;
320
+ - 版本控制 status/diff 范围;
321
+ - 明确说明未执行版本控制提交、未自动删除或 quarantine 文档。
322
+
323
+ ## 文档定位与漂移纪律
324
+
325
+ ## 定位
326
+ `project_docs/` 是**自动生成的目录镜像索引**,由本技能生成与校验
327
+ (工具在本技能自带的 `tools/` 子目录里,**不在项目根的 `tools/`**)。
328
+
329
+ ## 权威顺序(冲突时按此采信)
330
+ 1. **实测运行输出**(报告 / 日志 / 器件回读)
331
+ 2. **标准原文**(你的标准与规范文档目录)
332
+ 3. **源码**(被测代码本体)
333
+ 4. **配置数据**(运行时配置、环境参数、设备描述)
334
+ 5. `project_docs/`(索引)
335
+ 6. `CLAUDE.md`(总览,可能滞后)
336
+ 7. 技能文档(方法论,不替代 1–4)
337
+
338
+ ## 漂移纪律
339
+ * 发现文档与实测不符:**先取证,再改文档,并在台账留痕**
340
+ * 不要"顺手改文档让它看起来对";不要把历史计划文档改写成事后正确
341
+ * 已知漂移应显式列出(例如:标称值 vs 实测标定值、目录迁移后的旧路径)
342
+
343
+ ## 何时不要动文档
344
+ * 正在跑测试批次(改动会污染归档)
345
+ * 结论尚无法复现(先补证据)
346
+
347
+ ## 收尾自检
348
+ ```bash
349
+ python -m pytest "<skill-dir>/tests" -q # 本技能自带的用例(Windows 上部分用例按平台跳过)
350
+ ```
@@ -0,0 +1,96 @@
1
+ # 全量文件清单审计脚本参考
2
+
3
+ > Phase 2.6 / Phase 6 使用的审计脚本模板。Agent 可基于此编写 Python 脚本,也可自行实现等效逻辑。
4
+
5
+ ## 脚本功能
6
+
7
+ 对 `project_docs/` 下的每个 `.md` 文件(排除 `_*` 和 `index.md`):
8
+
9
+ 1. 从 `## 文件清单` 表格提取已记录的文件名集合(`| \`filename\` |` 模式)
10
+ 2. 从对应源码目录提取磁盘直接文件集合
11
+ 3. 比对差异并报告
12
+
13
+ ## Python 模板
14
+
15
+ ```python
16
+ # -*- coding: utf-8 -*-
17
+ """全量文档文件清单一致性审计"""
18
+ import re
19
+ from pathlib import Path
20
+
21
+ def audit(project_root: str):
22
+ root = Path(project_root)
23
+ pd = root / 'project_docs'
24
+
25
+ issues = []
26
+
27
+ for md in pd.rglob('*.md'):
28
+ # 跳过内部文件和索引
29
+ if md.name.startswith('_') or md.name == 'index.md':
30
+ continue
31
+
32
+ # 计算对应源码目录路径
33
+ rel = md.relative_to(pd)
34
+ src_dir = root / rel.parent / rel.stem.replace('.md', '')
35
+
36
+ if not src_dir.exists() or not src_dir.is_dir():
37
+ continue
38
+
39
+ # 磁盘文件
40
+ disk_files = sorted([
41
+ f.name for f in src_dir.iterdir()
42
+ if f.is_file() and not f.name.startswith('.')
43
+ ])
44
+ disk_set = set(disk_files)
45
+
46
+ # 文档表格中的文件名
47
+ content = md.read_text(encoding='utf-8')
48
+ file_section = re.search(
49
+ r'## 文件清单\s*\n(.*?)(?=\n## |\Z)', content, re.S
50
+ )
51
+ if file_section:
52
+ doc_files = set(
53
+ re.findall(r'^\| `([^`]+)`', file_section.group(1), re.M)
54
+ )
55
+ else:
56
+ doc_files = set()
57
+
58
+ missing = disk_set - doc_files
59
+ extra = doc_files - disk_set
60
+
61
+ if missing or extra:
62
+ rel_str = str(rel).replace('\\', '/')
63
+ issues.append({
64
+ 'doc': rel_str,
65
+ 'disk_count': len(disk_files),
66
+ 'doc_count': len(doc_files),
67
+ 'missing': sorted(missing),
68
+ 'extra': sorted(extra),
69
+ })
70
+
71
+ return issues
72
+
73
+
74
+ if __name__ == '__main__':
75
+ import sys
76
+ root = sys.argv[1] if len(sys.argv) > 1 else '.'
77
+ issues = audit(root)
78
+
79
+ if not issues:
80
+ print('所有文档文件清单与磁盘一致 ✅')
81
+ else:
82
+ print(f'发现 {len(issues)} 个文档有问题:')
83
+ for i in issues:
84
+ print(f" {i['doc']}: 磁盘 {i['disk_count']} / 文档 {i['doc_count']}")
85
+ if i['missing']:
86
+ print(f" 缺失: {i['missing']}")
87
+ if i['extra']:
88
+ print(f" 多余: {i['extra']}")
89
+ ```
90
+
91
+ ## 使用方式
92
+
93
+ ```powershell
94
+ $env:PYTHONIOENCODING='utf-8'
95
+ python audit_doc_files.py "C:\path\to\project_root"
96
+ ```