@modusensus/dsh-mneme 0.10.0 → 0.11.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 (79) hide show
  1. package/README.md +11 -3
  2. package/bin/dsh-mneme-choro.mjs +254 -0
  3. package/docs/CONFIGURATION.md +8 -1
  4. package/lib/api-standalone.js +17 -21
  5. package/lib/api.js +298 -12
  6. package/lib/bootstrap-http.js +105 -0
  7. package/lib/bootstrap.js +5 -1
  8. package/lib/choro-command.js +104 -0
  9. package/lib/client.js +1153 -106
  10. package/lib/config-keys.js +144 -0
  11. package/lib/config.js +28 -0
  12. package/lib/graph/anchoring.js +7 -2
  13. package/lib/index.js +50 -4
  14. package/lib/inject.js +15 -3
  15. package/lib/lang.js +54 -0
  16. package/lib/quality-filter.js +48 -12
  17. package/lib/service.js +72 -8
  18. package/lib/settings.js +8 -1
  19. package/lib/store.js +657 -0
  20. package/lib/tools.js +127 -1
  21. package/lib/wiki/inject.js +164 -0
  22. package/lib/wiki/partition.js +200 -0
  23. package/lib/wiki/plan.js +214 -0
  24. package/lib/wiki/queries.js +220 -0
  25. package/lib/wiki/render.js +187 -0
  26. package/lib/wiki/scan.js +371 -0
  27. package/lib/wiki/t0.js +463 -0
  28. package/lib/wiki/t1.js +496 -0
  29. package/lib/write-admission.js +5 -3
  30. package/package.json +4 -2
  31. package/src/api-standalone.js +17 -21
  32. package/src/api.js +298 -12
  33. package/src/bootstrap-http.js +105 -0
  34. package/src/bootstrap.js +5 -1
  35. package/src/choro-command.js +104 -0
  36. package/src/config-keys.js +144 -0
  37. package/src/config.js +28 -0
  38. package/src/graph/anchoring.js +7 -2
  39. package/src/index.js +50 -4
  40. package/src/inject.js +15 -3
  41. package/src/lang.js +54 -0
  42. package/src/quality-filter.js +48 -12
  43. package/src/service.js +72 -8
  44. package/src/settings.js +8 -1
  45. package/src/store.js +657 -0
  46. package/src/tools.js +127 -1
  47. package/src/wiki/inject.js +164 -0
  48. package/src/wiki/partition.js +200 -0
  49. package/src/wiki/plan.js +214 -0
  50. package/src/wiki/queries.js +220 -0
  51. package/src/wiki/render.js +187 -0
  52. package/src/wiki/scan.js +371 -0
  53. package/src/wiki/t0.js +463 -0
  54. package/src/wiki/t1.js +496 -0
  55. package/src/write-admission.js +5 -3
  56. package/test/api-routes-gaps.test.js +131 -1
  57. package/test/api.test.js +7 -1
  58. package/test/bootstrap.test.js +8 -0
  59. package/test/choro-command.test.js +218 -0
  60. package/test/client.test.js +820 -19
  61. package/test/config-keys-routes.test.js +233 -0
  62. package/test/contrast.test.js +14 -7
  63. package/test/graph-boosted-relations.test.js +189 -0
  64. package/test/graph-multipath.test.js +269 -0
  65. package/test/inject.test.js +51 -0
  66. package/test/llm-audit.test.js +29 -1
  67. package/test/quality-backfill.test.js +290 -0
  68. package/test/quality-filter.test.js +113 -4
  69. package/test/service.test.js +1 -1
  70. package/test/wiki-api.test.js +153 -0
  71. package/test/wiki-inject.test.js +265 -0
  72. package/test/wiki-partition.test.js +112 -0
  73. package/test/wiki-plan.test.js +80 -0
  74. package/test/wiki-queries.test.js +187 -0
  75. package/test/wiki-scan.test.js +208 -0
  76. package/test/wiki-store.test.js +190 -0
  77. package/test/wiki-t0.test.js +380 -0
  78. package/test/wiki-t1.test.js +235 -0
  79. package/test/wiki-tools.test.js +121 -0
package/lib/wiki/t0.js ADDED
@@ -0,0 +1,463 @@
1
+ // dsh-mneme/src/wiki/t0.js
2
+ // T0 编排(spec §6 步 1–8):读 plan → 列文件 → 解析 import 图 → 划分模块 →
3
+ // 渲染骨架 → dry-run 报告或 apply 写盘 + 落库 + state.json 收尾。
4
+ //
5
+ // 全程零模型、零网络、可离线(spec:T0「秒级、可离线、必有产出」)。所有磁盘写入
6
+ // 被限定在 `<repo>/.chorography/` 之内(红线 1 的机械面:写路径断言 + 不碰
7
+ // .github/.gitignore/AGENTS.md,契约测试对整个仓库做树快照比对)。
8
+ //
9
+ // 失败语义(红线 5):中途任何一步失败,state.json 不写(保持上一次成功 run 的
10
+ // 内容),库侧 replaceChoroGraph 是单事务——半截失败整体回滚到上一次成功 run。
11
+ // 重跑幂等:同样的输入得到同样的划分、同样的页面字节、同样的行数。
12
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, realpathSync, readdirSync } from "node:fs";
13
+ import { join, posix, sep, resolve } from "node:path";
14
+ import { execFileSync } from "node:child_process";
15
+ import { loadPlanFromRepo } from "./plan.js";
16
+ import {
17
+ listFiles, parseImportGraph, repoFingerprint, countLines,
18
+ readRootPackage, workspacePrefixes, compileInclude,
19
+ } from "./scan.js";
20
+ import { partitionModules } from "./partition.js";
21
+ import {
22
+ renderSkeletonPage, renderIndex, extractHumanBlocks, injectHumanBlocks,
23
+ TEMPLATE_VERSION, T1_SECTION_START,
24
+ } from "./render.js";
25
+
26
+ export const CHORO_DIR = ".chorography";
27
+
28
+ /** 拒绝类:CLI 据此透出人话并 exit 1(不写任何东西就退)。 */
29
+ export class ChoroRefusal extends Error {
30
+ constructor(code, message) {
31
+ super(message);
32
+ this.name = "ChoroRefusal";
33
+ this.code = code;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * @param {object} opts
39
+ * @param {string} opts.repoRoot 仓库路径(内部 realpath)
40
+ * @param {object|null} opts.store createStore 产物(apply 时必传;dry-run 可为 null)
41
+ * @param {boolean} [opts.apply=false] false = dry-run(零写入)
42
+ * @param {() => string} [opts.now] ISO 时刻(测试注入假时钟)
43
+ */
44
+ export function runChoroT0({ repoRoot, store = null, apply = false, now = () => new Date().toISOString() }) {
45
+ let rootPath;
46
+ try {
47
+ rootPath = realpathSync(resolve(repoRoot));
48
+ } catch (err) {
49
+ throw new ChoroRefusal("no-such-dir", `仓库路径不存在或不可达:${repoRoot}(${String(err?.message ?? err)})`);
50
+ }
51
+ if (!statDir(rootPath)) {
52
+ throw new ChoroRefusal("no-such-dir", `仓库路径不是目录:${rootPath}`);
53
+ }
54
+
55
+ // git 基线(spec 降级表第一行:不是 git 仓库 → 拒绝并说明原因,锚点无法核验)。
56
+ const gitBaseline = gitHead(rootPath);
57
+ if (!gitBaseline) {
58
+ throw new ChoroRefusal(
59
+ "not-git",
60
+ `${rootPath} 不是 git 仓库(git rev-parse HEAD 失败)。chorography 的每条出处锚点都要能对着提交核验,非 git 目录拒绝生成。`
61
+ );
62
+ }
63
+
64
+ // plan.yaml(用户所有,机器只读):有 → 严格校验(未知键整轮拒绝);无 → 默认启发式。
65
+ const loaded = loadPlanFromRepo(rootPath);
66
+ const plan = loaded.plan;
67
+
68
+ // 扫描(spec 步 2–3)。include 白名单非空时文件还须命中任意一条。
69
+ const includeMatcher = compileInclude(plan.include ?? []);
70
+ let files = listFiles(rootPath, { exclude: plan.exclude ?? [] });
71
+ if ((plan.include ?? []).length > 0) files = files.filter((f) => includeMatcher.matchesFile(f));
72
+ const graph = parseImportGraph(rootPath, files);
73
+
74
+ // 划分(spec 步 4)。workspace 前缀目前只作登记,不参与合并启发式(v1 保守)。
75
+ const pkg = readRootPackage(rootPath);
76
+ workspacePrefixes(pkg?.workspaces ?? []);
77
+ const repoName = pkg?.name ?? rootPath.split(/[\\/]/).pop() ?? "repo";
78
+ const modules = partitionModules({ files, graph, maxFilesPerPage: plan.maxFilesPerPage, repoName });
79
+
80
+ // 模块级依赖边(M1 补口 P8):文件级边按所属模块聚合,只留跨模块方向;排序
81
+ // 进快照,库里的边集与页面字节一样可重建。
82
+ const slugByFile = new Map();
83
+ for (const mod of modules) {
84
+ for (const f of mod.files) slugByFile.set(f, mod.slug);
85
+ }
86
+ const edgeAgg = new Map();
87
+ for (const e of graph.edges) {
88
+ const from = slugByFile.get(e.from);
89
+ const to = slugByFile.get(e.to);
90
+ if (!from || !to || from === to) continue;
91
+ const key = `${from}|${to}`;
92
+ edgeAgg.set(key, (edgeAgg.get(key) ?? 0) + 1);
93
+ }
94
+ const moduleEdges = [...edgeAgg.entries()]
95
+ .map(([key, weight]) => {
96
+ const [fromSlug, toSlug] = key.split("|");
97
+ return { fromSlug, toSlug, weight };
98
+ })
99
+ .sort((a, b) =>
100
+ a.fromSlug < b.fromSlug ? -1 : a.fromSlug > b.fromSlug ? 1 : a.toSlug < b.toSlug ? -1 : 1
101
+ );
102
+
103
+ // 页面白名单(D7 正面控制):plan.pages 非空时只给列出的 slug 建页。
104
+ const whitelist = plan.pages && plan.pages.length > 0 ? new Map(plan.pages.map((p) => [p.path, p])) : null;
105
+ const warnings = [];
106
+ if (whitelist) {
107
+ for (const [path] of whitelist) {
108
+ if (!modules.some((m) => m.slug === path)) {
109
+ warnings.push(`plan.yaml pages 里的 "${path}" 没有对应的模块划分结果(划分会随代码漂移,这不是错误,只提示)。`);
110
+ }
111
+ }
112
+ }
113
+
114
+ // state.json:沿用上次成功 run 的 generatedAt(实现计划 P3)——只有当
115
+ // plan 与仓库状态都没变时沿用,页面字节才逐字稳定(spec §9 可重建不变量)。
116
+ const fingerprint = repoFingerprint(files, graph.edges);
117
+ const prevState = readState(rootPath);
118
+ const stateStable =
119
+ prevState !== null &&
120
+ prevState.planFingerprint === loaded.fingerprint &&
121
+ prevState.repoFingerprint === fingerprint;
122
+ const generatedAt = stateStable && prevState.generatedAt ? prevState.generatedAt : now();
123
+
124
+ const unresolvedTotal = graph.unresolved.length;
125
+
126
+ // 页面组装(spec 步 6)。
127
+ const pageTargets = [];
128
+ for (const mod of modules) {
129
+ if (whitelist && !whitelist.has(mod.slug)) continue;
130
+ const entry = assembleModuleView(mod, modules, graph, rootPath);
131
+ const custom = whitelist?.get(mod.slug);
132
+ let content = renderSkeletonPage(entry, {
133
+ slug: mod.slug,
134
+ title: custom?.title ?? mod.title,
135
+ parents: parentChain(mod, modules),
136
+ sourceFiles: mod.files,
137
+ gitBaseline,
138
+ generatedAt,
139
+ status: "skeleton",
140
+ language: "zh",
141
+ });
142
+ const extra = renderPlanExtras(custom, plan, warnings);
143
+ if (extra) content = `${content.replace(/\n*$/, "\n")}\n${extra}`;
144
+ pageTargets.push({ moduleSlug: mod.slug, relPath: `${CHORO_DIR}/modules/${mod.slug}.md`, content });
145
+ }
146
+
147
+ const indexRelPath = `${CHORO_DIR}/index.md`;
148
+ // index 是「页面目录」:白名单挡掉的模块没有页,目录里也不列(列出会指向不存在的文件)。
149
+ const indexedModules = modules.filter((m) => !whitelist || whitelist.has(m.slug));
150
+ const indexContent = renderIndex(
151
+ indexedModules.map((m) => ({
152
+ ...m,
153
+ fileLines: [],
154
+ })),
155
+ {
156
+ name: repoName,
157
+ gitBaseline,
158
+ generatedAt,
159
+ fileCount: files.length,
160
+ skipped: graph.skipped.length,
161
+ unresolved: unresolvedTotal,
162
+ scripts: pkg?.scripts ?? {},
163
+ }
164
+ );
165
+
166
+ // T0 重跑会把已富化的页退回骨架(P19:富化层不参与字节稳定不变量,重建整页丢弃
167
+ // 重来)。丢弃本身是设计意图,静默不是:不清点的话,人看到的只是「跑完 T0,语义
168
+ // 段落没了」,而 .chorography/evidence/*.json 还会变成没人引用的孤儿。这里只报,
169
+ // 不改字节、不删 evidence——一条只读的清点,dry-run 与 apply 共用。
170
+ const t1Loss = collectT1Loss(rootPath, pageTargets);
171
+ if (t1Loss.pages.length > 0) {
172
+ const names = t1Loss.pages.slice(0, 3).join("、");
173
+ warnings.push(
174
+ `${t1Loss.pages.length} 页含 T1 语义段(${names}${t1Loss.pages.length > 3 ? " 等" : ""}):`
175
+ + `本次会退回骨架、清空 choro_claims`
176
+ + `${t1Loss.orphanEvidence > 0 ? `,${t1Loss.orphanEvidence} 份 evidence 文件会变成孤儿(不删)` : ""}。`
177
+ + "要留住语义段就别在这里重跑 T0;需要时再用 --t1 重新富化。"
178
+ );
179
+ }
180
+
181
+ if (!apply) {
182
+ return {
183
+ dryRun: true,
184
+ repoPath: rootPath,
185
+ repoName,
186
+ gitBaseline,
187
+ planPath: loaded.planPath,
188
+ planFingerprint: loaded.fingerprint,
189
+ repoFingerprint: fingerprint,
190
+ generatedAt,
191
+ reusedGeneratedAt: stateStable,
192
+ fileCount: files.length,
193
+ moduleCount: modules.length,
194
+ pageCount: pageTargets.length,
195
+ skippedByWhitelist: whitelist ? modules.length - pageTargets.length : 0,
196
+ skippedFiles: graph.skipped,
197
+ unresolvedCount: unresolvedTotal,
198
+ humanBlocksSeen: countExistingHumanBlocks(rootPath, pageTargets),
199
+ t1Loss: { pages: t1Loss.pages, orphanEvidence: t1Loss.orphanEvidence },
200
+ wouldWrite: [...pageTargets.map((p) => ({ path: p.relPath, bytes: Buffer.byteLength(p.content, "utf8") })),
201
+ { path: indexRelPath, bytes: Buffer.byteLength(indexContent, "utf8") },
202
+ { path: `${CHORO_DIR}/state.json`, bytes: 0 }],
203
+ warnings,
204
+ moduleSummary: modules.map((m) => ({
205
+ slug: m.slug, title: m.title, fileCount: m.fileCount,
206
+ internalEdges: m.internalEdges.length, externalDeps: m.externalDeps.length,
207
+ })),
208
+ };
209
+ }
210
+
211
+ if (!store) throw new ChoroRefusal("store-required", "apply 模式需要打开的 store(memory.db)。");
212
+
213
+ // apply:写盘 → 落库 → state.json 收尾(红线 5:失败不推进 state)。
214
+ const choroDir = join(rootPath, CHORO_DIR);
215
+ mkdirSync(join(choroDir, "modules"), { recursive: true });
216
+
217
+ let humanBlocksPreserved = 0;
218
+ let bytes = 0;
219
+ for (const target of pageTargets) {
220
+ const abs = assertInsideChoro(rootPath, target.relPath);
221
+ const finalContent = preserveHumanBlocks(abs, target.content);
222
+ if (finalContent.humanBlocks > 0) humanBlocksPreserved += finalContent.humanBlocks;
223
+ writeFileSync(abs, finalContent.content, "utf8");
224
+ bytes += Buffer.byteLength(finalContent.content, "utf8");
225
+ }
226
+ const indexAbs = assertInsideChoro(rootPath, indexRelPath);
227
+ writeFileSync(indexAbs, indexContent, "utf8");
228
+ bytes += Buffer.byteLength(indexContent, "utf8");
229
+
230
+ const repoRow = store.upsertChoroRepo(rootPath, repoName, loaded.fingerprint, gitBaseline, generatedAt);
231
+ store.replaceChoroGraph(repoRow.id, {
232
+ edges: moduleEdges,
233
+ modules: modules.map((m) => ({
234
+ slug: m.slug,
235
+ title: (whitelist?.get(m.slug)?.title) ?? m.title,
236
+ parentSlug: m.parentSlug,
237
+ fileCount: m.fileCount,
238
+ fingerprint: m.fingerprint,
239
+ })),
240
+ pages: pageTargets.map((p) => ({
241
+ moduleSlug: p.moduleSlug,
242
+ relPath: p.relPath,
243
+ status: "skeleton",
244
+ gitBaseline,
245
+ templateVersion: TEMPLATE_VERSION,
246
+ generatedAt,
247
+ humanBlockCount: existingHumanBlockCount(join(rootPath, p.relPath)),
248
+ claims: [],
249
+ })),
250
+ updatedAt: generatedAt,
251
+ });
252
+
253
+ const state = {
254
+ choro: "v1",
255
+ gitBaseline,
256
+ templateVersion: TEMPLATE_VERSION,
257
+ planFingerprint: loaded.fingerprint,
258
+ repoFingerprint: fingerprint,
259
+ generatedAt,
260
+ moduleCount: modules.length,
261
+ pageCount: pageTargets.length,
262
+ fileCount: files.length,
263
+ };
264
+ const stateAbs = assertInsideChoro(rootPath, `${CHORO_DIR}/state.json`);
265
+ writeFileSync(stateAbs, `${JSON.stringify(state, null, 2)}\n`, "utf8");
266
+
267
+ return {
268
+ dryRun: false,
269
+ repoPath: rootPath,
270
+ repoName,
271
+ gitBaseline,
272
+ planPath: loaded.planPath,
273
+ planFingerprint: loaded.fingerprint,
274
+ repoFingerprint: fingerprint,
275
+ generatedAt,
276
+ reusedGeneratedAt: stateStable,
277
+ fileCount: files.length,
278
+ moduleCount: modules.length,
279
+ pageCount: pageTargets.length,
280
+ skippedByWhitelist: whitelist ? modules.length - pageTargets.length : 0,
281
+ skippedFiles: graph.skipped,
282
+ unresolvedCount: unresolvedTotal,
283
+ humanBlocksPreserved,
284
+ bytes,
285
+ t1Loss: { pages: t1Loss.pages, orphanEvidence: t1Loss.orphanEvidence },
286
+ warnings,
287
+ moduleSummary: modules.map((m) => ({
288
+ slug: m.slug, title: m.title, fileCount: m.fileCount,
289
+ internalEdges: m.internalEdges.length, externalDeps: m.externalDeps.length,
290
+ })),
291
+ };
292
+ }
293
+
294
+ /* ------------------------------ 内部件 ------------------------------ */
295
+
296
+ function statDir(path) {
297
+ try {
298
+ return statSync(path).isDirectory();
299
+ } catch {
300
+ return false;
301
+ }
302
+ }
303
+
304
+ export function gitHead(repoRoot) {
305
+ try {
306
+ const out = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" });
307
+ return out.trim() || null;
308
+ } catch {
309
+ return null;
310
+ }
311
+ }
312
+
313
+ function readState(repoRoot) {
314
+ try {
315
+ const raw = readFileSync(join(repoRoot, CHORO_DIR, "state.json"), "utf8");
316
+ const parsed = JSON.parse(raw);
317
+ return parsed && typeof parsed === "object" ? parsed : null;
318
+ } catch {
319
+ return null;
320
+ }
321
+ }
322
+
323
+ // 组装渲染视图:行数、入口、模块级上/下游、逐模块 unresolved 计数。
324
+ function assembleModuleView(mod, modules, graph, rootPath) {
325
+ const fileSet = new Set(mod.files);
326
+ const fileLines = mod.files.map((f) => [f, countLines(rootPath, f)]);
327
+ const entries = mod.files.filter((f) => /^(index|main)\.(js|mjs|cjs|ts|tsx|jsx|vue)$/.test(posix.basename(f)));
328
+ const slugByFile = new Map();
329
+ for (const other of modules) {
330
+ for (const f of other.files) slugByFile.set(f, other.slug);
331
+ }
332
+ const upstream = new Set();
333
+ const downstream = new Set();
334
+ // 跨模块方向查全图:本模块文件引用别的模块 → upstream(本模块的依赖);
335
+ // 别的模块引用本模块文件 → downstream(谁依赖它)。模块内部边不计方向。
336
+ for (const e of graph.edges) {
337
+ if (slugByFile.get(e.from) === mod.slug && slugByFile.get(e.to) !== mod.slug) upstream.add(slugByFile.get(e.to));
338
+ if (slugByFile.get(e.from) !== mod.slug && slugByFile.get(e.to) === mod.slug) downstream.add(slugByFile.get(e.from));
339
+ }
340
+ const unresolvedCount = graph.unresolved.filter((u) => fileSet.has(u.from)).length;
341
+ return {
342
+ ...mod,
343
+ fileLines,
344
+ entries: entries.sort(),
345
+ upstream: [...upstream].filter((s) => s && s !== mod.slug).sort(),
346
+ downstream: [...downstream].filter((s) => s && s !== mod.slug).sort(),
347
+ unresolvedCount,
348
+ };
349
+ }
350
+
351
+ function parentChain(mod, modules) {
352
+ const chain = [];
353
+ let current = mod;
354
+ const bySlug = new Map(modules.map((m) => [m.slug, m]));
355
+ while (current?.parentSlug) {
356
+ const parent = bySlug.get(current.parentSlug);
357
+ if (!parent) break;
358
+ chain.push(parent.slug);
359
+ current = parent;
360
+ }
361
+ return chain.reverse();
362
+ }
363
+
364
+ // plan.pages 的 template / notes 的 M0 确定性处理:模板正文与作图笔记原文追加为
365
+ // 页尾小节(零模型语义下「每页模板」能做到的就是把人写的话原样放进页里)。模板名
366
+ // 查不到时页里放占位、warnings 里也记一条——两头都看得见,不静默吞。
367
+ function renderPlanExtras(custom, plan, warnings) {
368
+ if (!custom) return null;
369
+ const parts = [];
370
+ if (custom.template) {
371
+ const body = plan.templates?.[custom.template];
372
+ if (typeof body === "string") {
373
+ parts.push(`## 模板:${custom.template}`);
374
+ parts.push("");
375
+ parts.push(body.replace(/\n*$/, ""));
376
+ parts.push("");
377
+ } else {
378
+ warnings.push(`plan.yaml pages["${custom.path}"] 引用的模板 "${custom.template}" 在 templates 里没有定义,页里先放了占位。`);
379
+ parts.push(`## 模板:${custom.template}`);
380
+ parts.push("");
381
+ parts.push(`> plan.yaml 引用的模板 "${custom.template}" 在 templates 里没有定义;这段先占位,模板补上后重跑即得正文。`);
382
+ parts.push("");
383
+ }
384
+ }
385
+ if (custom.notes) {
386
+ parts.push("## 作图笔记(plan.yaml notes)");
387
+ parts.push("");
388
+ parts.push(custom.notes.replace(/\n*$/, ""));
389
+ parts.push("");
390
+ }
391
+ return parts.length > 0 ? parts.join("\n") : null;
392
+ }
393
+
394
+ // 写盘前的保留区保留:已有页面文件里的 CHORO:HUMAN 块整体抽出,逐字节接回新正文
395
+ // 页尾(实现计划 P6)。文件不存在(首轮)就当无块,直接用新正文。
396
+ function preserveHumanBlocks(absPath, newContent) {
397
+ let blocks = [];
398
+ if (existsSync(absPath)) {
399
+ try {
400
+ blocks = extractHumanBlocks(readFileSync(absPath, "utf8")).blocks;
401
+ } catch {
402
+ blocks = [];
403
+ }
404
+ }
405
+ const content = blocks.length > 0 ? injectHumanBlocks(newContent, blocks) : newContent;
406
+ return { content, humanBlocks: blocks.length };
407
+ }
408
+
409
+ function existingHumanBlockCount(absPath) {
410
+ if (!existsSync(absPath)) return 0;
411
+ try {
412
+ return extractHumanBlocks(readFileSync(absPath, "utf8")).count;
413
+ } catch {
414
+ return 0;
415
+ }
416
+ }
417
+
418
+ // 重跑 T0 会丢掉的东西:页面里已有的 T1 语义段,以及只被它引用的 evidence 文件。
419
+ // 返回值里的 pages 是相对路径(receipt 里人读),orphanEvidence 是 .chorography/
420
+ // evidence/ 下现有的 .json 个数——T0 apply 会清空 choro_claims,这些文件从此没有
421
+ // 引用者。两者都是「会失去什么」的清点,不构成阻止:丢弃是设计意图,静默才是 bug。
422
+ function collectT1Loss(rootPath, pageTargets) {
423
+ const pages = [];
424
+ for (const target of pageTargets) {
425
+ const abs = join(rootPath, target.relPath);
426
+ if (!existsSync(abs)) continue;
427
+ try {
428
+ if (readFileSync(abs, "utf8").includes(T1_SECTION_START)) pages.push(target.relPath);
429
+ } catch {
430
+ /* 读不了就当没有:清点不该让 T0 失败 */
431
+ }
432
+ }
433
+ let orphanEvidence = 0;
434
+ const evidenceDir = join(rootPath, CHORO_DIR, "evidence");
435
+ try {
436
+ orphanEvidence = readdirSync(evidenceDir).filter((name) => name.endsWith(".json")).length;
437
+ } catch {
438
+ orphanEvidence = 0;
439
+ }
440
+ return { pages, orphanEvidence };
441
+ }
442
+
443
+ function countExistingHumanBlocks(rootPath, pageTargets) {
444
+ let n = 0;
445
+ for (const target of pageTargets) {
446
+ n += existingHumanBlockCount(join(rootPath, target.relPath));
447
+ }
448
+ return n;
449
+ }
450
+
451
+ // 红线 1 的机械面:所有写路径必须落在 <root>/.chorography/ 内。slug 由 slugify
452
+ // 生成([a-z0-9-]),这条断言是保险层不是唯一防线——划分器改动时先撞这里。
453
+ function assertInsideChoro(rootPath, relPath) {
454
+ const abs = resolve(rootPath, relPath.split("/").join(sep));
455
+ const choroRoot = resolve(rootPath, CHORO_DIR);
456
+ if (!(abs === choroRoot || abs.startsWith(choroRoot + sep))) {
457
+ throw new ChoroRefusal(
458
+ "write-outside-chorography",
459
+ `写路径越出 ${CHORO_DIR}/:${relPath}(红线 1:chorography 绝不写仓库里任何别的位置)`
460
+ );
461
+ }
462
+ return abs;
463
+ }