focus-guard 3.0.7 → 3.4.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 (161) hide show
  1. package/LICENSE +683 -21
  2. package/NOTICE +25 -0
  3. package/README.md +14 -9
  4. package/README.zh-CN.md +12 -9
  5. package/docs/AB-PROMPTS.md +123 -0
  6. package/docs/AB-SESSION.md +161 -0
  7. package/docs/ARCH-MAP.md +148 -0
  8. package/docs/BENCH-BASELINE.json +95 -0
  9. package/docs/BENCH.md +323 -0
  10. package/docs/GATE-INPUTS.json +10 -0
  11. package/docs/HANDOFF-2026-10-27.md +736 -0
  12. package/docs/HOOK-ORDERING.md +139 -0
  13. package/docs/LEGISLATION-LAW.md +4 -2
  14. package/docs/MCP-4.0-PLAN.md +184 -0
  15. package/docs/MEMORY-4.5-PLAN.md +415 -0
  16. package/docs/PROFILE-TUNING.md +147 -0
  17. package/docs/RATCHET.json +48 -0
  18. package/docs/RELEASE-POLICY.md +163 -0
  19. package/docs/RULES.md +95 -14
  20. package/docs/THREAT-MODEL.md +68 -0
  21. package/docs/TOOL-SCHEMA.json +6 -0
  22. package/docs/VERSION-PLAN.md +532 -0
  23. package/docs/WRITING-STYLE.md +109 -0
  24. package/docs/architecture-map.mermaid +186 -0
  25. package/docs/deepseek-pricing-audit.md +2 -0
  26. package/hooks/guard.mjs +92 -56
  27. package/package.json +34 -5
  28. package/skills/focus-thinking/SKILL.md +9 -7
  29. package/src/adapters/dsh/eligibility-gate.mjs +446 -23
  30. package/src/adapters/dsh/tool-kinds.mjs +81 -0
  31. package/src/core/approval.mjs +2 -8
  32. package/src/core/approvals.mjs +208 -0
  33. package/src/core/audit-writer.mjs +297 -0
  34. package/src/core/audit.mjs +46 -16
  35. package/src/core/backup.mjs +37 -11
  36. package/src/core/checkEligibility.mjs +7 -4
  37. package/src/core/constants.mjs +67 -22
  38. package/src/core/decisionEngine.mjs +12 -0
  39. package/src/core/env.mjs +147 -19
  40. package/src/core/grants.mjs +54 -13
  41. package/src/core/kpi.mjs +16 -0
  42. package/src/core/outputGate.mjs +77 -0
  43. package/src/core/patterns.mjs +129 -0
  44. package/src/core/prefixStability.mjs +143 -0
  45. package/src/core/profileLoader.mjs +40 -5
  46. package/src/core/progressPolicy.mjs +65 -0
  47. package/src/core/redlines.mjs +49 -5
  48. package/src/core/risk.mjs +94 -15
  49. package/src/core/schemaDrift.mjs +125 -0
  50. package/src/core/sessionScratch.mjs +147 -0
  51. package/src/core/stageGraph.mjs +104 -0
  52. package/src/core/staleCleanup.mjs +153 -0
  53. package/src/core/state.mjs +215 -81
  54. package/src/core/stopPolicy.mjs +97 -0
  55. package/src/core/tempPath.mjs +23 -0
  56. package/src/dsh/audit.mjs +168 -118
  57. package/src/dsh/compactionWatch/announce.mjs +117 -0
  58. package/src/dsh/compactionWatch.mjs +68 -153
  59. package/src/dsh/guard/authz.mjs +97 -0
  60. package/src/dsh/guard/evidence.mjs +308 -0
  61. package/src/dsh/guard/hardCheck.mjs +85 -0
  62. package/src/dsh/guard/redline.mjs +62 -0
  63. package/src/dsh/guard/risk.mjs +196 -0
  64. package/src/dsh/guard/runtime.mjs +162 -0
  65. package/src/dsh/guard/superpowers.mjs +70 -0
  66. package/src/dsh/guard/tooling.mjs +177 -0
  67. package/src/dsh/guard/volume.mjs +181 -0
  68. package/src/dsh/guard/wholeFile.mjs +109 -0
  69. package/src/dsh/heartbeat.mjs +76 -13
  70. package/src/dsh/hookOrder.mjs +101 -0
  71. package/src/dsh/index.js +247 -15
  72. package/src/dsh/pipeline.mjs +77 -854
  73. package/src/dsh/policy-audit.mjs +84 -0
  74. package/src/dsh/postProgress.mjs +400 -274
  75. package/src/dsh/preGuard.mjs +249 -228
  76. package/src/dsh/repeatGuard.mjs +98 -0
  77. package/src/dsh/seams/pre-step.mjs +186 -0
  78. package/src/dsh/seams/prompt-rules.mjs +59 -0
  79. package/src/dsh/seams/session-start.mjs +297 -0
  80. package/src/dsh/seams/shared.mjs +109 -0
  81. package/src/dsh/seams.mjs +95 -408
  82. package/src/dsh/search-hints.mjs +136 -0
  83. package/src/dsh/sessionScope.mjs +28 -0
  84. package/src/dsh/status.mjs +7 -0
  85. package/src/dsh/stopGuard.mjs +225 -164
  86. package/src/dsh/testRuntime.mjs +62 -0
  87. package/src/dsh/toolKindAudit.mjs +66 -0
  88. package/src/dsh/tools.mjs +81 -5
  89. package/src/dsh/traceMeta.mjs +125 -0
  90. package/src/dsh/value-gate.mjs +93 -0
  91. package/src/dsh/workspace.mjs +3 -143
  92. package/src/memory/index.mjs +15 -0
  93. package/src/memory/tags.mjs +30 -0
  94. package/src/memory/workspace.mjs +283 -0
  95. package/src/peak-cost.mjs +1 -1
  96. package/src/profiles/deepseek-flash.mjs +7 -1
  97. package/src/profiles/deepseek-pro.mjs +6 -1
  98. package/src/profiles/default.mjs +6 -1
  99. package/src/profiles/glm.mjs +6 -1
  100. package/src/profiles/gpt-astra.mjs +6 -1
  101. package/tools/bench-ab.mjs +240 -0
  102. package/tools/bench-cost.mjs +176 -0
  103. package/tools/brain-cosmic.mjs +43 -0
  104. package/tools/brain-view.html +853 -0
  105. package/tools/brain.mjs +317 -0
  106. package/tools/capture-fixtures.mjs +182 -0
  107. package/tools/case-audit.mjs +114 -0
  108. package/tools/collect-panel.mjs +218 -0
  109. package/tools/dead-export.mjs +60 -0
  110. package/tools/docs-lint.mjs +82 -0
  111. package/tools/env-fingerprint.mjs +126 -33
  112. package/tools/first-run-sweep.mjs +123 -0
  113. package/tools/focusguard.mjs +155 -0
  114. package/tools/gate-audit.mjs +140 -0
  115. package/tools/gate-inputs.mjs +115 -0
  116. package/tools/handoff.mjs +56 -0
  117. package/tools/health.mjs +182 -0
  118. package/tools/knowledge.mjs +118 -0
  119. package/tools/layering-audit.mjs +105 -0
  120. package/tools/lib/book-style.mjs +136 -0
  121. package/tools/lib/brain-core.mjs +342 -0
  122. package/tools/lib/brain-docs.mjs +293 -0
  123. package/tools/lib/brain-regions.mjs +169 -0
  124. package/tools/lib/brain-relate.mjs +235 -0
  125. package/tools/lib/brain-text.mjs +121 -0
  126. package/tools/lib/case-tool.mjs +186 -0
  127. package/tools/lib/docs-core.mjs +392 -0
  128. package/tools/lib/docs-version.mjs +66 -0
  129. package/tools/lib/envMap.mjs +31 -0
  130. package/tools/lib/health-core.mjs +94 -0
  131. package/tools/lib/import-graph.mjs +118 -0
  132. package/tools/lib/index-io.mjs +70 -0
  133. package/tools/lib/open.mjs +32 -0
  134. package/tools/lib/prefix-cost.mjs +143 -0
  135. package/tools/lib/ratchet.mjs +174 -0
  136. package/tools/lib/reach.mjs +28 -0
  137. package/tools/lib/sessionDump.mjs +80 -0
  138. package/tools/lib/source-text.mjs +112 -0
  139. package/tools/library-book.mjs +313 -0
  140. package/tools/library-build.mjs +50 -12
  141. package/tools/library-index.mjs +91 -0
  142. package/tools/lint.mjs +282 -0
  143. package/tools/log-audit.mjs +108 -0
  144. package/tools/manifest-sync.mjs +111 -0
  145. package/tools/memory-audit.mjs +67 -0
  146. package/tools/module-audit.mjs +56 -0
  147. package/tools/mutate.mjs +316 -0
  148. package/tools/prefix-audit.mjs +122 -0
  149. package/tools/prefix-drift.mjs +325 -0
  150. package/tools/privacy-guard.mjs +352 -0
  151. package/tools/quality-audit.mjs +166 -0
  152. package/tools/schema-fingerprint.mjs +191 -0
  153. package/{src/dsh → tools}/selftest.mjs +75 -22
  154. package/tools/smells.mjs +398 -0
  155. package/tools/verify-case-paths.mjs +93 -0
  156. package/tools/version.mjs +191 -0
  157. package/docs/MASTER-PLAN-2.0.0.md +0 -133
  158. package/docs/MASTER-PLAN-3.0.0.md +0 -76
  159. package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
  160. package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
  161. /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
@@ -0,0 +1,317 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 3D 脑(tools/brain.mjs,2026-11-02)——零依赖,产出单文件 HTML。
4
+ *
5
+ * 为什么做这个:
6
+ * `AUDIT.log` 是一列按时间排的事件。时间轴告诉你「发生了什么」,不告诉你
7
+ * 「什么东西在长、什么东西正在被忘掉」。这个工具把事件流摊成一个体积:
8
+ * **实体是位置,共现是连线,强度是大小**。
9
+ *
10
+ * 三条判据(缺一条这东西就只是烟花):
11
+ * ① 位置 = FNV-1a(实体名) → 皮层顶点。实体不变,位置就不变。
12
+ * ② 位置由**分区**决定:脑干/小脑/大脑左右半球各自一块。解剖位置即语义。
13
+ * ③ 大小与亮度 = **遗忘曲线**(Ebbinghaus 指数衰减)。常用的亮,久不用的淡。
14
+ *
15
+ * 为什么要有索引(`.focus-guard/brain-index.json`):
16
+ * 审计按事件增长,永无止境;但**记忆的价值不随事件数增长**——第 8000 条和
17
+ * 第 8001 条讲的多半是同一批文件。所以这里把事件聚合成实体:**事件无界,实体有界**。
18
+ * 索引增量更新(游标),并随强度修剪——这是"不无限增长"的真正实现。
19
+ * 附带效果:`archive/` 里的原始底稿可以删,记忆不会丢(索引里已有聚合)。
20
+ *
21
+ * 边界(硬性,别越):
22
+ * ① **只读审计**。不写 AUDIT.log、不碰状态文件、不改任何判定。只写自己的索引与 HTML。
23
+ * ② **不进 hook**。`npm run brain` 手动跑一次,不在任何工具调用路径上。
24
+ * ③ **不打包第三方皮层数据**。网格是 `buildMesh` 自己算的。
25
+ * ④ **不引 three.js**。本仓 `dependencies: {}` 是唯一的性格。
26
+ *
27
+ * 用法:
28
+ * npm run brain # 增量 → .focus-guard/brain.html,并打开
29
+ * npm run brain:build # 只生成不打开
30
+ * node packages/core/tools/brain.mjs --rebuild # 丢掉索引,从头重算
31
+ * node packages/core/tools/brain.mjs --json # 只打图数据(供测试)
32
+ * node packages/core/tools/brain.mjs --out <path> # 换产物路径(试生成用)
33
+ */
34
+
35
+ import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from "node:fs";
36
+ import { dirname, join, resolve } from "node:path";
37
+ import { fileURLToPath, pathToFileURL } from "node:url";
38
+ import {
39
+ REGIONS, applyEvent, applySeqLinks, classify, emptyIndex, entitiesOf, listSources, loadConfig,
40
+ loadIndex, prune, readNewLines, reclassify, saveIndex, snapshot,
41
+ } from "./lib/brain-core.mjs";
42
+ import { syncDocs } from "./lib/brain-docs.mjs";
43
+ import { openInBrowser } from "./lib/open.mjs";
44
+
45
+ const HERE = dirname(fileURLToPath(import.meta.url));
46
+ const REPO = resolve(HERE, "..", "..", "..");
47
+ /* 包根:仓库里是 `packages/core`,装到 node_modules 之后就是包自己。
48
+ 文档源的路径在两个位置不同,`readDocs` 两个基都试。 */
49
+ const PKG = resolve(HERE, "..");
50
+
51
+ const DEFAULTS = {
52
+ log: join(REPO, ".focus-guard", "AUDIT.log"),
53
+ out: join(REPO, ".focus-guard", "brain.html"),
54
+ index: join(REPO, ".focus-guard", "brain-index.json"),
55
+ config: join(REPO, ".focus-guard", "brain-config.json"),
56
+ casefile: join(REPO, ".ai", "CASE_FILE.md"),
57
+ maxNodes: 3000,
58
+ maxEdges: 12000,
59
+ maxInf: 800,
60
+ };
61
+
62
+ function parseArgs(argv) {
63
+ const o = { ...DEFAULTS, json: false, open: false, rebuild: false, unknown: false, casefileWrite: false };
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ if (a === "--json") o.json = true;
67
+ else if (a === "--open") o.open = true;
68
+ else if (a === "--rebuild") o.rebuild = true;
69
+ else if (a === "--unknown") o.unknown = true;
70
+ else if (a === "--casefile") o.casefileWrite = true;
71
+ else if (a === "--log") o.log = resolve(argv[++i]);
72
+ else if (a === "--out") o.out = resolve(argv[++i]);
73
+ else if (a === "--index") o.index = resolve(argv[++i]);
74
+ else if (a === "--config") o.config = resolve(argv[++i]);
75
+ else if (a === "--max-nodes") o.maxNodes = Number(argv[++i]) || o.maxNodes;
76
+ else if (a === "--max-edges") o.maxEdges = Number(argv[++i]) || o.maxEdges;
77
+ else if (a === "--max-inf") o.maxInf = Number(argv[++i]) || o.maxInf;
78
+ }
79
+ return o;
80
+ }
81
+
82
+ /** 一批新行 → 索引。seq 链要跨行,所以按批聚合后再补边。 */
83
+ function ingest(idx, lines, repo, now, cfg) {
84
+ const groups = new Map();
85
+ let added = 0;
86
+ for (const line of lines) {
87
+ let rec;
88
+ try {
89
+ rec = JSON.parse(line);
90
+ } catch {
91
+ continue;
92
+ }
93
+ added += applyEvent(idx, rec, repo, now, cfg);
94
+ if (!rec.seq) continue;
95
+ const ids = entitiesOf(rec, repo, cfg).map((e) => `${e.type}:${e.name}`);
96
+ if (!ids.length) continue;
97
+ const g = groups.get(rec.seq) || [];
98
+ g.push({ ids, t: Date.parse(rec.ts || "") || now });
99
+ groups.set(rec.seq, g);
100
+ }
101
+ applySeqLinks(idx, [...groups.values()], now);
102
+ return added;
103
+ }
104
+
105
+ function readAll(opts, idx, now, cfg) {
106
+ let added = 0;
107
+ let sources = 0;
108
+ for (const src of listSources(opts.log)) {
109
+ const { lines, cursor } = readNewLines(src.path, idx.cursors[src.path]);
110
+ idx.cursors[src.path] = cursor;
111
+ if (!lines.length) continue;
112
+ sources++;
113
+ added += ingest(idx, lines, REPO, now, cfg);
114
+ }
115
+ return { added, sources };
116
+ }
117
+
118
+ /**
119
+ * 认不出来的东西,报出来——这是"灵活"的落点。
120
+ *
121
+ * 分类器没命中词表时**不猜**,标 fallback。但光标记没用,人看不见。
122
+ * 这里把 fallback 的实体按次数排序打出来,并附一条**共现建议**:
123
+ * 跟它连得最多的邻居都在哪个区,就建议归到哪个区。
124
+ *
125
+ * 为什么建议只进报告、不自动生效:分区决定位置(位置 = hash → 分区顶点池)。
126
+ * 让分区随图演化,同一个实体会今天在左脑、明天在右脑——那就看不出东西在长了。
127
+ * 自动学习只配**提议**,落地必须写进配置,由人拍板。
128
+ */
129
+ function reportUnknown(idx, cfg, configPath) {
130
+ // 空索引说「没有认不出来的」是假绿——那是没东西可认,不是都认出来了。
131
+ if (!Object.keys(idx.entities || {}).length) {
132
+ process.stdout.write("索引为空(还没跑过,或索引版本已升级被丢弃)。先跑一次 npm run brain。\n");
133
+ return;
134
+ }
135
+ const adj = new Map();
136
+ for (const e of Object.values(idx.edges)) {
137
+ for (const [a, b] of [[e.s, e.t], [e.t, e.s]]) {
138
+ if (!adj.has(a)) adj.set(a, []);
139
+ adj.get(a).push(b);
140
+ }
141
+ }
142
+ const rows = [];
143
+ for (const [id, n] of Object.entries(idx.entities)) {
144
+ const c = classify(n.t, n.n, cfg);
145
+ if (c.why !== "fallback" && c.why !== "fallback-trigger") continue;
146
+ const tally = {};
147
+ for (const nb of adj.get(id) || []) {
148
+ const m = idx.entities[nb];
149
+ if (!m) continue;
150
+ tally[m.r] = (tally[m.r] || 0) + 1;
151
+ }
152
+ const top = Object.entries(tally).sort((a, b) => b[1] - a[1])[0];
153
+ rows.push({ id, type: n.t, name: n.n, count: n.c, region: n.r, why: c.why, suggest: top ? top[0] : "", hits: top ? top[1] : 0 });
154
+ }
155
+ rows.sort((a, b) => b.count - a.count);
156
+
157
+ if (!rows.length) {
158
+ process.stdout.write("分类器:没有认不出来的实体(全部命中词表或结构判据)。\n");
159
+ return;
160
+ }
161
+ const lines = rows.slice(0, 40).map(
162
+ (r) =>
163
+ ` ${String(r.count).padStart(5)} 次 ${r.type.padEnd(7)} ${r.name.slice(0, 52).padEnd(52)}` +
164
+ `→ ${REGIONS[r.region].label}` +
165
+ (r.suggest ? ` (邻居多在${REGIONS[r.suggest].label} ${r.hits} 个)` : ""),
166
+ );
167
+ process.stdout.write(
168
+ `分类器:${rows.length} 个实体没命中词表,暂按兜底处理(共 ${rows.reduce((s, r) => s + r.count, 0)} 次)。\n` +
169
+ `补词表:在 ${String(configPath).replace(REPO, ".").replace(/\\/g, "/")} 里写 ` +
170
+ `{"lexicon":{"stem":["…"]}},或 {"rules":[{"re":"…","region":"stem"}]}\n` +
171
+ `${lines.join("\n")}\n` +
172
+ (rows.length > 40 ? ` …另有 ${rows.length - 40} 个\n` : ""),
173
+ );
174
+ }
175
+
176
+ /**
177
+ * 卷宗反写:把推断关联写成【六】段,让卷宗自己长出「相关条目」。
178
+ *
179
+ * 为什么默认**不写**、要显式 `--casefile`:脑是只读面的工具,卷宗是判定面的文件。
180
+ * 每次跑脑都顺手改判定面的文件,测试里那条「软记录变化」就会被自己的噪音淹掉,
181
+ * 而且"只读审计"这条边界也就名存实亡。要写,就写成一个明确的动作。
182
+ */
183
+ function writeCaseFile(casePath, g, now, events) {
184
+ const name = (i) => (g.nodes[i] ? g.nodes[i].name : "?");
185
+ // 两边都是盘符绝对路径(`E:/DSH/_install/*.mjs` 那批探针)互相关联,信息量最低:
186
+ // 它们本来就同目录同批产生。过滤掉,把位置让给本仓内的关联。
187
+ const external = (s) => /^[A-Za-z]:\//.test(String(s));
188
+ const cand = g.edges.filter((e) => e.k === "inf" && e.v >= 0.5 && !(external(name(e.s)) && external(name(e.t))));
189
+ const rows = cand.slice(0, 20).map(
190
+ (e) =>
191
+ `| \`${name(e.s)}\` | \`${name(e.t)}\` | ${e.v.toFixed(2)} | ${e.parts?.aa ?? "-"} | ${e.parts?.aff ?? "-"} | ${e.parts?.tmp ?? "-"} |`,
192
+ );
193
+ const block =
194
+ `### 【六】相关条目(脑推断 · 非人工填写)\n\n` +
195
+ `> 由 \`npm run brain -- --casefile\` 生成,${new Date(now).toISOString().slice(0, 16).replace("T", " ")}。\n` +
196
+ `> 判据:两个实体**从未在同一行出现**,但共享冷门中间物(结构)、同目录(亲缘)、\n` +
197
+ `> 或同一段时间一起活跃(共活跃)。只列综合分 ≥ 0.5 的前 20 条,分数逐项可复算。\n` +
198
+ `> 用途:查一个东西时先看它跟谁有关,不必把 ${events} 条事件从头读一遍。\n` +
199
+ `> 已排除「两边都是盘符绝对路径」的条目——那批探针同目录同批产生,关联是自明的。\n\n` +
200
+ `| 甲 | 乙 | 分 | 结构 | 亲缘 | 共活跃 |\n|---|---|---|---|---|---|\n` +
201
+ `${rows.join("\n")}\n`;
202
+
203
+ const old = existsSync(casePath) ? readFileSync(casePath, "utf8") : "";
204
+ const at = old.search(/^### 【六】/m);
205
+ let head = old;
206
+ if (at >= 0) {
207
+ // 只替换【六】这一段,后面的【七】…(如果哪天加了)原样保留
208
+ const nextAt = old.slice(at + 1).search(/^### 【/m);
209
+ head = old.slice(0, at) + (nextAt >= 0 ? old.slice(at + 1 + nextAt) : "");
210
+ } else if (old && !old.endsWith("\n")) {
211
+ head = `${old}\n`;
212
+ }
213
+ writeFileSync(casePath, head + (head.endsWith("\n\n") ? "" : "\n") + block);
214
+ return rows.length;
215
+ }
216
+
217
+ function main() {
218
+ const o = parseArgs(process.argv.slice(2));
219
+ const now = Date.now();
220
+ const cfg = loadConfig(o.config);
221
+
222
+ if (o.rebuild && existsSync(o.index)) rmSync(o.index, { force: true });
223
+ const idx = o.rebuild ? emptyIndex() : loadIndex(o.index);
224
+
225
+ if (o.unknown) {
226
+ reportUnknown(idx, cfg, o.config);
227
+ return;
228
+ }
229
+
230
+ const moved = reclassify(idx, cfg);
231
+ const { added, sources } = readAll(o, idx, now, cfg);
232
+ // 文档源:日志记的是"我碰过什么",文档记的是"我知道什么"。
233
+ // 只有前者的时候,脑认识 `docs/RULES.md` 被提到 85 次,却不知道那 85 次说了什么。
234
+ const docs = syncDocs(idx, REPO, o.docs, PKG);
235
+ const dropped = prune(idx, now);
236
+ saveIndex(o.index, idx, now);
237
+
238
+ const g = snapshot(idx, now, o.maxNodes, o.maxEdges, o.maxInf);
239
+ // 每个点自证位置:分区是按什么判据定的。没有这一行,点开只看到"它在左脑",
240
+ // 却不知道为什么——那正是"知识看起来莫名其妙"的来源。
241
+ // 记忆块的分区来自**它所在的文档**(法条→脑干、方法→小脑),不是词表打分,所以单独标。
242
+ for (const n of g.nodes) n.w = n.type === "memory" ? "source" : classify(n.type, n.name, cfg).why;
243
+ const regionCount = {};
244
+ for (const n of g.nodes) regionCount[n.r] = (regionCount[n.r] || 0) + 1;
245
+ const from = g.nodes.reduce((m, n) => (!m || (n.f && n.f < m) ? n.f : m), "");
246
+ const to = g.nodes.reduce((m, n) => (n.l && n.l > m ? n.l : m), "");
247
+
248
+ const meta = {
249
+ log: o.log.replace(REPO, "").replace(/\\/g, "/"),
250
+ generatedAt: new Date(now).toISOString(),
251
+ events: idx.seen,
252
+ added,
253
+ sources,
254
+ nodes: g.nodes.length,
255
+ edges: g.edges.length,
256
+ inferred: g.inferred,
257
+ clusters: g.clusters,
258
+ total: g.total,
259
+ totalEdges: g.totalEdges,
260
+ truncated: g.nodes.length < g.total,
261
+ forgotten: dropped,
262
+ memories: docs.blocks,
263
+ // 实读数,不是配置数。界面要能说"这个脑是从几份文档长出来的"。
264
+ memorySources: docs.sources,
265
+ memoryMissing: docs.missing.length,
266
+ from,
267
+ to,
268
+ regions: regionCount,
269
+ halfLives: Object.fromEntries(Object.entries(REGIONS).map(([k, v]) => [k, v.halfLife])),
270
+ };
271
+
272
+ if (o.json) {
273
+ process.stdout.write(JSON.stringify({ meta, nodes: g.nodes, edges: g.edges }, null, 1));
274
+ return;
275
+ }
276
+
277
+ const tpl = readFileSync(join(HERE, "brain-view.html"), "utf8");
278
+ const payload = JSON.stringify({ meta, nodes: g.nodes, edges: g.edges }).replace(/<\//g, "<\\/");
279
+ mkdirSync(dirname(o.out), { recursive: true });
280
+ writeFileSync(o.out, tpl.replace("/*__FG_BRAIN_DATA__*/null", payload));
281
+
282
+ const cf = o.casefileWrite ? writeCaseFile(o.casefile, g, now, idx.seen) : 0;
283
+ report(o, { g, idx, added, sources, moved, dropped, docs, regionCount, from, to, cf });
284
+ if (o.open) openInBrowser(o.out);
285
+ }
286
+
287
+ /* 汇总输出单独成函数:它跟"跑一遍"本来就是两件事,混在 main() 里只会让流程读不清。
288
+ 判据要的是"这一段能不能读懂",不是"能不能压到 80 行"。 */
289
+ function report(o, x) {
290
+ const rl = Object.entries(REGIONS)
291
+ .map(([k, v]) => `${v.label} ${x.regionCount[k] || 0}`)
292
+ .join(" · ");
293
+ process.stdout.write(
294
+ `脑已更新:${pathToFileURL(o.out).href}\n` +
295
+ ` ${o.open ? "已请求用默认程序打开(没弹窗就点上面那个地址)" : `打开:npm run brain -- --open 或直接双击上面这个地址`}\n` +
296
+ ` 新增 ${x.added} 条(源 ${x.sources} 个)· 累计 ${x.idx.seen} 条事件 · 遗忘 ${x.dropped} 个 · 重分区 ${x.moved} 个\n` +
297
+ ` 记忆 ${x.docs.blocks} 块(实读 ${x.docs.sources} 份文档` +
298
+ (x.docs.missing.length ? `,缺 ${x.docs.missing.length} 份` : "") +
299
+ (x.docs.stale ? `,跳过作废 ${x.docs.stale} 条` : "") + `)\n` +
300
+ memLine(x.docs) +
301
+ ` ${x.g.nodes.length} 实体 / ${x.g.edges.length} 边(推断 ${x.g.inferred}) ${rl}\n` +
302
+ ` 知识簇:${x.g.clusters.map((c) => `${c.name}(${c.size})`).slice(0, 6).join(" · ") || "(无)"}\n` +
303
+ (o.casefileWrite ? ` 卷宗【六】已写:${x.cf} 条相关条目 → ${o.casefile.replace(REPO, ".")}\n` : "") +
304
+ // 空态下不报日期范围:那两头的日期来自**文档条目**的 mtime,跟"事件"没关系,
305
+ // 写着只是让人以为有 24 小时的数据。判据要用事件数,不能用 from 是否为空。
306
+ ` ${x.idx.seen ? `${x.from.slice(0, 10)} → ${x.to.slice(0, 10)} ` : "尚无审计事件 "}索引 ${(readFileSync(o.index).length / 1024).toFixed(0)} KB\n`,
307
+ );
308
+ }
309
+
310
+ /* 关联要报**连上了多少**,不能只报"有连边"——孤岛多少同样是事实。
311
+ 上一版只写「记忆 356 块」,于是"关联做好了"这句话成立了三周,图上一直是散点。 */
312
+ function memLine(d) {
313
+ return ` 记忆关联:痕迹 ${d.trace} · 互引 ${d.ref} · 同题 ${d.share}` +
314
+ (d.orphan ? ` 落空 ${d.orphan} 处` : "") + "\n";
315
+ }
316
+
317
+ main();
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 真实调用夹具导出(2026-10-22)——防"手写参数自欺"。
4
+ *
5
+ * 病根:合成测试之所以能骗过自己,是因为**测试输入由实现作者手写**:写 `head_limit`
6
+ * 的人,测试里就有 `head_limit`。真实模型发的是另一套参数(`{pattern,path,include}`)。
7
+ * 本工具只做一件事:把**真实会话里的 (工具名, 参数, 判定结果)** 原样导出成夹具,
8
+ * 测试只准读这些夹具。手写参数仅作为补充,且必须在测试里标注「合成」。
9
+ *
10
+ * 用法:
11
+ * node packages/core/tools/capture-fixtures.mjs # 写到 tests/fixtures/real-calls/
12
+ * node packages/core/tools/capture-fixtures.mjs --limit 40 # 最多扫 40 个会话
13
+ * node packages/core/tools/capture-fixtures.mjs --since 24h # 只取最近 24h
14
+ */
15
+
16
+ import { decodeSession as decode } from './lib/sessionDump.mjs'
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from 'node:fs'
18
+ import { dirname, join, basename } from 'node:path'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ const HERE = dirname(fileURLToPath(import.meta.url))
22
+ const CORE = join(HERE, '..')
23
+ const SESSIONS = process.env.FG_SESSIONS_DIR || 'E:/DSH/.dsh/sessions'
24
+ const OUT = join(CORE, 'tests', 'fixtures', 'real-calls')
25
+
26
+ // 本机环境闸的规则来源是 `.ai/env-fingerprint.json`——**私有面文件,不入版本库**。
27
+ // 不把 map 一起记下来,这类样本就只能在录制机上复现:干净 clone 上该闸按设计 fail-open,
28
+ // 重放必报「漏拦」。记下来,重放时用 `FG_ENV_FP_FILE` 指到临时文件即可还原现场。
29
+ const ENV_FP = join(CORE, '..', '.ai', 'env-fingerprint.json')
30
+ const ENV_MAP = (() => {
31
+ try {
32
+ const j = JSON.parse(readFileSync(ENV_FP, 'utf8'))
33
+ return j && j.map && typeof j.map === 'object' ? j.map : null
34
+ } catch {
35
+ return null
36
+ }
37
+ })()
38
+
39
+ const argv = process.argv.slice(2)
40
+ const LIMIT = Number(argv.includes('--limit') ? argv[argv.indexOf('--limit') + 1] : 30) || 30
41
+ const MAX_BYTES = 3 * 1024 * 1024
42
+
43
+ // 判定为「被拦」的真实文案(与 collect-panel / gate-audit 同口径)
44
+ // 判定为「被拦」:必须命中 FG 自己的**拒绝措辞**,不能只是文本里出现"禁/红线/拦截"这类词。
45
+ // 2026-10-22 教训:宽松正则把专家团任务描述(含"禁"“红线")全判成 deny,夹具一跑就假阳性。
46
+ const DENY_RE =
47
+ /focus-guard-native|该工具需先调 fg_apply|命中绝对红线|整文件闸|体积刺客|本机环境[::]用|第\s*3\s*层状态校验|卷宗无取证记录|反规避抽查B|改动类工具/
48
+ // 拒绝必须以 Error 开头:成功结果里也可能出现上面这些词(例如读的是 FG 自己的源码)。
49
+ const DENY_PREFIX_RE = /^\s*Error[::]/
50
+ const DENY_ZCODE_RE = /^\s*【拦截】/
51
+
52
+ function walk(dir, out = []) {
53
+ let entries = []
54
+ try {
55
+ entries = readdirSync(dir)
56
+ } catch {
57
+ return out
58
+ }
59
+ for (const e of entries) {
60
+ const p = join(dir, e)
61
+ let st
62
+ try {
63
+ st = statSync(p)
64
+ } catch {
65
+ continue
66
+ }
67
+ if (st.isDirectory()) walk(p, out)
68
+ else if (e === 'session.v4.jsonl.zstd') out.push({ f: p, m: st.mtimeMs, size: st.size })
69
+ }
70
+ return out
71
+ }
72
+
73
+ /** 截断过长的参数值(content/command 可能上千字),只保留形状。 */
74
+ function compactArg(value, limit = 160) {
75
+ if (typeof value === 'string') return value.length > limit ? `${value.slice(0, limit)}…(${value.length})` : value
76
+ if (Array.isArray(value)) return value.slice(0, 6).map((v) => compactArg(v, limit))
77
+ if (value && typeof value === 'object') {
78
+ const out = {}
79
+ for (const [k, v] of Object.entries(value)) out[k] = compactArg(v, limit)
80
+ return out
81
+ }
82
+ return value
83
+ }
84
+
85
+ const files = walk(SESSIONS)
86
+ .filter((x) => x.size < MAX_BYTES)
87
+ .sort((a, b) => b.m - a.m)
88
+ .slice(0, LIMIT)
89
+
90
+ const fixtures = []
91
+ const passPerTool = new Map()
92
+
93
+ for (const { f } of files) {
94
+ let lines
95
+ try {
96
+ lines = decode(f)
97
+ } catch {
98
+ continue
99
+ }
100
+ const sid = basename(dirname(f)).replace('session-', '').slice(0, 8)
101
+ const calls = new Map()
102
+ for (const l of lines) {
103
+ if (l.type === 'tool/call') {
104
+ let args = {}
105
+ try {
106
+ args = JSON.parse(l.data.arguments || '{}')
107
+ } catch {
108
+ args = { _raw: String(l.data.arguments || '').slice(0, 200) }
109
+ }
110
+ calls.set(l.data.callId, { name: l.data.name, args, turn: l.data.turn, step: l.data.step })
111
+ }
112
+ }
113
+ for (const l of lines) {
114
+ if (l.type !== 'tool/result') continue
115
+ const call = calls.get(l.data.toolCallId || (l.data.message && l.data.message.toolCallId))
116
+ if (!call) continue
117
+ const content = (l.data.message && l.data.message.content) || []
118
+ const text = JSON.stringify(content)
119
+ // 判定"被拦"必须看**结果的首个文本块是否以 Error 开头**:
120
+ // 2026-10-22 教训:成功结果里也会出现"整文件闸""拦截"等字样(读的是 FG 自己的源码),
121
+ // 用全文正则匹配会把成功读取误判成拦截,夹具一重放就露馅。
122
+ const firstText = String((content.find((c) => c && c.type === 'text') || {}).text || '')
123
+ const denied = DENY_PREFIX_RE.test(firstText) || DENY_ZCODE_RE.test(firstText)
124
+ if (!denied) {
125
+ const n = passPerTool.get(call.name) || 0
126
+ if (n >= 2) continue // 放行样本每工具最多留 2 条,避免夹具膨胀
127
+ passPerTool.set(call.name, n + 1)
128
+ }
129
+ // 参数必须**原样**保留:截断过的参数会让重放判定失真(2026-10-22 实测:
130
+ // 截断后的路径不再是目录 → Grep 未收窄闸不触发 → 夹具自己假阳性)。
131
+ // 过大参数整条跳过,而不是截断。
132
+ const argJson = JSON.stringify(call.args)
133
+ if (argJson.length > 4000) continue
134
+ fixtures.push({
135
+ source: { session: sid, turn: call.turn, step: call.step },
136
+ tool: call.name,
137
+ args: call.args,
138
+ verdict: denied ? 'deny' : 'pass',
139
+ reason: denied ? text.replace(/\\n/g, ' ').slice(0, 160) : null,
140
+ ...(denied && /本机环境/.test(text) && ENV_MAP ? { envMap: ENV_MAP } : {}),
141
+ })
142
+ }
143
+ }
144
+
145
+ if (existsSync(OUT)) rmSync(OUT, { recursive: true, force: true })
146
+ mkdirSync(OUT, { recursive: true })
147
+
148
+ fixtures.forEach((fx, i) => {
149
+ writeFileSync(join(OUT, `call-${String(i + 1).padStart(3, '0')}-${fx.verdict}.json`), JSON.stringify(fx, null, 2) + '\n')
150
+ })
151
+
152
+ writeFileSync(
153
+ join(OUT, 'manifest.json'),
154
+ JSON.stringify(
155
+ {
156
+ generatedAt: new Date().toISOString(),
157
+ sessions: files.length,
158
+ total: fixtures.length,
159
+ deny: fixtures.filter((f) => f.verdict === 'deny').length,
160
+ pass: fixtures.filter((f) => f.verdict === 'pass').length,
161
+ byTool: fixtures.reduce((acc, f) => ((acc[f.tool] = (acc[f.tool] || 0) + 1), acc), {}),
162
+ },
163
+ null,
164
+ 2,
165
+ ) + '\n',
166
+ )
167
+
168
+ writeFileSync(
169
+ join(OUT, 'README.md'),
170
+ `# 真实调用夹具(自动生成,禁止手改)
171
+
172
+ 由 \`node packages/core/tools/capture-fixtures.mjs\` 从**真实会话**导出:
173
+ 每条 = 一次真实 \`tool/call\` 的参数形状 + 宿主返回的 \`tool/result\` 判定。
174
+
175
+ - \`verdict: "deny"\` = 当时 FG 拦下了(真实拦截文案前 160 字)
176
+ - \`verdict: "pass"\` = 当时放行(每工具最多 2 条)
177
+
178
+ **纪律**:测试只准读这里 + 自己的合成参数(合成必须标注)。手改本目录等于毁掉证据链。
179
+ `,
180
+ )
181
+
182
+ console.log(`[capture-fixtures] 写出 ${fixtures.length} 条(deny ${fixtures.filter((f) => f.verdict === 'deny').length} / pass ${fixtures.filter((f) => f.verdict === 'pass').length})→ ${OUT}`)
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 卷宗体检 —— 只读重放磁盘,比对卷宗【三】,报不一致(3.4.0)
4
+ *
5
+ * ## 抄的是谁
6
+ *
7
+ * `Ido1um/DeepSeek-memory-Ido1um` 的 `audit-facts.mjs`:只读重放原文 → 按当前抽取规则
8
+ * 重抽一遍 → 跟事实库比对 → 报「漏记 N 条」。那套范式的价值不在代码,在**判据**:
9
+ * 它不问「库好不好」,只问「原文里该有的,库里有没有」。
10
+ *
11
+ * ## 本仓的映射
12
+ *
13
+ * memory 的「原文日志」 → 本仓的「磁盘现状」
14
+ * memory 的「抽取规则」 → 本仓的「侦查规则」(guard.mjs / postProgress.mjs 写【三】的口径)
15
+ * memory 的「事实库」 → 本仓的「卷宗【三】侦查记录」
16
+ *
17
+ * 卷宗是磁盘的投影。投影失真 = 记录不可信 = 拿旧结论当新证据。
18
+ * 这正是 3.3 那四个症状的同一个病:**校验物与被校验物断线**。
19
+ *
20
+ * ## 三条断言
21
+ *
22
+ * ghost 卷宗有行、磁盘没文件 改名/删除后没清理,记录悬空 —— **真异常**
23
+ * changed 读完之后文件又变了 卷宗落后于现实 —— 正常流转,下次读取自然更新
24
+ * aged 保持度 R < 0.5 半衰期已过 —— 正常流转,保守重读
25
+ *
26
+ * 前一条是缺陷,后两条是状态。混在一起报就是 197/200 全红——红得没信息量,
27
+ * 人开始忽略红,检查等于没有(2026-10-29 教训:按原因分档,不按结果对错分档)。
28
+ *
29
+ * ## 读法(对齐 audit-facts 的三种结果)
30
+ *
31
+ * ✓ 没有悬空 —— 卷宗与磁盘一致
32
+ * ✗ 悬空 N 条 —— 逐条列路径,删掉那一行即可(本命令只报告,不自动修)
33
+ * · 落后 M 条 —— 只是「该重读了」,不影响结论有效性,默认不展开
34
+ *
35
+ * 默认退出码 0(体检不阻断);`--strict` 时只有**悬空**才 1。
36
+ */
37
+ import { existsSync } from 'node:fs'
38
+ import { isAbsolute, join } from 'node:path'
39
+ import { casePath, loadCaseRecords, fingerprint, retention, halfLifeOf } from '../src/core/state.mjs'
40
+
41
+ const HALF_LIFE_MS = 3600e3
42
+
43
+ /** 卷宗行 → 绝对路径。绝对路径原样用,相对路径按工作区解析。 */
44
+ function resolveRecord(projDir, rec) {
45
+ return isAbsolute(rec.path) ? rec.path : join(projDir, rec.path)
46
+ }
47
+
48
+ /** 单行判定:返回一条 finding 或 null。顺序即优先级,一条行只报一个最重的。 */
49
+ function judge(projDir, rec, now) {
50
+ const abs = resolveRecord(projDir, rec)
51
+ if (!existsSync(abs)) {
52
+ return { kind: 'ghost', path: rec.path, detail: '卷宗有行,磁盘上没这个文件' }
53
+ }
54
+ let fp
55
+ try {
56
+ fp = fingerprint(abs)
57
+ } catch {
58
+ return { kind: 'ghost', path: rec.path, detail: '文件存在但读不动(权限/占用)' }
59
+ }
60
+ const moved = rec.sha ? Boolean(fp.sha) && fp.sha !== rec.sha : Math.abs(fp.mtime - rec.mtime) > 1 || fp.size !== rec.size
61
+ if (moved) return { kind: 'changed', path: rec.path, detail: '读完之后文件又变了' }
62
+ const r = retention(rec, now)
63
+ if (r < 0.5) {
64
+ const s = (halfLifeOf(rec, now) / HALF_LIFE_MS).toFixed(1)
65
+ return { kind: 'aged', path: rec.path, detail: `R=${r.toFixed(2)}(半衰期 ${s}h 已过)` }
66
+ }
67
+ return null
68
+ }
69
+
70
+ export function auditCase(projDir, opts = {}) {
71
+ const now = opts.now || Date.now()
72
+ const file = casePath(projDir)
73
+ const records = loadCaseRecords(file)
74
+ const rows = Object.values(records)
75
+ const findings = rows.map((rec) => judge(projDir, rec, now)).filter(Boolean)
76
+ return { file, total: rows.length, findings }
77
+ }
78
+
79
+ function printHuman(result, showAll) {
80
+ const { file, total, findings } = result
81
+ const ghost = findings.filter((f) => f.kind === 'ghost')
82
+ const drift = findings.filter((f) => f.kind !== 'ghost')
83
+ console.log(`卷宗 ${file}`)
84
+ console.log(`侦查记录 ${total} 条`)
85
+ if (ghost.length) {
86
+ console.log(`\n✗ 悬空 ${ghost.length} 条 —— 文件已不在,行该删`)
87
+ for (const f of ghost.slice(0, 12)) console.log(` ${f.path}`)
88
+ if (ghost.length > 12) console.log(` …另 ${ghost.length - 12} 条`)
89
+ } else {
90
+ console.log('\n✓ 没有悬空:卷宗里每一行都指向真实文件。')
91
+ }
92
+ if (!drift.length) return
93
+ const changed = drift.filter((f) => f.kind === 'changed').length
94
+ console.log(`\n· 落后 ${drift.length} 条(changed ${changed} / aged ${drift.length - changed})—— 只是该重读了,不影响结论有效性`)
95
+ if (!showAll) {
96
+ console.log(' 加 --all 展开明细')
97
+ return
98
+ }
99
+ for (const f of drift.slice(0, 20)) console.log(` [${f.kind}] ${f.path} —— ${f.detail}`)
100
+ if (drift.length > 20) console.log(` …另 ${drift.length - 20} 条`)
101
+ }
102
+
103
+ function main() {
104
+ const argv = process.argv.slice(2)
105
+ const dirIdx = argv.indexOf('--dir')
106
+ const projDir = dirIdx >= 0 ? argv[dirIdx + 1] : process.cwd()
107
+ const result = auditCase(projDir)
108
+ if (argv.includes('--json')) console.log(JSON.stringify(result, null, 2))
109
+ else printHuman(result, argv.includes('--all'))
110
+ const blocking = result.findings.filter((f) => f.kind === 'ghost').length
111
+ process.exit(argv.includes('--strict') && blocking ? 1 : 0)
112
+ }
113
+
114
+ if (process.argv[1] && process.argv[1].endsWith('case-audit.mjs')) main()