@modusensus/dsh-mneme 0.12.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 (182) hide show
  1. package/README.md +51 -20
  2. package/bin/dsh-mneme-choro.mjs +9 -1
  3. package/docs/CONFIGURATION.md +47 -6
  4. package/docs/DIRECTORIES.md +114 -0
  5. package/docs/DISTILL.md +64 -0
  6. package/docs/DSH-GO.md +97 -0
  7. package/docs/ENTITIES.md +5 -3
  8. package/docs/FORGET.md +77 -0
  9. package/docs/KB.md +110 -0
  10. package/docs/SLEEP.md +28 -3
  11. package/docs/STORAGE.md +23 -0
  12. package/lib/api-standalone.js +4 -1
  13. package/lib/api.js +788 -30
  14. package/lib/attachment-text.js +122 -0
  15. package/lib/choro-command.js +9 -2
  16. package/lib/client.js +4627 -1409
  17. package/lib/config.js +166 -1
  18. package/lib/continuity.js +7 -6
  19. package/lib/diary/auto.js +190 -0
  20. package/lib/diary/compose.js +440 -0
  21. package/lib/diary/dir.js +59 -0
  22. package/lib/diary/export.js +97 -0
  23. package/lib/diary/index.js +26 -0
  24. package/lib/diary/library.js +189 -0
  25. package/lib/diary/qq-inbox.js +142 -0
  26. package/lib/diary/rollover.js +61 -0
  27. package/lib/diary/session-provider.js +122 -0
  28. package/lib/dream/decisions.js +95 -6
  29. package/lib/dream/sleep.js +760 -19
  30. package/lib/dream/triage.js +139 -0
  31. package/lib/dream.js +168 -21
  32. package/lib/dsh-go/host.js +162 -0
  33. package/lib/dsh-go/panel.js +2091 -0
  34. package/lib/dsh-go/text.js +342 -0
  35. package/lib/dsh-go/views/common.js +68 -0
  36. package/lib/dsh-go/views/entity.js +48 -0
  37. package/lib/dsh-go/views/memory.js +198 -0
  38. package/lib/dsh-go/views/root.js +30 -0
  39. package/lib/dsh-go/views/settings.js +398 -0
  40. package/lib/dsh-go/views/status.js +51 -0
  41. package/lib/embedding.js +42 -8
  42. package/lib/entities/extractor.js +36 -7
  43. package/lib/hot-memory.js +22 -11
  44. package/lib/index.js +123 -3
  45. package/lib/inject.js +203 -20
  46. package/lib/kb/index.js +309 -0
  47. package/lib/kb/routes.js +220 -0
  48. package/lib/kb/tools.js +148 -0
  49. package/lib/lang.js +98 -4
  50. package/lib/peak-hours.js +57 -2
  51. package/lib/semantic.js +347 -60
  52. package/lib/service.js +268 -69
  53. package/lib/settings.js +128 -15
  54. package/lib/store.js +585 -26
  55. package/lib/summarize.js +38 -11
  56. package/lib/tools.js +35 -4
  57. package/lib/user-settings.js +128 -32
  58. package/lib/vector-index.js +76 -6
  59. package/lib/wiki/claims.js +267 -0
  60. package/lib/wiki/cli-hint.js +90 -0
  61. package/lib/wiki/queries.js +282 -2
  62. package/lib/wiki/render.js +74 -0
  63. package/lib/wiki/t0.js +43 -6
  64. package/lib/wiki/t1-jobs.js +232 -0
  65. package/lib/wiki/t1.js +145 -32
  66. package/package.json +39 -1
  67. package/scripts/release-docs.mjs +7 -1
  68. package/scripts/release-notes.mjs +4 -1
  69. package/src/api-standalone.js +4 -1
  70. package/src/api.js +788 -30
  71. package/src/attachment-text.js +122 -0
  72. package/src/choro-command.js +9 -2
  73. package/src/config.js +166 -1
  74. package/src/continuity.js +7 -6
  75. package/src/diary/auto.js +190 -0
  76. package/src/diary/compose.js +440 -0
  77. package/src/diary/dir.js +59 -0
  78. package/src/diary/export.js +97 -0
  79. package/src/diary/index.js +26 -0
  80. package/src/diary/library.js +189 -0
  81. package/src/diary/qq-inbox.js +142 -0
  82. package/src/diary/rollover.js +61 -0
  83. package/src/diary/session-provider.js +122 -0
  84. package/src/dream/decisions.js +95 -6
  85. package/src/dream/sleep.js +760 -19
  86. package/src/dream/triage.js +139 -0
  87. package/src/dream.js +168 -21
  88. package/src/dsh-go/host.js +162 -0
  89. package/src/dsh-go/panel.js +2091 -0
  90. package/src/dsh-go/text.js +342 -0
  91. package/src/dsh-go/views/common.js +68 -0
  92. package/src/dsh-go/views/entity.js +48 -0
  93. package/src/dsh-go/views/memory.js +198 -0
  94. package/src/dsh-go/views/root.js +30 -0
  95. package/src/dsh-go/views/settings.js +398 -0
  96. package/src/dsh-go/views/status.js +51 -0
  97. package/src/embedding.js +42 -8
  98. package/src/entities/extractor.js +36 -7
  99. package/src/hot-memory.js +22 -11
  100. package/src/index.js +123 -3
  101. package/src/inject.js +203 -20
  102. package/src/kb/index.js +309 -0
  103. package/src/kb/routes.js +220 -0
  104. package/src/kb/tools.js +148 -0
  105. package/src/lang.js +98 -4
  106. package/src/peak-hours.js +57 -2
  107. package/src/semantic.js +347 -60
  108. package/src/service.js +268 -69
  109. package/src/settings.js +128 -15
  110. package/src/store.js +585 -26
  111. package/src/summarize.js +38 -11
  112. package/src/tools.js +35 -4
  113. package/src/user-settings.js +128 -32
  114. package/src/vector-index.js +76 -6
  115. package/src/wiki/claims.js +267 -0
  116. package/src/wiki/cli-hint.js +90 -0
  117. package/src/wiki/queries.js +282 -2
  118. package/src/wiki/render.js +74 -0
  119. package/src/wiki/t0.js +43 -6
  120. package/src/wiki/t1-jobs.js +232 -0
  121. package/src/wiki/t1.js +145 -32
  122. package/test/api-routes-gaps.test.js +63 -0
  123. package/test/api.test.js +385 -4
  124. package/test/attachment-text.test.js +140 -0
  125. package/test/bm25-corpus-cache.test.js +145 -0
  126. package/test/capacity-warning.test.js +262 -0
  127. package/test/client.test.js +1051 -185
  128. package/test/conflict-freeze.test.js +45 -1
  129. package/test/conflict-ledger-enforce.test.js +452 -0
  130. package/test/conflict-ledger.test.js +242 -0
  131. package/test/continuity.test.js +8 -1
  132. package/test/contrast.test.js +124 -12
  133. package/test/diary-library.test.js +187 -0
  134. package/test/diary.test.js +576 -0
  135. package/test/dream-baseline-clamp.test.js +174 -0
  136. package/test/dream-maxtokens-fallback.test.js +3 -3
  137. package/test/dream.test.js +62 -1
  138. package/test/dsh-go-host.test.js +134 -0
  139. package/test/dsh-go-panel-actions.test.js +854 -0
  140. package/test/dsh-go-panel.test.js +251 -0
  141. package/test/embedding-ready.test.js +33 -3
  142. package/test/entities.test.js +73 -0
  143. package/test/forget-corrections.test.js +70 -0
  144. package/test/graph-api.test.js +124 -0
  145. package/test/hot-memory.test.js +48 -0
  146. package/test/image-memory.test.js +171 -0
  147. package/test/inject-parent-gate.test.js +6 -3
  148. package/test/inject.test.js +59 -0
  149. package/test/issue-617-step1-query-and-fusion.test.js +361 -0
  150. package/test/kb-api-wiring.test.js +128 -0
  151. package/test/kb-collections.test.js +272 -0
  152. package/test/kb-routes.test.js +379 -0
  153. package/test/mint-source.test.js +26 -0
  154. package/test/panel-chart-scale.test.js +90 -0
  155. package/test/panel-tokens.test.js +245 -0
  156. package/test/peak-hours-observability.test.js +70 -0
  157. package/test/persona-api.test.js +3 -3
  158. package/test/persona-by-session.test.js +568 -0
  159. package/test/persona-settings.test.js +7 -7
  160. package/test/reflection-update-gate.test.js +129 -0
  161. package/test/reindex-backfill.test.js +334 -0
  162. package/test/reindex-scheduler.test.js +369 -0
  163. package/test/release-docs.test.js +20 -0
  164. package/test/release-notes.test.js +25 -0
  165. package/test/scope-candidates.test.js +249 -0
  166. package/test/security-doc.test.js +10 -0
  167. package/test/sleep-action-set.test.js +14 -0
  168. package/test/sleep-heat.test.js +49 -0
  169. package/test/sleep.test.js +635 -0
  170. package/test/standalone-api.test.js +24 -0
  171. package/test/store.test.js +20 -0
  172. package/test/summarize.test.js +26 -0
  173. package/test/user-settings-segments.test.js +528 -0
  174. package/test/vector-index.test.js +120 -6
  175. package/test/wiki-api.test.js +463 -1
  176. package/test/wiki-claims.test.js +194 -0
  177. package/test/wiki-cli-hint.test.js +118 -0
  178. package/test/wiki-provenance.test.js +202 -0
  179. package/test/wiki-queries.test.js +128 -0
  180. package/test/wiki-t0.test.js +77 -1
  181. package/test/wiki-t1-jobs.test.js +125 -0
  182. package/test/wiki-t1.test.js +226 -1
@@ -257,12 +257,86 @@ test("重跑 T0 覆盖已富化的页:必须先出声(t1Loss 清点 + warnin
257
257
  }
258
258
  });
259
259
 
260
+ // 读不出来 ≠ 没有:清点靠读盘,读失败就先不知道那页有没有语义段。旧实现在 catch 里
261
+ // 直接当「没有」,guard 于是放行,replaceChoroGraph 把读不到的页连同它可能有的语义段
262
+ // 一起退回骨架、claims 清空——一次权限错误就能静默抹掉一整页富化成果。
263
+ // 这条锁的是:读失败必须进 unreadable、必须拒绝刷新、必须在 receipt 里说出来。
264
+ test("collectT1Loss 读页失败:进 unreadable,guard 拒绝刷新,绝不静默放行", () => {
265
+ const root = makeFixture();
266
+ const store = createStore(":memory:");
267
+ try {
268
+ runChoroT0({ repoRoot: root, store, apply: true, now: FIXED_NOW });
269
+ const pagePath = join(root, ".chorography", "modules", "src.md");
270
+ writeFileSync(pagePath,
271
+ `${readFileSync(pagePath, "utf8")}\n${T1_SECTION_START}\n## 架构\n\na.js 是入口。\n${T1_SECTION_END}\n`,
272
+ "utf8");
273
+ // 用「同名目录顶掉文件」制造真实的读失败:existsSync 为真(目录存在),
274
+ // readFileSync 抛 EISDIR。比 chmod 稳(Windows 上 chmod 不生效),也不依赖权限。
275
+ rmSync(pagePath, { force: true });
276
+ mkdirSync(pagePath, { recursive: true });
277
+
278
+ const dry = runChoroT0({ repoRoot: root, store, now: FIXED_NOW });
279
+ assert.ok(Array.isArray(dry.t1Loss.unreadable) && dry.t1Loss.unreadable.length > 0,
280
+ "读不出来的页必须被点名,不能当成「没有 T1 段」");
281
+ assert.equal(dry.t1Loss.unreadable[0].reason, "EISDIR", "记下读失败的原因,便于归因");
282
+ assert.ok(dry.warnings.some((w) => w.includes("读不出来")), "dry-run 也要如实说一声");
283
+
284
+ assert.throws(
285
+ () => runChoroT0({ repoRoot: root, store, apply: true, guardT1Loss: true, now: () => "2026-11-09T00:00:00.000Z" }),
286
+ (err) => err instanceof ChoroRefusal && err.code === "would-drop-t1" && /读不出来/.test(err.message),
287
+ "读不出内容时无法证明它没有语义段 → 拒绝刷新,而不是赌一把"
288
+ );
289
+ } finally {
290
+ store.close();
291
+ rmTempBestEffort(root);
292
+ }
293
+ });
294
+
295
+ // guardT1Loss(自动刷新专用):读侧「顺手」重跑 T0 会在用户只点开一页的时候
296
+ // 替他丢掉语义段与 claims——那是破坏性写盘,不是刷新。这条锁三件事:
297
+ // ① 有 T1 段时 apply 整轮拒绝(would-drop-t1),一个字节都不写、claims 一条不少;
298
+ // ② 拒绝发生在写盘之前,页里 T1 段还在(拒绝不能只拒一半);
299
+ // ③ 不传 guardT1Loss 的老路径行为不变(手动重建就是用户明确要的那次写)。
300
+ test("guardT1Loss:自动刷新遇到已富化的页就整轮拒绝,不写字节也不清 claims", () => {
301
+ const root = makeFixture();
302
+ const store = createStore(":memory:");
303
+ try {
304
+ runChoroT0({ repoRoot: root, store, apply: true, now: FIXED_NOW });
305
+ const pagePath = join(root, ".chorography", "modules", "src.md");
306
+ writeFileSync(pagePath,
307
+ `${readFileSync(pagePath, "utf8")}\n${T1_SECTION_START}\n## 架构\n\na.js 是入口。\n${T1_SECTION_END}\n`,
308
+ "utf8");
309
+ // 库里也造一条 claim:拒绝必须让它原样躺着。
310
+ const repoRow = store.choroRepoByRoot(root);
311
+ const pageRow = store.choroPageBySlug(repoRow.id, "src");
312
+ store.saveChoroPageClaims(pageRow.id, [{ statement: "a.js 是入口", kind: "architecture", sourcePath: "src/a.js", startLine: 1, endLine: 4, createdAt: FIXED_NOW() }]);
313
+ const beforeBytes = readFileSync(pagePath, "utf8");
314
+
315
+ assert.throws(
316
+ () => runChoroT0({ repoRoot: root, store, apply: true, guardT1Loss: true, now: () => "2026-11-09T00:00:00.000Z" }),
317
+ (err) => err instanceof ChoroRefusal && err.code === "would-drop-t1" && /src/.test(err.message),
318
+ "有富化页时拒绝,且点名是哪一页"
319
+ );
320
+ assert.equal(readFileSync(pagePath, "utf8"), beforeBytes, "拒绝发生在写盘之前:页一字节未动");
321
+ assert.equal(store.db.prepare("SELECT COUNT(*) AS c FROM choro_claims").get().c, 1, "claims 一条不少");
322
+ assert.notEqual(store.choroPageBySlug(repoRow.id, "src").status, "enriched", "拒绝时不该顺手把页标成富化");
323
+
324
+ // 老路径(手动重建)行为不变:它照样退回骨架,只是回执里会说一声。
325
+ const manual = runChoroT0({ repoRoot: root, store, apply: true, now: () => "2026-11-10T00:00:00.000Z" });
326
+ assert.deepEqual(manual.t1Loss.pages, [".chorography/modules/src.md"], "手动路径仍按设计丢弃并清点");
327
+ } finally {
328
+ store.close();
329
+ rmTempBestEffort(root);
330
+ }
331
+ });
332
+
260
333
  // CLI 的 --timeout 是「秒」,一路乘 1000 变成 spawn 的 timeoutMs。NaN 混进去不会
261
334
  // 报错,只会让墙钟上限静默失效——用户以为设了 60 秒,实际跑到 4 分钟默认值。
262
335
  test("CLI 解析:--t1 相关旗标取到值,--timeout 只收正数秒", () => {
263
336
  const { flags } = parseArgv([
264
337
  "D:/repo", "--t1", "--apply", "--module", "src", "--model", "xdpool/m",
265
- "--timeout", "60", "--retry-failed", "--dsh-exe", "D:/Harness.exe", "--json",
338
+ "--timeout", "60", "--retry-failed", "--dsh-exe", "D:/Harness.exe",
339
+ "--dsh-cli", "D:/cli.js", "--json",
266
340
  ]);
267
341
  assert.equal(flags.t1, true);
268
342
  assert.equal(flags.apply, true);
@@ -271,6 +345,8 @@ test("CLI 解析:--t1 相关旗标取到值,--timeout 只收正数秒", () =
271
345
  assert.equal(flags.timeout, 60, "解析出来就是数字,接线处不再二次转换");
272
346
  assert.equal(flags.retryFailed, true);
273
347
  assert.equal(flags["dsh-exe"], "D:/Harness.exe");
348
+ // --dsh-cli 是 issue #578 的人工出口(探测不进 asar 时的唯一办法),必须能取到值
349
+ assert.equal(flags["dsh-cli"], "D:/cli.js");
274
350
  assert.throws(() => parseArgv(["--t1", "--timeout", "abc"]), /正数秒/);
275
351
  assert.throws(() => parseArgv(["--t1", "--timeout", "0"]), /正数秒/);
276
352
  assert.throws(() => parseArgv(["--t1", "--timeout"]), /需要一个秒数/);
@@ -0,0 +1,125 @@
1
+ // T1 面板后台任务状态机的回归锁(契约 §3.2)。
2
+ //
3
+ // **绝不真起进程**:T1 一次要花模型额度,测试里注入假 spawn 就够——这一层要证明的
4
+ // 是「记账与状态迁移对不对」,不是「模型跑得通不通」(那是 CLI 的 e2e 地盘)。
5
+ import test from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { EventEmitter } from "node:events";
8
+ import { createT1Jobs } from "../src/wiki/t1-jobs.js";
9
+
10
+ // 假子进程:stdout/stderr 是 EventEmitter,close/error 也走事件——形状贴着真
11
+ // ChildProcess,但一个字节都不会真跑出去。
12
+ function fakeSpawn() {
13
+ const calls = [];
14
+ const spawn = (cmd, args, opts) => {
15
+ const child = new EventEmitter();
16
+ child.stdout = new EventEmitter();
17
+ child.stderr = new EventEmitter();
18
+ child.stdout.setEncoding = () => {};
19
+ child.stderr.setEncoding = () => {};
20
+ child.killed = false;
21
+ child.kill = () => { child.killed = true; };
22
+ child.cmd = cmd;
23
+ child.args = args;
24
+ child.opts = opts;
25
+ calls.push(child);
26
+ return child;
27
+ };
28
+ return { spawn, calls };
29
+ }
30
+
31
+ function makeJobs(overrides = {}) {
32
+ const fake = fakeSpawn();
33
+ const jobs = createT1Jobs({
34
+ spawn: fake.spawn,
35
+ nodePath: "node",
36
+ scriptPath: "/pkg/bin/dsh-mneme-choro.mjs",
37
+ dbPath: "/mem/memory.db",
38
+ now: (() => { let i = 0; return () => `T${++i}`; })(),
39
+ ...overrides
40
+ });
41
+ return { jobs, calls: fake.calls };
42
+ }
43
+
44
+ const repo = { id: 1, name: "r", root_path: "/repo" };
45
+
46
+ test("start:起的是 CLI 的 --t1 --apply --json(面板必须带 apply,否则 CLI 只列候选不写)", () => {
47
+ const { jobs, calls } = makeJobs();
48
+ const r = jobs.start({ repo, module: "src", retryFailed: true });
49
+ assert.equal(r.started, true);
50
+ assert.ok(r.jobId);
51
+ assert.equal(calls.length, 1);
52
+ const [cmd, args, opts] = [calls[0].cmd, calls[0].args, calls[0].opts];
53
+ assert.equal(cmd, "node");
54
+ assert.deepEqual(args.slice(0, 5), ["/pkg/bin/dsh-mneme-choro.mjs", "/repo", "--t1", "--apply", "--json"]);
55
+ assert.ok(args.includes("--module") && args.includes("src"));
56
+ assert.ok(args.includes("--retry-failed"));
57
+ assert.ok(args.includes("--db") && args.includes("/mem/memory.db"));
58
+ // Electron 宿主里不设这个变量会去开窗口而不是跑脚本——这条是踩过的坑。
59
+ assert.equal(opts.env.ELECTRON_RUN_AS_NODE, "1");
60
+ assert.deepEqual(opts.stdio, ["ignore", "pipe", "pipe"]);
61
+ jobs.dispose();
62
+ });
63
+
64
+ test("同一仓库并发 → job-running 且带回在跑的 jobId(面板据此继续轮询而不是重起)", () => {
65
+ const { jobs } = makeJobs();
66
+ const first = jobs.start({ repo });
67
+ const second = jobs.start({ repo });
68
+ assert.equal(second.started, false);
69
+ assert.equal(second.code, "job-running");
70
+ assert.equal(second.jobId, first.jobId);
71
+
72
+ // 不同仓库互不影响:并发闸是按仓库的,不是全局的。
73
+ const other = jobs.start({ repo: { id: 2, name: "o", root_path: "/repo2" } });
74
+ assert.equal(other.started, true);
75
+ jobs.dispose();
76
+ });
77
+
78
+ test("stdout 逐行进 logTail(封顶 200 行),chunk 切在一行中间也不丢字", async () => {
79
+ const { jobs, calls } = makeJobs();
80
+ const { jobId } = jobs.start({ repo });
81
+ const child = calls[0];
82
+ // 故意把一行拆成两个 chunk:不做余量拼接的实现会把它切成两条假日志。
83
+ child.stdout.emit("data", "第一行\n第二");
84
+ child.stdout.emit("data", "行\n");
85
+ let view = jobs.status(jobId);
86
+ assert.deepEqual(view.logTail, ["第一行", "第二行"]);
87
+
88
+ for (let i = 0; i < 300; i += 1) child.stdout.emit("data", `l${i}\n`);
89
+ view = jobs.status(jobId);
90
+ assert.equal(view.logTail.length, 200, "ring buffer 封顶:长任务 stdout 不封顶就是内存泄漏");
91
+ assert.equal(view.logTail[199], "l299", "留下的是最新的尾巴(面板要看的是当前在干嘛)");
92
+ jobs.dispose();
93
+ });
94
+
95
+ test("退出码 0 → done 且从回执读出进度;非 0 → failed 且带 stderr 尾巴", () => {
96
+ const { jobs, calls } = makeJobs();
97
+ const ok = jobs.start({ repo });
98
+ // CLI --json 输出的是多行 JSON(不是 NDJSON):按行收日志、按全文解析回执,两条路
99
+ // 各走各的,才不会互相牺牲。
100
+ calls[0].stdout.emit("data", JSON.stringify({ dryRun: false, enriched: [{ slug: "a" }], failed: [{ slug: "b" }] }, null, 2));
101
+ calls[0].emit("close", 0);
102
+ const done = jobs.status(ok.jobId);
103
+ assert.equal(done.state, "done");
104
+ assert.deepEqual(done.modules, { total: 2, done: 1, failed: 1 });
105
+ assert.ok(done.finishedAt);
106
+
107
+ const bad = jobs.start({ repo: { id: 2, name: "o", root_path: "/repo2" } });
108
+ calls[1].stderr.emit("data", "拒绝运行(not-registered):仓库没登记\n");
109
+ calls[1].emit("close", 1);
110
+ const failed = jobs.status(bad.jobId);
111
+ assert.equal(failed.state, "failed");
112
+ // 只报 exit code 等于让面板说「失败了,不知道为啥」——stderr 尾巴才是人话。
113
+ assert.match(failed.error, /not-registered/);
114
+ jobs.dispose();
115
+ });
116
+
117
+ test("未知 jobId → null;dispose 杀掉在跑的进程并清账", () => {
118
+ const { jobs, calls } = makeJobs();
119
+ assert.equal(jobs.status("nope"), null);
120
+ const { jobId } = jobs.start({ repo });
121
+ assert.equal(jobs.status(jobId).state, "running");
122
+ jobs.dispose();
123
+ assert.equal(calls[0].killed, true, "宿主卸载时要带走子进程,不留孤儿");
124
+ assert.equal(jobs.status(jobId), null);
125
+ });
@@ -10,9 +10,10 @@ import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync, existsSync
10
10
  import { tmpdir } from "node:os";
11
11
  import { join } from "node:path";
12
12
  import { execFileSync } from "node:child_process";
13
+ import { EventEmitter } from "node:events";
13
14
  import { runChoroT0 } from "../src/wiki/t0.js";
14
15
  import { createStore } from "../src/store.js";
15
- import { createT1, T1Refusal, T1_SECTION_START, T1_SECTION_END } from "../src/wiki/t1.js";
16
+ import { createT1, T1Refusal, T1_SECTION_START, T1_SECTION_END, makeHeadlessRunner, locateDshExe, resolveCliJs } from "../src/wiki/t1.js";
16
17
 
17
18
  const FIXED_NOW = () => "2026-11-05T12:00:00.000Z";
18
19
 
@@ -233,3 +234,227 @@ test("未登记仓库整轮拒绝(先跑 T0)", async () => {
233
234
  rmTempBestEffort(root);
234
235
  }
235
236
  });
237
+
238
+ /* ------------------------- 定位层(issue #578) ------------------------- */
239
+ //
240
+ // 这一组锁的是「按安装布局写死路径」那类回归:exe 名、cli.js 位置、失败诊断三件事
241
+ // 以前都只有一种答案,换一种安装布局(DSH NEXT)整档 T1 就起不来,而报错是
242
+ // 「(无输出)」。全部用临时目录造假结构,不碰真 asar、不真开进程。
243
+
244
+ /** 造一棵假的安装树:<root>/<exeName> + <root>/resources/app.asar/<rel> */
245
+ function fakeInstall(exeName, cliRels) {
246
+ const root = mkdtempSync(join(tmpdir(), "choro-install-"));
247
+ const exe = join(root, exeName);
248
+ writeFileSync(exe, "", "utf8");
249
+ for (const rel of cliRels) {
250
+ const abs = join(root, "resources", "app.asar", ...rel.split("/"));
251
+ mkdirSync(join(abs, ".."), { recursive: true });
252
+ writeFileSync(abs, "// cli\n", "utf8");
253
+ }
254
+ return { root, exe };
255
+ }
256
+
257
+ test("resolveCliJs:DSH NEXT 布局优先于旧布局,且 DSH_CLI_JS 压过一切", () => {
258
+ // 两种布局同时在(老机器升级后可能留下旧目录),新布局必须赢——否则又一次
259
+ // 「升级了但还是按旧位置找」。
260
+ const both = fakeInstall("DSH NEXT.exe", [
261
+ "lib/desktop-cli.js",
262
+ "dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/cli.js",
263
+ ]);
264
+ try {
265
+ const picked = resolveCliJs(both.exe, {});
266
+ assert.equal(picked.verified, true);
267
+ assert.equal(picked.path, join(both.root, "resources", "app.asar", "lib", "desktop-cli.js"));
268
+ } finally {
269
+ rmTempBestEffort(both.root);
270
+ }
271
+
272
+ // 只有旧布局:仍要认(不能为了修新布局把老安装打坏)。
273
+ const legacy = fakeInstall("DeepSeek Harness.exe", ["dsh/node_modules/@deepseek-ai/dsh-desktop-host/lib/cli.js"]);
274
+ try {
275
+ const picked = resolveCliJs(legacy.exe, {});
276
+ assert.equal(picked.verified, true);
277
+ assert.ok(picked.path.includes("dsh-desktop-host"));
278
+ } finally {
279
+ rmTempBestEffort(legacy.root);
280
+ }
281
+
282
+ // DSH_CLI_JS:探测不进 asar 的进程(裸 node、远程布局)唯一的人工出口。
283
+ const manual = fakeInstall("DSH NEXT.exe", []);
284
+ try {
285
+ const custom = join(manual.root, "custom-cli.js");
286
+ writeFileSync(custom, "// cli\n", "utf8");
287
+ const picked = resolveCliJs(manual.exe, { DSH_CLI_JS: custom });
288
+ assert.equal(picked.path, custom);
289
+ assert.equal(picked.verified, true);
290
+ } finally {
291
+ rmTempBestEffort(manual.root);
292
+ }
293
+ });
294
+
295
+ test("resolveCliJs:DSH_CLI_JS 明确指定但路径不存在 → 直接失败,绝不回退到其它候选", () => {
296
+ const root = mkdtempSync(join(tmpdir(), "choro-t1-explicit-"));
297
+ try {
298
+ const exe = join(root, "DSH NEXT.exe");
299
+ writeFileSync(exe, "", "utf8");
300
+ // 这份「看起来能用」的布局候选真的存在:如果没有显式指定的短路,
301
+ // resolveCliJs 会安静地挑中它,用户以为自己的 DSH_CLI_JS 生效了。
302
+ const asarLib = join(root, "resources", "app.asar", "lib");
303
+ mkdirSync(asarLib, { recursive: true });
304
+ writeFileSync(join(asarLib, "desktop-cli.js"), "", "utf8");
305
+
306
+ const missing = join(root, "不存在的", "desktop-cli.js");
307
+ const picked = resolveCliJs(exe, { DSH_CLI_JS: missing });
308
+ assert.equal(picked.path, null, "显式指定失败就是失败:回退会让人以为设置生效了");
309
+ assert.equal(picked.verified, false);
310
+ assert.equal(picked.explicitMissing, missing, "把用户写的那个路径原样带回来,好让他改");
311
+ assert.ok(picked.candidates.includes(missing), "候选清单里仍是第一位");
312
+ } finally {
313
+ for (let i = 0; i < 5; i++) {
314
+ try { rmSync(root, { recursive: true, force: true }); break; } catch { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200); }
315
+ }
316
+ }
317
+ });
318
+
319
+ test("runner:DSH_CLI_JS 指定不存在的路径时,错误信息指向那个路径而不是布局", () => {
320
+ const run = makeHeadlessRunner({
321
+ locateExe: () => "D:\\fake\\DSH.exe",
322
+ resolveCli: () => ({ path: null, candidates: ["D:\\fake\\cli.js"], verified: false, explicitMissing: "D:\\my\\cli.js" }),
323
+ });
324
+ return run({ cwd: ".", task: "x", model: "p/m" }).then((res) => {
325
+ assert.equal(res.ok, false);
326
+ assert.equal(res.kind, "environment");
327
+ assert.ok(res.reason.includes("D:\\my\\cli.js"), "要点名用户写的路径");
328
+ assert.ok(res.reason.includes("不会回退"), "要说清它不会自动改用别的候选,否则用户会去查布局");
329
+ });
330
+ });
331
+
332
+ test("resolveCliJs:全都不在时交回旧布局路径但标 verified:false,候选清单完整", () => {
333
+ // verified:false 是失败信息里那句「这次没探测」的依据:宁可说清楚「我没看到」
334
+ // 也不假装自己确认过路径存在。
335
+ const empty = fakeInstall("DSH NEXT.exe", []);
336
+ try {
337
+ const picked = resolveCliJs(empty.exe, {});
338
+ assert.equal(picked.verified, false);
339
+ assert.ok(picked.path.endsWith(join("dsh-desktop-host", "lib", "cli.js")));
340
+ assert.equal(picked.candidates.length, 3); // DSH_CLI_JS 未设 → 不占位
341
+ assert.ok(picked.candidates.some((c) => c.endsWith(join("lib", "desktop-cli.js"))));
342
+ } finally {
343
+ rmTempBestEffort(empty.root);
344
+ }
345
+ });
346
+
347
+ test("locateDshExe:认 DSH NEXT.exe,也认标准安装位与 DSH_EXE", () => {
348
+ // 旧实现只认 basename === "deepseek harness.exe":DSH NEXT 的 exe 名不匹配、
349
+ // 装在别处也不匹配 → 两个条件同时不满足,直接 environment 失败。
350
+ assert.equal(locateDshExe({}, "D:\\Apps\\DSH NEXT.exe"), "D:\\Apps\\DSH NEXT.exe");
351
+ assert.equal(locateDshExe({}, "D:\\Apps\\DeepSeek Harness.exe"), "D:\\Apps\\DeepSeek Harness.exe");
352
+ // 不认识的 exe 名不许瞎猜:装了两套宿主时按「同目录任意 exe」挑会挑错。
353
+ assert.equal(locateDshExe({ ProgramFiles: "Z:\\nope", "ProgramFiles(x86)": "Z:\\nope2" }, "D:\\Apps\\other.exe"), null);
354
+
355
+ const install = fakeInstall("DSH NEXT.exe", []);
356
+ try {
357
+ // 标准安装位探测:<root>/DSH NEXT/DSH NEXT.exe
358
+ const pf = join(install.root, "pf");
359
+ const dir = join(pf, "DSH NEXT");
360
+ mkdirSync(dir, { recursive: true });
361
+ writeFileSync(join(dir, "DSH NEXT.exe"), "", "utf8");
362
+ assert.equal(locateDshExe({ ProgramFiles: pf }, "D:\\Apps\\other.exe"), join(dir, "DSH NEXT.exe"));
363
+ // DSH_EXE 最高优先(显式指定永远赢过探测)。
364
+ assert.equal(locateDshExe({ DSH_EXE: install.exe, ProgramFiles: pf }, "D:\\Apps\\other.exe"), install.exe);
365
+ } finally {
366
+ rmTempBestEffort(install.root);
367
+ }
368
+ });
369
+
370
+ /** 假子进程:只实现 consumeHeadlessStream 用到的那几个面。 */
371
+ function fakeProc({ stdout = [], stderr = [], code = 0 } = {}) {
372
+ const proc = new EventEmitter();
373
+ proc.stdout = new EventEmitter();
374
+ proc.stderr = new EventEmitter();
375
+ proc.killed = false;
376
+ proc.exitCode = null;
377
+ proc.signalCode = null;
378
+ proc.kill = () => { proc.killed = true; };
379
+ queueMicrotask(() => {
380
+ for (const chunk of stdout) proc.stdout.emit("data", Buffer.from(chunk));
381
+ for (const chunk of stderr) proc.stderr.emit("data", Buffer.from(chunk));
382
+ proc.emit("close", code);
383
+ });
384
+ return proc;
385
+ }
386
+
387
+ test("headless 起不来时,stderr 尾巴进 reason(不再是「(无输出)」)", async () => {
388
+ // issue #578 的直接症状:退出码 1 + stdout 空 → reason 只有「(无输出)」,用户
389
+ // 连是缺 credential 还是路径错都不知道。原因一直在 stderr 里。
390
+ const runner = makeHeadlessRunner({
391
+ locateExe: () => "D:\\fake\\DSH NEXT.exe",
392
+ resolveCli: () => ({ path: "D:\\fake\\cli.js", candidates: [], verified: true }),
393
+ spawn: () => fakeProc({ stderr: ["Error: Cannot find module 'D:\\fake\\cli.js'\n"], code: 1 }),
394
+ });
395
+ const result = await runner({ cwd: ".", task: "t", model: "p/m", timeoutMs: 5000, maxToolCalls: 3, maxOutputBytes: 4096 });
396
+ assert.equal(result.ok, false);
397
+ assert.equal(result.kind, "environment"); // "Cannot find" → 环境级
398
+ assert.ok(result.reason.includes("Cannot find module"));
399
+ assert.ok(!result.reason.includes("(无输出)"));
400
+ });
401
+
402
+ test("成功路径不追加「未经探测」的提示;探测失败且环境错时才追加", async () => {
403
+ // 成功时多说一句会让人以为哪里没配好;失败时这句是唯一的自查线索。
404
+ const okRunner = makeHeadlessRunner({
405
+ locateExe: () => "D:\\fake\\app.exe",
406
+ resolveCli: () => ({ path: "D:\\fake\\cli.js", candidates: [], verified: false }),
407
+ spawn: () => fakeProc({ stdout: ['{"type":"final","text":"ok"}\n'] }),
408
+ });
409
+ const ok = await okRunner({ cwd: ".", task: "t", model: "p/m", timeoutMs: 5000, maxToolCalls: 3, maxOutputBytes: 4096 });
410
+ assert.equal(ok.ok, true);
411
+ assert.ok(!ok.reason);
412
+
413
+ const badRunner = makeHeadlessRunner({
414
+ locateExe: () => "D:\\fake\\app.exe",
415
+ resolveCli: () => ({ path: "D:\\fake\\cli.js", candidates: [], verified: false }),
416
+ spawn: () => fakeProc({ stderr: ["MISSING_CREDENTIAL\n"], code: 1 }),
417
+ });
418
+ const bad = await badRunner({ cwd: ".", task: "t", model: "p/m", timeoutMs: 5000, maxToolCalls: 3, maxOutputBytes: 4096 });
419
+ assert.equal(bad.kind, "environment");
420
+ assert.ok(bad.reason.includes("DSH_CLI_JS")); // 提示指向唯一的人工出口
421
+ });
422
+
423
+ test("找不到 CLI 时 reason 列出全部候选路径", async () => {
424
+ const runner = makeHeadlessRunner({
425
+ locateExe: () => "D:\\fake\\DSH NEXT.exe",
426
+ resolveCli: () => ({ path: null, candidates: ["a/lib/desktop-cli.js", "b/dsh/lib/cli.js"], verified: false }),
427
+ spawn: () => { throw new Error("不该 spawn"); },
428
+ });
429
+ const result = await runner({ cwd: ".", task: "t", model: "p/m", timeoutMs: 5000, maxToolCalls: 3, maxOutputBytes: 4096 });
430
+ assert.equal(result.ok, false);
431
+ assert.equal(result.kind, "environment");
432
+ assert.ok(result.reason.includes("a/lib/desktop-cli.js"));
433
+ assert.ok(result.reason.includes("b/dsh/lib/cli.js"));
434
+ });
435
+
436
+ test("--dsh-exe 只影响这一轮:跑完 env 还原", async () => {
437
+ // 原来写进 process.env 就不还:同一进程里后续每次定位都继承旧值(面板切仓库
438
+ // 还是那个 exe),属于会记很久的脏状态。
439
+ const { root, store } = setup();
440
+ const saved = process.env.DSH_EXE;
441
+ try {
442
+ delete process.env.DSH_EXE;
443
+ let seen = null;
444
+ const t1 = createT1({
445
+ store,
446
+ runSession: async () => {
447
+ seen = process.env.DSH_EXE;
448
+ return { ok: true, text: GOOD_OUTPUT };
449
+ },
450
+ now: FIXED_NOW,
451
+ });
452
+ await t1.runT1({ repoRoot: root, moduleSlug: "src", dshExe: "D:\\Harness.exe" });
453
+ assert.equal(seen, "D:\\Harness.exe"); // 轮内可见
454
+ assert.equal(process.env.DSH_EXE, undefined); // 轮后还原
455
+ } finally {
456
+ if (saved !== undefined) process.env.DSH_EXE = saved;
457
+ store.close();
458
+ rmTempBestEffort(root);
459
+ }
460
+ });