@modusensus/dsh-mneme 0.13.0 → 0.14.0-beta.1

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 (65) hide show
  1. package/README.md +6 -4
  2. package/bin/dsh-mneme-choro.mjs +9 -1
  3. package/docs/CONFIGURATION.md +5 -3
  4. package/lib/api.js +211 -5
  5. package/lib/client.js +1240 -354
  6. package/lib/config.js +27 -0
  7. package/lib/dream/decisions.js +39 -1
  8. package/lib/dream/sleep.js +146 -6
  9. package/lib/dream/triage.js +139 -0
  10. package/lib/dream.js +123 -8
  11. package/lib/hot-memory.js +14 -2
  12. package/lib/index.js +31 -1
  13. package/lib/inject.js +14 -2
  14. package/lib/lang.js +11 -0
  15. package/lib/service.js +76 -4
  16. package/lib/settings.js +16 -1
  17. package/lib/store.js +238 -5
  18. package/lib/wiki/claims.js +267 -0
  19. package/lib/wiki/queries.js +168 -2
  20. package/lib/wiki/render.js +74 -0
  21. package/lib/wiki/t0.js +43 -6
  22. package/lib/wiki/t1.js +138 -31
  23. package/package.json +15 -1
  24. package/scripts/release-docs.mjs +7 -1
  25. package/scripts/release-notes.mjs +4 -1
  26. package/src/api.js +211 -5
  27. package/src/config.js +27 -0
  28. package/src/dream/decisions.js +39 -1
  29. package/src/dream/sleep.js +146 -6
  30. package/src/dream/triage.js +139 -0
  31. package/src/dream.js +123 -8
  32. package/src/hot-memory.js +14 -2
  33. package/src/index.js +31 -1
  34. package/src/inject.js +14 -2
  35. package/src/lang.js +11 -0
  36. package/src/service.js +76 -4
  37. package/src/settings.js +16 -1
  38. package/src/store.js +238 -5
  39. package/src/wiki/claims.js +267 -0
  40. package/src/wiki/queries.js +168 -2
  41. package/src/wiki/render.js +74 -0
  42. package/src/wiki/t0.js +43 -6
  43. package/src/wiki/t1.js +138 -31
  44. package/test/api.test.js +11 -1
  45. package/test/client.test.js +275 -34
  46. package/test/conflict-ledger-enforce.test.js +452 -0
  47. package/test/conflict-ledger.test.js +242 -0
  48. package/test/contrast.test.js +124 -12
  49. package/test/dream-baseline-clamp.test.js +174 -0
  50. package/test/graph-api.test.js +124 -0
  51. package/test/hot-memory.test.js +48 -0
  52. package/test/inject-parent-gate.test.js +6 -3
  53. package/test/inject.test.js +59 -0
  54. package/test/panel-chart-scale.test.js +90 -0
  55. package/test/panel-tokens.test.js +245 -0
  56. package/test/release-docs.test.js +20 -0
  57. package/test/release-notes.test.js +25 -0
  58. package/test/security-doc.test.js +10 -0
  59. package/test/sleep.test.js +37 -0
  60. package/test/wiki-api.test.js +110 -3
  61. package/test/wiki-claims.test.js +194 -0
  62. package/test/wiki-provenance.test.js +202 -0
  63. package/test/wiki-queries.test.js +121 -0
  64. package/test/wiki-t0.test.js +77 -1
  65. package/test/wiki-t1.test.js +226 -1
package/lib/wiki/t1.js CHANGED
@@ -23,7 +23,11 @@ import { readFileSync, writeFileSync, existsSync, mkdtempSync, rmSync, mkdirSync
23
23
  import { join, dirname, sep, resolve } from "node:path";
24
24
  import { tmpdir } from "node:os";
25
25
  import { realpathSync } from "node:fs";
26
- import { extractHumanBlocks, injectHumanBlocks, T1_SECTION_START, T1_SECTION_END } from "./render.js";
26
+ import {
27
+ extractHumanBlocks, injectHumanBlocks, T1_SECTION_START, T1_SECTION_END,
28
+ FM_VERIFIED_AT, FM_VERIFIED_BASELINE, setFrontmatterKeys,
29
+ } from "./render.js";
30
+ import { gitHead } from "./t0.js";
27
31
  // issue #607:拒绝文案里的 CLI 命令要给绝对路径入口(profile 装的插件没有全局
28
32
  // shim,光写 `dsh-mneme-choro` 用户照抄只会 command not found)。
29
33
  import { choroCliCommandFrom } from "./cli-hint.js";
@@ -64,9 +68,18 @@ export function isEnvironmentFailure(result) {
64
68
  // 模型路由走 --patch 临时 overlay 指池模型(bili-scroll 同款,零配置改动)。
65
69
  // exe 定位:env DSH_EXE > process.execPath(本身是 Harness exe,即已在宿主 CLI 内)>
66
70
  // 标准安装位。定位不到 → environment 失败(降级表第一行),不猜测。
67
- export function makeHeadlessRunner({ profile = "headless", onOverlay = null } = {}) {
71
+ //
72
+ // 三种定位(exe / cli.js / 失败诊断)都做成可注入的纯函数:issue #578 的病根全在
73
+ // 「按一种安装布局写死」,而布局差异只有真机上才看得见——不能测的东西迟早会错。
74
+ export function makeHeadlessRunner({
75
+ profile = "headless",
76
+ onOverlay = null,
77
+ spawn: spawnFn = spawn,
78
+ locateExe = locateDshExe,
79
+ resolveCli = resolveCliJs,
80
+ } = {}) {
68
81
  return async function runSession({ cwd, task, model, timeoutMs, maxToolCalls, maxOutputBytes }) {
69
- const exe = locateDshExe();
82
+ const exe = locateExe();
70
83
  if (!exe) {
71
84
  return {
72
85
  ok: false,
@@ -74,10 +87,16 @@ export function makeHeadlessRunner({ profile = "headless", onOverlay = null } =
74
87
  reason: "找不到 DeepSeek Harness 主程序(设 DSH_EXE 环境变量,或用 --dsh-exe 显式指定)",
75
88
  };
76
89
  }
77
- const cliJs = locateCliJs(exe);
78
- if (!cliJs) {
79
- return { ok: false, kind: "environment", reason: `在 ${dirname(exe)} 下找不到 dsh-desktop-host 的 cli.js` };
90
+ const cli = resolveCli(exe);
91
+ if (!cli.path) {
92
+ // 显式指定(DSH_CLI_JS / --dsh-cli)但路径不存在,与「哪种布局都找不到」是两件
93
+ // 事:前者是人写错了一个字符,后者是布局没覆盖。分开说,否则用户会去改布局。
94
+ const reason = cli.explicitMissing
95
+ ? `DSH_CLI_JS 指定的 headless CLI 不存在:${cli.explicitMissing}(这是显式指定,不会回退到其它候选;改正它或取消指定)`
96
+ : `在 ${dirname(exe)} 下找不到 headless CLI。试过:${cli.candidates.join("、") || "(无候选)"}。DSH NEXT 布局可用环境变量 DSH_CLI_JS 直接指定 cli 路径`;
97
+ return { ok: false, kind: "environment", reason };
80
98
  }
99
+ const cliJs = cli.path;
81
100
  const [provider, modelName] = String(model).split("/");
82
101
  const overlayPath = writeModelOverlay(provider ?? "xdpool", modelName ?? "deepseek-v4.1-flash", onOverlay);
83
102
  let proc = null;
@@ -90,12 +109,21 @@ export function makeHeadlessRunner({ profile = "headless", onOverlay = null } =
90
109
  "headless",
91
110
  task,
92
111
  ];
93
- proc = spawn(exe, args, {
112
+ proc = spawnFn(exe, args, {
94
113
  cwd,
95
114
  env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
96
115
  stdio: ["ignore", "pipe", "pipe"],
97
116
  });
98
- return await consumeHeadlessStream(proc, { timeoutMs, maxToolCalls, maxOutputBytes });
117
+ const result = await consumeHeadlessStream(proc, { timeoutMs, maxToolCalls, maxOutputBytes });
118
+ // 探测不可用时(普通 node 看不进 asar)走的是旧布局的老路径,这条提示只在真失败时
119
+ // 附上——成功时多说一句只会让人以为哪里没配好。
120
+ if (!result.ok && !cli.verified && result.kind === "environment") {
121
+ // 候选清单一起带上:只说「未经探测」等于让人重新猜一遍布局,而这轮已经把
122
+ // 探测过哪些路径算出来了(#578 那位用户当初只能靠读源码猜)。
123
+ result.reason += `(CLI 路径未经探测:当前进程看不进 asar,按旧布局 ${cliJs} 处理;`
124
+ + `已探测:${(cli.candidates ?? []).join("、") || "(无候选)"}。若是 DSH NEXT 请设 DSH_CLI_JS)`;
125
+ }
126
+ return result;
99
127
  } catch (err) {
100
128
  return { ok: false, kind: "environment", reason: String(err?.message ?? err) };
101
129
  } finally {
@@ -105,19 +133,60 @@ export function makeHeadlessRunner({ profile = "headless", onOverlay = null } =
105
133
  };
106
134
  }
107
135
 
108
- function locateDshExe() {
109
- if (process.env.DSH_EXE && existsSync(process.env.DSH_EXE)) return process.env.DSH_EXE;
110
- const exePath = process.execPath ?? "";
111
- if (basename(exePath).toLowerCase() === "deepseek harness.exe") return exePath;
112
- const standard = join(process.env["ProgramFiles"] ?? "C:\\Program Files", "DeepSeek Harness", "DeepSeek Harness.exe");
113
- return existsSync(standard) ? standard : null;
136
+ // exe 名白名单:不认「同目录任意 exe」——那只会在装了两套宿主时挑中错的那个。
137
+ // 前两个是现行两种安装布局的名字(DSH NEXT 的 exe 就叫 DSH NEXT.exe),第三个是
138
+ // 历史名字,留着只为不打断已经在用旧版的人。
139
+ const DSH_EXE_NAMES = ["deepseek harness.exe", "dsh next.exe", "dsh.exe"];
140
+
141
+ export function locateDshExe(env = process.env, execPath = process.execPath) {
142
+ if (env.DSH_EXE && existsSync(env.DSH_EXE)) return env.DSH_EXE;
143
+ const exePath = execPath ?? "";
144
+ if (DSH_EXE_NAMES.includes(basename(exePath).toLowerCase())) return exePath;
145
+ // 标准安装位按「两种布局 × 两种名字」逐个试。issue #578:DSH NEXT 装在别处、
146
+ // exe 也不叫 DeepSeek Harness.exe,旧实现两个条件同时不满足 → 直接 environment 失败。
147
+ const roots = [env["ProgramFiles"] ?? "C:\\Program Files", env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)"].filter(Boolean);
148
+ for (const root of roots) {
149
+ for (const name of ["DeepSeek Harness", "DSH NEXT"]) {
150
+ const candidate = join(root, name, `${name}.exe`);
151
+ if (existsSync(candidate)) return candidate;
152
+ }
153
+ }
154
+ return null;
114
155
  }
115
156
 
116
- function locateCliJs(exe) {
117
- // cli.js 固定在 exe 相对路径的 app.asar 内部。**不能 existsSync 校验**:CLI 进程
118
- // 是普通 node,没有 asar 支持 stat 不进包内——而 exe 自己(V1 实测)加载这个
119
- // 路径没问题。位置是安装器定的,直接给出去。
120
- return join(dirname(exe), "resources", "app.asar", "dsh", "node_modules", "@deepseek-ai", "dsh-desktop-host", "lib", "cli.js");
157
+ // cli.js 在 app.asar 内部,位置随安装布局变(issue #578 的核心):旧布局多一层
158
+ // `dsh/`,DSH NEXT 直接放在 `lib/desktop-cli.js`。所以这里是**按优先级探测**,
159
+ // 不再硬编码单一路径。
160
+ //
161
+ // 关于「不能 existsSync」那条旧注释:它对 CLI 子进程成立(普通 node 没有 asar
162
+ // 补丁),但**探测发生在插件进程里**(Electron 主进程 / ELECTRON_RUN_AS_NODE 子
163
+ // 进程,两者都给 fs 打了 asar 补丁)——本机实测 statSync/readFileSync 对 asar 内
164
+ // 路径都正常工作。探测不到时(比如被测进程是裸 node)退回旧布局那条老路径并标记
165
+ // verified:false,让失败信息自己说明「这次没探测」。
166
+ export function resolveCliJs(exe, env = process.env) {
167
+ const base = dirname(exe);
168
+ const asar = join(base, "resources", "app.asar");
169
+ // DSH_CLI_JS 是**人明确指定**的答案,不是一条待排序的候选:指定了就不许再猜。
170
+ // 回退到别的候选会让人以为自己的设置生效了——实际跑的却是另一份 CLI,症状是
171
+ // 「我明明指了 NEXT 的 cli,报错里还是旧布局路径」。指定了但不存在 → 直接失败,
172
+ // 让错误信息如实指向他写的那个路径。
173
+ const explicit = typeof env.DSH_CLI_JS === "string" && env.DSH_CLI_JS !== "" ? env.DSH_CLI_JS : null;
174
+ const candidates = [
175
+ explicit,
176
+ join(asar, "lib", "desktop-cli.js"),
177
+ join(asar, "dsh", "node_modules", "@deepseek-ai", "dsh-desktop-host", "lib", "cli.js"),
178
+ join(asar, "node_modules", "@deepseek-ai", "dsh-desktop-host", "lib", "cli.js"),
179
+ ].filter((c) => typeof c === "string" && c !== "");
180
+ if (explicit !== null) {
181
+ if (existsSync(explicit)) return { path: explicit, candidates, verified: true };
182
+ return { path: null, candidates, verified: false, explicitMissing: explicit };
183
+ }
184
+ for (const candidate of candidates) {
185
+ if (existsSync(candidate)) return { path: candidate, candidates, verified: true };
186
+ }
187
+ // 全部探测失败:把**旧布局**那条老路径交出去(它曾是唯一答案,老真机上大概率还是
188
+ // 它),但如实带上 verified:false 与完整候选清单——猜错时失败信息里得看得见试过什么。
189
+ return { path: join(asar, "dsh", "node_modules", "@deepseek-ai", "dsh-desktop-host", "lib", "cli.js"), candidates, verified: false };
121
190
  }
122
191
 
123
192
  // overlay 只含 provider/model 名(红线 4:不落 key);一次性临时目录,finally 里删。
@@ -137,6 +206,9 @@ function writeModelOverlay(provider, model, onOverlay) {
137
206
  return p;
138
207
  }
139
208
 
209
+ // stderr 尾巴上限:够装下一条栈顶报错,又不至于把几万行 usage 全端上来。
210
+ const STDERR_TAIL_LIMIT = 4096;
211
+
140
212
  // NDJSON 事件流消费:三重上限在读取循环里计数,超限 kill。headless --json 的事件
141
213
  // 形状以宿主实现为准——工具调用按「事件名含 tool_call/tool_use」的宽匹配计数,
142
214
  // 计不出就退化为只用 timeout/bytes 两道上限(如实降级,不假装第三道存在)。
@@ -147,6 +219,7 @@ function consumeHeadlessStream(proc, { timeoutMs, maxToolCalls, maxOutputBytes }
147
219
  let toolCalls = 0;
148
220
  let scannedLines = 0; // 已计过数的完整行数——每块只扫新增部分,否则事件被平方级重复计数(实测 11s 撞 40 上限的假象就是这么来的)
149
221
  let timedOut = false;
222
+ let stderrTail = "";
150
223
  const timer = setTimeout(() => {
151
224
  timedOut = true;
152
225
  proc.kill();
@@ -183,15 +256,22 @@ function consumeHeadlessStream(proc, { timeoutMs, maxToolCalls, maxOutputBytes }
183
256
  }
184
257
  scannedLines = complete;
185
258
  });
186
- proc.stderr.on("data", () => { /* 诊断进 stderr,不影响结果 */ });
259
+ // stderr 必须收:headless 起不来时真正的原因(缺 credential、NO_ADAPTER、模块解析
260
+ // 失败、CLI 路径不存在)全在这里,而 stdout 一个字都没有——issue #578 的「(无输出)」
261
+ // 就是这么来的。只留尾巴(4 KiB)且不参与成败判定,纯诊断。
262
+ proc.stderr.on("data", (chunk) => {
263
+ stderrTail = (stderrTail + chunk.toString("utf8")).slice(-STDERR_TAIL_LIMIT);
264
+ });
187
265
  proc.on("error", (err) => finish({ ok: false, kind: "environment", reason: `spawn 失败:${String(err?.message ?? err)}` }));
188
266
  proc.on("close", (code) => {
189
267
  if (timedOut) { finish({ ok: false, kind: "module", reason: `超过 ${timeoutMs}ms 墙钟上限` }); return; }
190
268
  // 最终答案:--json 流里最后一个非事件行;流解析失败就取 stdout 去掉事件行后的文本。
191
269
  const text = extractFinalText(out);
192
270
  if (code !== 0) {
193
- const envHint = /MISSING_CREDENTIAL|NO_ADAPTER|UNKNOWN_MODEL|EADDR|cannot find/i.test(out) ? "environment" : "module";
194
- finish({ ok: false, kind: envHint, reason: `headless 退出码 ${code}:${(text || "").slice(0, 200) || "(无输出)"}` });
271
+ const envHint = /MISSING_CREDENTIAL|NO_ADAPTER|UNKNOWN_MODEL|EADDR|cannot find/i.test(out + stderrTail) ? "environment" : "module";
272
+ // 诊断优先取 stderr 尾巴:失败时 stdout 常常是空的,而原因都在 stderr。
273
+ const detail = (text || "").slice(0, 200) || stderrTail.trim().slice(-400) || "(无输出)";
274
+ finish({ ok: false, kind: envHint, reason: `headless 退出码 ${code}:${detail}` });
195
275
  return;
196
276
  }
197
277
  if (!text.trim()) { finish({ ok: false, kind: "module", reason: "headless 没有产出可解析的最终回答" }); return; }
@@ -286,10 +366,18 @@ export function createT1({ store, runSession = null, limits = DEFAULT_LIMITS, no
286
366
  skipped,
287
367
  t1Unavailable: null,
288
368
  };
369
+ // --dsh-exe 只影响这一轮:原来写进 process.env 就不还了,同一进程里后续任何一次
370
+ // 定位都会继承它(面板里切仓库、换个布局都还是旧值),属于会记很久的脏状态。
289
371
  const runnerWithExe = dshExe
290
372
  ? async (call) => {
373
+ const saved = process.env.DSH_EXE;
291
374
  process.env.DSH_EXE = dshExe;
292
- return runner(call);
375
+ try {
376
+ return await runner(call);
377
+ } finally {
378
+ if (saved === undefined) delete process.env.DSH_EXE;
379
+ else process.env.DSH_EXE = saved;
380
+ }
293
381
  }
294
382
  : runner;
295
383
 
@@ -345,12 +433,18 @@ export function createT1({ store, runSession = null, limits = DEFAULT_LIMITS, no
345
433
 
346
434
  // 富化 + 双落(P19/P20)。写路径断言复用 t0 的机械面语义:只许动
347
435
  // .chorography/** 下的页面与 evidence。
436
+ //
437
+ // verifiedBaseline 必须是**这一刻**的 HEAD:claims 的行号是从这棵代码树上读出来
438
+ // 的,之后判失效只能从它起算。拿不到 HEAD(不是 git 仓库 / git 不在)就记 null,
439
+ // 面板据此说「这一页哪次验证的,不知道」——不退回全仓 git_baseline,那会把
440
+ // 「T1 之前就发生、claim 早已算进去」的改动误报成 touched。
348
441
  const generatedAt = now();
349
- enrichPageFile(pageFile, parsed.sections);
350
- writeEvidenceFile(rootPath, slug, parsed.claims, generatedAt);
442
+ const verifiedBaseline = gitHead(rootPath);
443
+ enrichPageFile(pageFile, parsed.sections, { verifiedBaseline, verifiedAt: generatedAt });
444
+ writeEvidenceFile(rootPath, slug, parsed.claims, generatedAt, verifiedBaseline);
351
445
  store.saveChoroPageClaims(pageRow.id, parsed.claims.map((c) => ({ ...c, createdAt: generatedAt })));
352
- store.markChoroPageEnriched(pageRow.id, generatedAt);
353
- receipt.enriched.push({ slug, sections: Object.keys(parsed.sections), claims: parsed.claims.length });
446
+ store.markChoroPageEnriched(pageRow.id, generatedAt, verifiedBaseline);
447
+ receipt.enriched.push({ slug, sections: Object.keys(parsed.sections), claims: parsed.claims.length, verifiedBaseline });
354
448
  }
355
449
  return receipt;
356
450
  }
@@ -430,7 +524,11 @@ function parseT1Output(text) {
430
524
  }
431
525
 
432
526
  // 富化(P19):剥掉旧 T1 段 → 新段插在「## 生成说明」之前 → 保留区照旧页尾回填。
433
- function enrichPageFile(pageFile, sections) {
527
+ //
528
+ // 顺带把「对着哪个提交验证的」写进 frontmatter(① provenance):这两个键**只有 T1
529
+ // 写**,T0 渲染一个字节都不产出。因此 T0 重跑整页重建时它们随语义段一起消失,
530
+ // 与「T0 丢弃 T1 正文」是同一件事,不新增语义,也不碰 T0 的逐字节确定性。
531
+ function enrichPageFile(pageFile, sections, { verifiedBaseline = null, verifiedAt = null } = {}) {
434
532
  let content = readFileSync(pageFile, "utf8");
435
533
  // 剥旧 T1 段(含标记本身)
436
534
  const wrap = new RegExp(`${escapeRe(T1_SECTION_START)}[\\s\\S]*?${escapeRe(T1_SECTION_END)}\\n?`, "g");
@@ -462,7 +560,13 @@ function enrichPageFile(pageFile, sections) {
462
560
  ? `${content.replace(/\n*$/, "\n")}\n${block}`
463
561
  : content.slice(0, anchor) + block.replace(/^\n/, "") + content.slice(anchor);
464
562
  const { blocks } = extractHumanBlocks(base);
465
- const finalContent = blocks.length > 0 ? injectHumanBlocks(stripHumanBlocks(base), blocks) : base;
563
+ const withHuman = blocks.length > 0 ? injectHumanBlocks(stripHumanBlocks(base), blocks) : base;
564
+ // HUMAN 块是页尾整块,frontmatter 在页首,两者互不干扰;顺序仍按「先回填保留区、
565
+ // 再收尾 frontmatter」,避免 fronts 里的键名与保留区正文同名时被误改。
566
+ const finalContent = setFrontmatterKeys(withHuman, [
567
+ [FM_VERIFIED_BASELINE, verifiedBaseline],
568
+ [FM_VERIFIED_AT, verifiedAt],
569
+ ]);
466
570
  writeFileSync(pageFile, finalContent, "utf8");
467
571
  }
468
572
 
@@ -472,11 +576,14 @@ function stripHumanBlocks(text) {
472
576
  return text.replace(re, "");
473
577
  }
474
578
 
475
- function writeEvidenceFile(repoRoot, slug, claims, generatedAt) {
579
+ function writeEvidenceFile(repoRoot, slug, claims, generatedAt, verifiedBaseline = null) {
476
580
  const rel = `${".chorography"}/evidence/${slug}.json`;
477
581
  const abs = insideChoro(repoRoot, rel);
478
582
  mkdirp(dirname(abs));
479
- writeFileSync(abs, `${JSON.stringify({ slug, generatedAt, claims }, null, 2)}\n`, "utf8");
583
+ // verifiedBaseline 与页面 frontmatter 同源同写:evidence 是给人核的旁证,光有 claims
584
+ // 没有「对着哪个提交」的,事后同样无从复核。
585
+ const body = { slug, generatedAt, verifiedBaseline, claims };
586
+ writeFileSync(abs, `${JSON.stringify(body, null, 2)}\n`, "utf8");
480
587
  }
481
588
 
482
589
  function insideChoro(rootPath, relPath) {
package/package.json CHANGED
@@ -1,8 +1,22 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 10 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.13.0",
4
+ "version": "0.14.0-beta.1",
5
5
  "license": "MIT",
6
+ "keywords": [
7
+ "dsh",
8
+ "dsh-plugin",
9
+ "deepseek-harness",
10
+ "deepseek",
11
+ "memory",
12
+ "agent-memory",
13
+ "long-term-memory",
14
+ "cross-session",
15
+ "recall",
16
+ "consolidation",
17
+ "sqlite",
18
+ "markdown"
19
+ ],
6
20
  "repository": {
7
21
  "type": "git",
8
22
  "url": "git+https://github.com/slow-stack/mneme.git"
@@ -182,6 +182,12 @@ export function sectionOf(text, heading) {
182
182
  export function checkSupportTable(text, version) {
183
183
  const [major, minor] = version.split(".");
184
184
  const expected = `${major}.${minor}.x`;
185
+ // 预发布版(0.14.0-beta.1)不是「受支持的版本」,支持表不该跟着它挪格。
186
+ // 挪了等于对外宣称 0.14 已经在活跃维护——而 beta 随时可能推倒重来。
187
+ // 这里显式标 skipped,调用方据此换一句人话;**不静默通过**:skipped 是返回值的一部分。
188
+ if (version.includes("-")) {
189
+ return { ok: true, expected, problems: [], skipped: "prerelease" };
190
+ }
185
191
  const problems = [];
186
192
  for (const [heading, label] of [
187
193
  ["## Supported Versions", "英文"],
@@ -200,5 +206,5 @@ export function checkSupportTable(text, version) {
200
206
  const found = rows[0].split("|")[1].trim();
201
207
  if (found !== expected) problems.push(`${label}表首行写的是 ${found},应为 ${expected}`);
202
208
  }
203
- return { ok: problems.length === 0, expected, problems };
209
+ return { ok: problems.length === 0, expected, problems, skipped: null };
204
210
  }
@@ -149,7 +149,10 @@ export function renderNotes(sectionText, opts = {}) {
149
149
  /** release.yml 的调用方式:node dsh-mneme/scripts/release-notes.mjs <version>(cwd 为仓库根)。 */
150
150
  function main() {
151
151
  const v = (process.argv[2] || "").replace(/^v/, "");
152
- if (!/^\d+\.\d+\.\d+$/.test(v)) { console.error("usage: release-notes.mjs <version>"); process.exit(1); }
152
+ // 允许预发布后缀:0.14.0-beta.1 是合法发布版本,此前这条守卫把它当非法用法直接 exit 1,
153
+ // 于是 release job 在抽正文这步就红了——预发布版根本发不出去。语义校验交给
154
+ // semver 的形状(x.y.z 后可跟 -标识),不做额外白名单。
155
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v)) { console.error("usage: release-notes.mjs <version>"); process.exit(1); }
153
156
  const md = readFileSync("dsh-mneme/CHANGELOG.md", "utf8");
154
157
  const sec = findSection(md, v);
155
158
  if (!sec) { console.error("changelog section not found: " + v); process.exit(1); }
package/src/api.js CHANGED
@@ -1670,7 +1670,16 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
1670
1670
  // 少了它们,「这条边被抬过」在面板上根本看不出来。取不到时给
1671
1671
  // 初值形状而不是 undefined,前端不必到处判空。
1672
1672
  weight: e.weight ?? 1.0,
1673
- source: e.source ?? "manual"
1673
+ source: e.source ?? "manual",
1674
+ // #619 可见化 B:边上的 metadata 必须原样透传,否则情感边写进去的
1675
+ // emotion / attribution / sessionCount / evidence 在面板上永远取不到
1676
+ // ——数据在库里、在 store.toRelation 里(src/store.js 已 JSON.parse),
1677
+ // 只在最后一跳被这个映射丢掉,读起来就像「这个功能不存在」。
1678
+ // 不裁剪字段:情感边的 metadata 由 sleep 相位写入,形状本来就会随版本
1679
+ // 演进,在 API 层挑字段等于给未来的字段再挖一个同样的坑。
1680
+ // 无 metadata 时给 null,不伪造空对象——前端要靠 null 区分「老边(抽取器
1681
+ // 写的,本来就没有情绪)」和「有 metadata 但没有 emotion」。
1682
+ metadata: e.metadata ?? null
1674
1683
  }))
1675
1684
  });
1676
1685
  } catch {
@@ -1723,6 +1732,92 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
1723
1732
  }
1724
1733
  });
1725
1734
 
1735
+ // --- affective: 情绪归因一览(#619 可见化 C) ---
1736
+ // `ego` 端点只能从某个实体往外看,回答不了「这库里一共记了哪些情绪」。
1737
+ // 所以单开一条:按 person/target/emotion 聚合,occasion 与 trait 分开。
1738
+ //
1739
+ // 三处刻意的选择,都是为了让面板不撒谎:
1740
+ // - 聚键含 attribution(occasion / trait),两类不混在一条里。同一个「焦虑」
1741
+ // 在一件事上是 occasion,跨三件事才是 trait,合成一条会把「这次」说成「一贯」。
1742
+ // - trait 组带 independentSessions(跨几个独立会话)。trait 的判据本来就是会话数,
1743
+ // 面板只显示「稳定倾向」而不给数字,用户没法判断它是攒够了还是被猜测出来的。
1744
+ // - 完全读不到时返回 500 + error,不返回空列表:空列表在面板上长得跟
1745
+ // 「你还没记过任何情绪」一样,而这两件事对用户的含义完全相反。
1746
+ // 前端靠 httpStatusCode 区分,不靠 items.length。
1747
+ register({
1748
+ kind: "exact",
1749
+ path: "/api/dsh-mneme/semantic/graph/affective",
1750
+ policy: "open",
1751
+ handler(req, res) {
1752
+ try {
1753
+ const url = new URL(req.url, "http://localhost");
1754
+ const limit = Math.max(1, Math.min(500, Number(url.searchParams.get("limit") ?? 200) || 200));
1755
+ if (typeof service.relationsByType !== "function") {
1756
+ sendJson(res, 500, { error: "unavailable" });
1757
+ return;
1758
+ }
1759
+ const edges = service.relationsByType("affective_context", limit) ?? [];
1760
+ const groups = new Map();
1761
+ for (const e of edges) {
1762
+ const meta = e.metadata && typeof e.metadata === "object" ? e.metadata : {};
1763
+ const emotion = String(meta.emotion ?? "").trim();
1764
+ // 没有情绪名的边不进聚合:它是老版本或手工写的空壳,凑进「情绪一览」
1765
+ // 会造出一个名字为空的条目。但也不能假装它不存在——计数单列。
1766
+ const attribution = String(meta.attribution ?? "").trim() || "occasion";
1767
+ if (!emotion) continue;
1768
+ const key = `${e.from_entity}\u0000${e.to_entity}\u0000${emotion}\u0000${attribution}`;
1769
+ if (!groups.has(key)) {
1770
+ groups.set(key, {
1771
+ person: e.from_name ?? null,
1772
+ personId: e.from_entity,
1773
+ target: e.to_name ?? null,
1774
+ targetId: e.to_entity,
1775
+ emotion,
1776
+ attribution,
1777
+ promotedToTrait: meta.promotedToTrait === true,
1778
+ sessionCount: Number.isFinite(meta.sessionCount) ? meta.sessionCount : null,
1779
+ traitSessionCount: Number.isFinite(meta.traitSessionCount) ? meta.traitSessionCount : null,
1780
+ evidenceCount: Array.isArray(meta.evidence) ? meta.evidence.length : (e.memory_id ? 1 : 0),
1781
+ firstSeen: e.created_at ?? null,
1782
+ lastSeen: e.created_at ?? null,
1783
+ edgeIds: []
1784
+ });
1785
+ }
1786
+ const g = groups.get(key);
1787
+ g.edgeIds.push(e.id);
1788
+ if (e.created_at && (!g.lastSeen || e.created_at > g.lastSeen)) g.lastSeen = e.created_at;
1789
+ if (e.created_at && (!g.firstSeen || e.created_at < g.firstSeen)) g.firstSeen = e.created_at;
1790
+ if (e.from_name) g.person = e.from_name;
1791
+ if (e.to_name) g.target = e.to_name;
1792
+ if (Number.isFinite(meta.sessionCount)) {
1793
+ g.sessionCount = Math.max(g.sessionCount ?? 0, meta.sessionCount);
1794
+ }
1795
+ if (Number.isFinite(meta.traitSessionCount)) {
1796
+ g.traitSessionCount = Math.max(g.traitSessionCount ?? 0, meta.traitSessionCount);
1797
+ }
1798
+ if (meta.promotedToTrait === true) g.promotedToTrait = true;
1799
+ }
1800
+ const items = [...groups.values()].sort((a, b) => {
1801
+ // trait 在前(更值得看),同类按最近一次出现倒序。
1802
+ if ((b.attribution === "trait") !== (a.attribution === "trait")) {
1803
+ return a.attribution === "trait" ? -1 : 1;
1804
+ }
1805
+ return String(b.lastSeen ?? "").localeCompare(String(a.lastSeen ?? ""));
1806
+ });
1807
+ sendJson(res, 200, {
1808
+ items,
1809
+ // 读到了多少条原始边、其中多少条因为没情绪名没进聚合。给出来是为了
1810
+ // 让「只有 0 条」能自我解释:是库里真没有,还是有边但都不带情绪。
1811
+ totalEdges: edges.length,
1812
+ skippedEdges: edges.length - items.reduce((n, g) => n + g.edgeIds.length, 0),
1813
+ truncated: edges.length >= limit
1814
+ });
1815
+ } catch {
1816
+ sendJson(res, 500, { error: "internal" });
1817
+ }
1818
+ }
1819
+ });
1820
+
1726
1821
  // --- entity attrs: current valid attrs for one entity (graph hover panel) ---
1727
1822
  // Read-only; mirrors getCurrentAttrs (valid_until IS NULL). Also used as the
1728
1823
  // graph panel's fallback list when the ego graph is too sparse to draw.
@@ -2223,6 +2318,38 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
2223
2318
  }
2224
2319
  });
2225
2320
 
2321
+ // GET /conflicts/ledger(issue #641,beta 第三阶段):矛盾分诊账本的只读面——
2322
+ // 分诊分布(按 tier 计数)+ 最近账本行。conflict_ledger 是 bookkeeping 表,
2323
+ // 这里的行不是待办(处置由 enforce 档自动完成),面板只回答「账本里有什么、
2324
+ // 分布如何」。policy 与 /conflicts 同级(token):行带标题级信息与检出时间,
2325
+ // 不该对未持 token 的本地进程开放。
2326
+ register({
2327
+ kind: "exact",
2328
+ path: "/api/dsh-mneme/conflicts/ledger",
2329
+ policy: "token",
2330
+ handler(req, res) {
2331
+ try {
2332
+ if (req.method !== "GET") {
2333
+ sendJson(res, 404, { error: "not-found" });
2334
+ return;
2335
+ }
2336
+ const url = new URL(req.url, "http://localhost");
2337
+ const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
2338
+ const offset = Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0);
2339
+ const items = service.listConflictLedger({ limit, offset });
2340
+ const counts = {
2341
+ dup: service.countConflictLedger({ tier: "dup" }),
2342
+ "cross-scope-dup": service.countConflictLedger({ tier: "cross-scope-dup" }),
2343
+ evolution: service.countConflictLedger({ tier: "evolution" }),
2344
+ conflict: service.countConflictLedger({ tier: "conflict" })
2345
+ };
2346
+ sendJson(res, 200, { items, counts, total: service.countConflictLedger() });
2347
+ } catch {
2348
+ sendJson(res, 500, { error: "internal" });
2349
+ }
2350
+ }
2351
+ });
2352
+
2226
2353
  register({
2227
2354
  kind: "exact",
2228
2355
  path: "/api/dsh-mneme/conflicts/resolve",
@@ -3047,18 +3174,47 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
3047
3174
  // 为什么要 caller 指定 repo:一次面板加载若把 5 个 stale 仓库全扫一遍,用户只是
3048
3175
  // 打开一个页面却付了 5 次全仓扫描;列表路径只在 ?repo= 明确点名时才刷。
3049
3176
  function autoRefreshOne(repoId, facts) {
3050
- const result = { autoRefreshed: false, autoRefreshError: undefined, repo: facts };
3177
+ const result = {
3178
+ autoRefreshed: false,
3179
+ autoRefreshError: undefined,
3180
+ // autoRefreshSkipped 与 autoRefreshError 是两件事:前者是「我们主动没做」,
3181
+ // 后者是「试了但失败了」。混成一个字段会让面板把一次正确的拒绝说成故障。
3182
+ autoRefreshSkipped: undefined,
3183
+ autoRefreshSkipNote: undefined,
3184
+ repo: facts
3185
+ };
3051
3186
  if (!config || config.chorographyAutoRefresh !== true) return result;
3052
3187
  if (!facts || facts.staleReason !== "git") return result;
3053
3188
  if (typeof choro.runT0Apply !== "function") return result;
3189
+ // 有富化页时先别动手:读侧刷新只该刷新「确定性骨架」,不该在用户点开一页时
3190
+ // 顺手把语义段(花模型调用换来的)连同 claims 一起清掉。T0 自己也会拒绝
3191
+ // (guardT1Loss),这里提前拦一道是为了给面板一句能直接显示的人话,
3192
+ // 并且不进 warn 日志——这不是异常。
3193
+ if (Number(facts.enrichedPages ?? 0) > 0) {
3194
+ result.autoRefreshSkipped = "t1-loss";
3195
+ result.autoRefreshSkipNote =
3196
+ `这个仓库有 ${facts.enrichedPages} 页已经富化过:自动刷新会退回骨架、清空语义段与结论,`
3197
+ + "所以这次没有动。代码已变这件事仍然有效,需要新快照请在面板里手动点「重建骨架」。";
3198
+ return result;
3199
+ }
3054
3200
  try {
3055
- choro.runT0Apply({ repoRoot: facts.rootPath });
3201
+ // guardT1Loss 必须显式传:库里的 enrichedPages 只是第一道提示(快、能生成人话),
3202
+ // 真正读盘判断「会丢哪几页」的是 T0 自己。不传给 T0 等于把唯一的硬守卫关掉。
3203
+ choro.runT0Apply({ repoRoot: facts.rootPath, guardT1Loss: true });
3056
3204
  result.autoRefreshed = true;
3057
3205
  // 重跑之后基线推进了,回执里的 stale 必须按新基线说话:沿用旧行的判定会让
3058
3206
  // 面板刚刷完就显示「代码已变」,也就是谎报一次失败。
3059
3207
  const fresh = typeof choro.repoFactsById === "function" ? choro.repoFactsById(repoId) : null;
3060
3208
  if (fresh) result.repo = fresh;
3061
3209
  } catch (err) {
3210
+ // would-drop-t1 是 T0 侧的同一条判断(它读盘,比这里的库计数更准):
3211
+ // 到这一层说明库里的 enrichedPages 和磁盘上的实际情况对不上,仍按「主动跳过」
3212
+ // 处理并把人话透出去,绝不报成刷新失败。
3213
+ if (err?.code === "would-drop-t1") {
3214
+ result.autoRefreshSkipped = "t1-loss";
3215
+ result.autoRefreshSkipNote = String(err?.message ?? err);
3216
+ return result;
3217
+ }
3062
3218
  result.autoRefreshError = String(err?.message ?? err);
3063
3219
  ctx.logger?.warn?.(`dsh-mneme: choro auto refresh failed for repo ${repoId}: ${result.autoRefreshError}`);
3064
3220
  }
@@ -3078,6 +3234,8 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
3078
3234
  const repoParam = new URL(req.url, "http://localhost").searchParams.get("repo");
3079
3235
  let autoRefreshed = false;
3080
3236
  let autoRefreshError;
3237
+ let autoRefreshSkipped;
3238
+ let autoRefreshSkipNote;
3081
3239
  if (repoParam !== null && repoParam !== "") {
3082
3240
  const target = choro.resolveRepo(repoParam);
3083
3241
  if (target && !target.ambiguous) {
@@ -3086,13 +3244,15 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
3086
3244
  const refreshed = autoRefreshOne(target.id, repos[idx]);
3087
3245
  autoRefreshed = refreshed.autoRefreshed;
3088
3246
  autoRefreshError = refreshed.autoRefreshError;
3247
+ autoRefreshSkipped = refreshed.autoRefreshSkipped;
3248
+ autoRefreshSkipNote = refreshed.autoRefreshSkipNote;
3089
3249
  if (refreshed.repo) repos[idx] = refreshed.repo;
3090
3250
  }
3091
3251
  }
3092
3252
  }
3093
3253
  // cliCommand(#607):面板空态直接把它贴出来,用户复制即用。推导不出
3094
3254
  // 入口时为 null,面板据此退回通用说法(不硬编一个假路径)。
3095
- sendJson(res, 200, { repos, autoRefreshed, autoRefreshError, cliCommand: CHORO_CLI });
3255
+ sendJson(res, 200, { repos, autoRefreshed, autoRefreshError, autoRefreshSkipped, autoRefreshSkipNote, cliCommand: CHORO_CLI });
3096
3256
  }
3097
3257
  });
3098
3258
 
@@ -3161,10 +3321,15 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
3161
3321
  stale: repoNow.stale,
3162
3322
  staleReason: repoNow.staleReason,
3163
3323
  legacy: repoNow.legacy,
3324
+ // 面板要靠它解释「为什么这次自动刷新没动」——它是主动拒绝的依据,
3325
+ // 不是内部账本,所以随读页一起回。
3326
+ enrichedPages: repoNow.enrichedPages ?? 0,
3164
3327
  lastRunAt: repoNow.lastRunAt
3165
3328
  } : { id: repo.id, name: repo.name },
3166
3329
  autoRefreshed: refreshed.autoRefreshed,
3167
- autoRefreshError: refreshed.autoRefreshError
3330
+ autoRefreshError: refreshed.autoRefreshError,
3331
+ autoRefreshSkipped: refreshed.autoRefreshSkipped,
3332
+ autoRefreshSkipNote: refreshed.autoRefreshSkipNote
3168
3333
  });
3169
3334
  }
3170
3335
  });
@@ -3201,6 +3366,47 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
3201
3366
  }
3202
3367
  });
3203
3368
 
3369
+ // Claim 粒度失效清单(借 openwiki 的 Grounded Claims)。只读、policy open,
3370
+ // 与其余 choro 读路由同级。
3371
+ //
3372
+ // 为什么不落库:判据是 git diff × claims 三列证据的纯机械比对,一次几十毫秒。
3373
+ // 落库就多一份要失效的缓存,而它唯一的消费者(面板)本来就是打开时现读。
3374
+ // 写路径一条不加,spec §4 的红线(生成只走 CLI)不动。
3375
+ //
3376
+ // 响应三态刻意分开,别让面板把「算不出来」说成「没事」:
3377
+ // 200 clean:true 基线 == HEAD,确实没变
3378
+ // 200 anchorStale:true 基线认不出 / git 不可读(附 reason)
3379
+ // 200 clean:false 且有 pages 正常算出来了,逐页看 atRisk
3380
+ // 仓库不存在 → 404;chorography 关闭 → 409;queries 未装配 → 503(由 choroGate 给)。
3381
+ register({
3382
+ kind: "exact",
3383
+ path: "/api/dsh-mneme/choro/claims",
3384
+ policy: "open",
3385
+ handler(req, res) {
3386
+ if (!choroGate(req, res)) return;
3387
+ const repo = choroResolveOr4xx(req, res);
3388
+ if (!repo) return;
3389
+ if (typeof choro.claimDrift !== "function") {
3390
+ sendJson(res, 503, { error: "unavailable", reason: "choro-claims-unavailable" });
3391
+ return;
3392
+ }
3393
+ let drift;
3394
+ try {
3395
+ drift = choro.claimDrift(repo.id);
3396
+ } catch (err) {
3397
+ // 读盘(页面正文判 hasT1)可能撞上权限/占用:说清是哪一步炸的,
3398
+ // 不要假装「没有 claim」。
3399
+ sendJson(res, 500, { error: "claims-failed", detail: String(err?.message ?? err) });
3400
+ return;
3401
+ }
3402
+ if (!drift) {
3403
+ sendJson(res, 404, { error: "repo-not-found" });
3404
+ return;
3405
+ }
3406
+ sendJson(res, 200, drift);
3407
+ }
3408
+ });
3409
+
3204
3410
  // 面板重建入口(收尾档 P34):T0 apply 秒级同步回执。
3205
3411
  // policy token-write:写的是仓库磁盘的 .chorography/**,属数据面写。
3206
3412
  //