@yolk_vat-y/dsh-project-memory 0.5.15 → 0.6.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.
package/cordis.patch.yml CHANGED
@@ -12,7 +12,7 @@
12
12
  watch: true
13
13
  watchInterval: 30
14
14
  # 危险根护栏(家目录 / 文件系统根 / 系统与包管理器前缀整体扫描会吃满内存)。
15
- # 自动路径永远不越权;true 只放开**显式**带 root 的工具调用。
15
+ # 懒索引/会话审计/任务桥永不越权;true 放开**显式**带 root 的工具调用,也放行 autoIndexOnFirstUse。
16
16
  allowUnsafeRoots: false
17
17
  # 单次扫描上限;截断会报告,且不会删除未扫到的条目。
18
18
  maxScanFiles: 20000
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.5.15",
3
+ "version": "0.6.1",
4
4
  "description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
5
5
  "author": "00080000 <3388065969@qq.com>",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  "url": "https://github.com/00080000/dsh-project-memory.git"
20
20
  },
21
21
  "scripts": {
22
- "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/host-contract.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/client-hints.test.mjs && node test/recall.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
22
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/host-contract.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
23
23
  "eval:injection": "node test/injection-scenarios.test.mjs",
24
24
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
25
25
  "selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
@@ -105,5 +105,8 @@
105
105
  ".": "./src/index.js",
106
106
  "./client": "./client/client.js",
107
107
  "./cordis.patch.yml": "./cordis.patch.yml"
108
+ },
109
+ "optionalDependencies": {
110
+ "leanvec": "^0.1.0"
108
111
  }
109
112
  }
@@ -13,9 +13,11 @@
13
13
  * files 可选,默认 5000(生成的代码文件数;每个文件约 4~5 条符号)。
14
14
  * 数据全部在 OS 临时目录生成,不会写入项目本身。
15
15
  */
16
+ import { execFileSync } from 'node:child_process'
16
17
  import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readdirSync, readFileSync } from 'node:fs'
17
18
  import { tmpdir } from 'node:os'
18
19
  import path from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
19
21
  import { performance } from 'node:perf_hooks'
20
22
 
21
23
  import { ProjectMemoryStore } from '../src/store.js'
@@ -166,6 +168,9 @@ async function main() {
166
168
  generateCorpus(root, FILES)
167
169
  await coldIndex(root, config)
168
170
  const times = []
171
+ // 每轮都在**独立进程**里冷加载:同进程里连着 load 5 份副本,storeCache 会攒下 5 个
172
+ // store —— 既绕不开预算结算,也不是"冷启动"(真实冷启动是空进程第一次 load)。
173
+ const loadScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bench-load.mjs')
169
174
  for (let r = 0; r < 5; r++) {
170
175
  // 拷贝到新路径,绕开进程内 storeCache,测真实读盘
171
176
  const copy = tmpd('pm-cldcp-')
@@ -182,10 +187,8 @@ async function main() {
182
187
  writeFileSync(path.join(dstDir, f), readFileSync(path.join(srcDir, f)))
183
188
  }
184
189
  }
185
- const t0 = performance.now()
186
- const s = new ProjectMemoryStore(dstDir).load()
187
- times.push(performance.now() - t0)
188
- s.stats()
190
+ const out = execFileSync(process.execPath, ['--expose-gc', loadScript, dstDir], { encoding: 'utf8' })
191
+ times.push(JSON.parse(out.trim().split('\n').pop()).loadMs)
189
192
  }
190
193
  show('cold load store (first read)', stats('coldload', times))
191
194
  }
package/scripts/bench.mjs CHANGED
@@ -211,11 +211,15 @@ const fileCount = Object.keys(store.files).length
211
211
 
212
212
  // ---------- 3. 存储体积 + 冷加载 ----------
213
213
  const onDisk = dirSize(tmpStore)
214
- // 真冷加载:store 有进程内缓存(同目录第二次 load() 直接命中),复制到新目录才是一次真正的冷启动
214
+ // 复制到新目录才是一次真正的冷加载(同目录第二次 load() 直接命中进程内缓存)
215
215
  const coldDir = `${tmpStore}-cold`
216
216
  cpSync(tmpStore, coldDir, { recursive: true })
217
- const coldLoad = timeSync(() => new ProjectMemoryStore(coldDir).load())
218
- // 常驻内存必须在独立进程里量:本进程已经拿着索引那个 store,再 load 一个副本得到的是两份
217
+ // 同进程里再 load 一份是**诊断**口径,不是"冷启动":本进程还拿着索引那个 store,
218
+ // storeCache 里于是有两个——缓存预算的结算因此会跑(大库上几十毫秒),而真实冷启动
219
+ // 是空进程里的第一次 load,不会背这笔账。
220
+ const siblingLoad = timeSync(() => new ProjectMemoryStore(coldDir).load())
221
+ // 常驻内存必须在独立进程里量:本进程已经拿着索引那个 store,再 load 一个副本得到的是两份。
222
+ // 同一个子进程顺手量了 loadMs —— 那才是要发布的口径。
219
223
  const memory = (() => {
220
224
  try {
221
225
  const loadScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bench-load.mjs')
@@ -225,6 +229,7 @@ const memory = (() => {
225
229
  return { error: err.message }
226
230
  }
227
231
  })()
232
+ const coldLoad = memory && !memory.error ? { ms: memory.loadMs } : siblingLoad
228
233
 
229
234
  // ---------- 4. 热查询 / 冷查询 ----------
230
235
  const queryPool = entries.filter((e) => typeof e.title === 'string' && e.title.trim().length >= 4)
@@ -352,6 +357,8 @@ const result = {
352
357
  bytesPerEntry: entries.length ? Math.round(onDisk.bytes / entries.length) : 0,
353
358
  },
354
359
  coldLoadMs: round(coldLoad.ms),
360
+ // 诊断:同进程里 load 第二个 store(缓存预算结算会跑),真实冷启动不背这笔账
361
+ secondStoreLoadMs: round(siblingLoad.ms),
355
362
  memory,
356
363
  query: {
357
364
  samples: queries.length,
@@ -385,7 +392,7 @@ if (opts.json) {
385
392
  console.log(` per file p50 ${result.index.perFileMs.p50} ms · p95 ${result.index.perFileMs.p95} ms`)
386
393
  console.log(` note: read+hash depends on the OS page cache — run it twice and say which run you quote`)
387
394
  console.log(
388
- `store ${mb(result.store.bytes)} content · ${mb(result.store.allocatedBytes)} on disk · ${result.store.bytesPerEntry} bytes/entry · cold load ${result.coldLoadMs} ms`,
395
+ `store ${mb(result.store.bytes)} content · ${mb(result.store.allocatedBytes)} on disk · ${result.store.bytesPerEntry} bytes/entry · cold load ${result.coldLoadMs} ms (fresh process; ${result.secondStoreLoadMs} ms with another store in-process)`,
389
396
  )
390
397
  if (memory && !memory.error) {
391
398
  console.log(
@@ -23,6 +23,7 @@ import { spawnSync } from 'node:child_process'
23
23
  import { mkdirSync, statSync, writeFileSync, existsSync } from 'node:fs'
24
24
  import os from 'node:os'
25
25
  import path from 'node:path'
26
+ import { fileURLToPath } from 'node:url'
26
27
 
27
28
  const argv = process.argv.slice(2)
28
29
  const mode = argv[0] && !argv[0].startsWith('--') ? argv[0] : null
@@ -273,7 +274,7 @@ function genPdf(file, targetBytes) {
273
274
  // ---------- 编排 ----------
274
275
 
275
276
  function runChild(childMode, file) {
276
- const r = spawnSync(process.execPath, ['--expose-gc', new URL(import.meta.url).pathname, childMode, file], {
277
+ const r = spawnSync(process.execPath, ['--expose-gc', fileURLToPath(import.meta.url), childMode, file], {
277
278
  encoding: 'utf8',
278
279
  maxBuffer: 64 * 1024 * 1024,
279
280
  })
@@ -15,10 +15,10 @@
15
15
  *
16
16
  * 用法: node scripts/tool-schema-size.mjs [--json]
17
17
  */
18
- import { pathToFileURL } from 'node:url'
18
+ import { fileURLToPath, pathToFileURL } from 'node:url'
19
19
  import path from 'node:path'
20
20
 
21
- const HERE = path.dirname(new URL(import.meta.url).pathname)
21
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
22
22
  const SRC = path.join(HERE, '..', 'src')
23
23
 
24
24
  // 工厂函数只需要在构造期读少量配置;用 Proxy 兜住所有未定义字段,
package/src/audit.js CHANGED
@@ -185,7 +185,16 @@ export function auditRecordFrom(input) {
185
185
  why: r.why,
186
186
  chars: typeof r.chars === 'number' ? r.chars : null,
187
187
  })),
188
- dropped: dropped.map((d) => ({ id: d.id, channel: d.channel, reason: d.reason })),
188
+ // `budget` 掉落带量纲(还剩多少 / 这条最少要多少),必须在审计面原样落地:
189
+ // 抹掉它们,`buildInjection` 那侧"细缝可诊断"的努力就只活在内存里。
190
+ // 只对带数字的条目落键——多数掉落(coverage 等)没有量纲,不该为它们付两个 null。
191
+ dropped: dropped.map((d) => ({
192
+ id: d.id,
193
+ channel: d.channel,
194
+ reason: d.reason,
195
+ ...(typeof d.remaining === 'number' ? { remaining: d.remaining } : {}),
196
+ ...(typeof d.need === 'number' ? { need: d.need } : {}),
197
+ })),
189
198
  // 会话级额度快照与"本轮为什么沉默":注入频率本身是可观测指标,不该只能靠感觉。
190
199
  budget: input.budget || null,
191
200
  silence: input.silence || null,
@@ -12,6 +12,7 @@ import { hasProjectMarker, isUnsafeRoot, memoryRootFor, resolveProjectMemoryRoot
12
12
  import { textOf } from './util/text.js'
13
13
  import { stepContent } from './util/task-view.js'
14
14
  import { insightMatchText, normalizedTokenOverlap } from './similarity.js'
15
+ import { createVectorRerank, vectorItemsFrom } from './vector-index.js'
15
16
  import { BoundedMap, SessionCache } from './util/session-cache.js'
16
17
  import { cfgInsight, GlobalStore, defaultGlobalFile, recordHit } from './insight-store.js'
17
18
  import { projectTags } from './project-profile.js'
@@ -101,9 +102,10 @@ export function cfgEngine(config) {
101
102
  reinjectItemsAfter: typeof c.reinjectItemsAfter === 'number' && c.reinjectItemsAfter >= 0 ? c.reinjectItemsAfter : 0,
102
103
  // ---- S2/S3/S4 新增(准入化改造) ----
103
104
  // 旧 `scope` 的处理:'filter'(默认,保留旧语义——不静默改用户数据)或 'ignore'。
104
- // 注意:实测里唯一带 scope 的条目,其值不在项目画像 tag 空间内,等于被判死刑;
105
- // 自检会把它报出来,由作者决定改值还是改语义。
106
- legacyScope: c.legacyScope === 'ignore' ? 'ignore' : 'filter',
105
+ // legacy `trigger.scope`:默认 **ignore**(与 `src/index.js` 的 schema 默认一致)。
106
+ // 值由作者手写,落不进自动派生的画像 tag 空间 → 当收窄条件用等于判死条目。
107
+ // 显式配 'filter' 才恢复旧的收窄语义。
108
+ legacyScope: c.legacyScope === 'filter' ? 'filter' : 'ignore',
107
109
  // 条目通道的步间隔:两次"条目注入"之间至少隔这么多步(常驻任务卡不受限——它是状态快照,
108
110
  // 内容变了就该更新)。这是"不频繁"的主要旋钮。
109
111
  gateCooldownSteps: typeof c.gateCooldownSteps === 'number' && c.gateCooldownSteps >= 0 ? c.gateCooldownSteps : 2,
@@ -127,6 +129,10 @@ export function cfgEngine(config) {
127
129
  // 通道级沉默:查询里能在语料中找到对应的词占比低于这个值时,整条提示通道本轮不出声。
128
130
  // 长句子里只有一两个词碰巧命中,coverage 会虚高到 1.00——这条门就是为它设的。
129
131
  hintMinSupport: typeof c.hintMinSupport === 'number' && c.hintMinSupport >= 0 ? c.hintMinSupport : 0.15,
132
+ // 可选向量层(leanvec)。`vectorDir` 无默认值 = 默认不用向量(纯词法);
133
+ // 只有配置了目录(或环境变量、或装上可选依赖)才构造 rerank,见 src/vector-index.js。
134
+ vectorDir: typeof c.vectorDir === 'string' && c.vectorDir ? c.vectorDir : null,
135
+ vectorAlpha: typeof c.vectorAlpha === 'number' && c.vectorAlpha >= 0 && c.vectorAlpha <= 1 ? c.vectorAlpha : 0.5,
130
136
  }
131
137
  }
132
138
 
@@ -267,8 +273,30 @@ function collectTriggered(cands, ctx) {
267
273
  * 通道 2:统计信号(提示态、优先级 2)。**双门槛**:层内相对阈值 + IDF 加权覆盖率(绝对下限)。
268
274
  * 查询只用「人类消息的意图文字 + 本次写目标」:原始工具参数不是查询文本,它们正是
269
275
  * `dcterms→rm`、`*.pptx→论文笔记` 那类假阳性的来源。被门槛拦下的记进 dropped,不静默。
276
+ *
277
+ * 可选的第三层:`rerank`(向量重排,默认关闭)。**职责严格分离**——闸门(支持度/覆盖率/共同词数)
278
+ * 仍由词法决定,`rerank` 只改层内排序与 `relative` 那一关。理由见下方融合处注释。
279
+ * @param {{ score: (q: string, cands: object[]) => Map<string, number>, alpha?: number, itemMin?: number, speakMin?: number }} [rerank]
280
+ * `itemMin` 给定且条目的余弦低于它时,该条目**不进提示通道**(只作用于提示通道,不碰 trigger)。
281
+ * `speakMin` 给定时,若层内最高余弦 ≥ 它,则本轮免于被通道级 `hintMinSupport` 静音(见下方救援处)。
282
+ *
283
+ * ⚠ 两个旋钮的实测边界(**都还没有可发布的默认值,别拍一个数字上去**):
284
+ * · `itemMin`:**真实交付上分辨力为零 → 不要开**。合成池上它看着很灵(假阳性 cos 0.351 vs
285
+ * 真命中 0.530),但真实 store 双重否定:① **绝对常量不可移植**——交付的 45 条余弦
286
+ * p50=0.206,同一个 0.42 会剪掉 45/45 = 100%(根因是文本变体:真实条目走 insightScoringText
287
+ * 的长文本,均值池化被稀释向语料均值);② **换成尺度无关量也不行**——在人工标注的 30 条真实
288
+ * 交付上(对 10 / 错 20,基线精度 0.33),cos 与 cos/步内最高的高半/低半精度**完全相同**
289
+ * (0.33 vs 0.33),"对"与"错"的 cosRel 分布重叠(p50 0.793 vs 0.782)。唯一有信号的是
290
+ * **步内名次 ≤4**(精度 0.46 vs 0.24),但拿它当门要误杀 4/10 个真命中 → 不划算。
291
+ * ③ **标签本身不稳**:同一个 30 条样本,agent 判 10 条有用、本地 4B 模型判 7 条,
292
+ * 逐条一致率只有 57%、Cohen kappa = **-0.05(等于随机)**。两次独立估计的水平接近
293
+ * (33% vs 23.8%,126 条上是 23.8%),所以"真实交付精度约 1/4~1/3"这个**水平**可信,
294
+ * 但**逐条标签不可信** → 任何在它上面标定的阈值都不可用。
295
+ * · `speakMin`:**证据仍不足 → 别开**。5 个自然语言对照的最高余弦
296
+ * 0.356 / 0.341 / **0.467** / 0.343 / 0.398,最低目标 0.483 → 间隔只有 0.016,且全靠一个
297
+ * 边界样本撑着;再补一个对照就可能翻转。
270
298
  */
271
- function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped }) {
299
+ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped, rerank = null }) {
272
300
  const hints = []
273
301
  // 影子记录用:本步**全部**被评过分的候选 + 特征 + 判据结果。与 hints/dropped 分开算——
274
302
  // 现有两类记录都只覆盖"过得了相对阈值的那部分",恰恰缺了"因为没到阈值而从未被考虑"的候选,
@@ -295,6 +323,35 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped }) {
295
323
  // 查询与被测覆盖率的文本用**同一个**过滤后的查询:否则缩写(wsl/npm)会在 BM25 里被剔除、
296
324
  // 却仍在覆盖率里计分,"至少两个共同词"就被它们凑够了。
297
325
  const scored = rankEntriesMergedScored(cands.map(insightToEntry), [q], cands.length)
326
+ // ---- 向量重排(可选、默认关闭):只改**排序**与 `relative` 那一关,绝不碰 support/coverage/thin ----
327
+ // 为什么不做成"向量分当绝对闸门":实测在带标注的 8 场景/24 条池上,expect 为空的对照场景
328
+ // 纯向量 top-1 = 0.38,而多条**真命中**只有 0.20~0.38(余弦与真值区间重叠)→ 任何绝对余弦
329
+ // 阈值要么放过对照、要么杀掉真命中。所以闸门继续由词法/支持度决定(它们不随嵌入模型变),
330
+ // 向量只在 BM25 的 top-k 内决定"先说哪条"。换模型/改词表只影响这一层,不必重标绝对阈值。
331
+ //
332
+ // `rerank.score(q, cands)` 由调用方提供(插件运行时装了 leanvec 才给;没装就不传,行为不变):
333
+ // 返回 Map<insightId, cos∈[0,1]>;**查询无法编码时应返回空 Map**——那样所有条目都没有
334
+ // 向量分,排序退化回纯词法,不会被压平成一个平台。
335
+ if (rerank && typeof rerank.score === 'function') {
336
+ const alpha = Math.max(0, Math.min(1, typeof rerank.alpha === 'number' ? rerank.alpha : 0.5))
337
+ let cos = null
338
+ try { cos = rerank.score(q, cands) } catch { cos = null } // 向量层任何异常都不得影响注入
339
+ const top0 = scored[0]?.score || 1
340
+ for (const r of scored) {
341
+ const v = cos instanceof Map ? cos.get(r.entry.insightId) : undefined
342
+ const has = typeof v === 'number' && Number.isFinite(v)
343
+ // 先留一份**未融合**的 BM25 原分:影子记录的 `rel` 必须继续是词法相对分,
344
+ // 否则离线重放(tools/vector-eval.mjs)拿到的"BM25 臂"会被融合分污染。
345
+ r.bm25 = r.score
346
+ r.vector = has ? v : null
347
+ // 有向量分的:归一后的词法分与余弦按 α 混合;没有的:只保留归一后的词法分
348
+ // (不拿 0 分去罚它——缺向量不等于不相关)。
349
+ r.score = has ? (1 - alpha) * (r.score / top0) + alpha * v : r.score / top0
350
+ }
351
+ scored.sort((a, b) => b.score - a.score)
352
+ } else {
353
+ for (const r of scored) r.vector = null
354
+ }
298
355
  // 语料词集合建**一次**再逐条算覆盖率。逐条调用 `idfCoverage` 会让它每次重建整个语料,
299
356
  // 即 O(C²) 次 tokenize(实测真实 store 单步 147ms → 1.3ms,109×,结果逐字段一致)。
300
357
  const corpusSets = corpusTermSets(corpus)
@@ -302,7 +359,19 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped }) {
302
359
  const qStats = coverage.get(cands[0].id) || { supported: 0, terms: 0 }
303
360
  const supportRatio = qStats.terms > 0 ? qStats.supported / qStats.terms : 0
304
361
  // 通道级沉默:查询里绝大多数词在语料里根本没有对应 → "覆盖率 1.00"只是假象。
305
- const channelThin = typeof cfg.hintMinSupport === 'number' && supportRatio < cfg.hintMinSupport
362
+ //
363
+ // ⚠ 它是**比率**(supported / 查询去重词数),所以长句在**小语料**上必然低:自然语言消息实测
364
+ // 只有 0.11~0.13——目标条目本身 rel=1.00 / coverage=1.00 / matched=2 也会被整条静音。
365
+ // 因此加一条**可选**的语义救援:仅当调用方提供了向量层、且层内最高余弦达到 `speakMin` 时,
366
+ // 才允许本轮不沉默(含义是"词法视角太稀,但语义视角很有把握")。它**不放松任何逐条闸门**
367
+ // (coverage / matched / relative 照旧),没有向量时的行为也一字不改。
368
+ let vectorRescue = false
369
+ if (rerank && typeof rerank.speakMin === 'number') {
370
+ let topCos = 0
371
+ for (const r of scored) if (typeof r.vector === 'number' && r.vector > topCos) topCos = r.vector
372
+ vectorRescue = topCos >= rerank.speakMin
373
+ }
374
+ const channelThin = typeof cfg.hintMinSupport === 'number' && supportRatio < cfg.hintMinSupport && !vectorRescue
306
375
  for (const r of relativeHits(scored, { ratioMin: cfg.signalMinRatio })) {
307
376
  const it = byId.get(r.entry.insightId)
308
377
  if (!it) continue
@@ -323,6 +392,14 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped }) {
323
392
  dropped.push({ id: it.id, channel: 'hint', reason: `thin:${ev.matched}` })
324
393
  continue
325
394
  }
395
+ // item 级余弦地板(可选):语义上根本不相关的条目,无论词法多像都不进提示通道。
396
+ // 这是**只作用于提示通道**的额外一关:authored trigger 是确定性全文注入契约,绝不能被向量拦。
397
+ // 实测(24 条池)分辨力真实:词法巧合的假阳性 `l_curated`(查询"把列表按日期倒序排")余弦
398
+ // 0.351,而真命中 `l_changelog` 0.530,间隔 0.179。取不到向量时不设限——缺向量不等于不相关。
399
+ if (rerank && typeof rerank.itemMin === 'number' && typeof r.vector === 'number' && r.vector < rerank.itemMin) {
400
+ dropped.push({ id: it.id, channel: 'hint', reason: `vector:${r.vector.toFixed(2)}` })
401
+ continue
402
+ }
326
403
  hints.push({ it, score: r.score, why: `relative:${(r.score / (scored[0].score || 1)).toFixed(2)} cov:${ev.coverage.toFixed(2)}/${ev.matched}` })
327
404
  }
328
405
 
@@ -341,17 +418,28 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped }) {
341
418
  if (channelThin) decision = 'support'
342
419
  else if (typeof cfg.hintMinCoverage === 'number' && ev.coverage < cfg.hintMinCoverage) decision = 'coverage'
343
420
  else if (ev.matched < needMatched) decision = 'thin'
421
+ else if (rerank && typeof rerank.itemMin === 'number' && typeof r.vector === 'number' && r.vector < rerank.itemMin) decision = 'vector'
344
422
  else if (r.score < top * Math.max(0, Math.min(1, ratio))) decision = 'relative'
345
- candidates.push({
423
+ const cand = {
346
424
  id: it.id,
347
425
  channel: 'hint',
348
- rel: Number((r.score / (top || 1)).toFixed(3)),
426
+ // `rel` 恒为**词法**相对分(未融合),供离线重放对照;融合后的分另记 fused。
427
+ rel: Number(((r.bm25 ?? r.score) / (top || 1)).toFixed(3)),
349
428
  coverage: Number(ev.coverage.toFixed(3)),
350
429
  matched: ev.matched,
351
430
  support: ev.supported,
352
431
  terms: ev.terms,
353
432
  decision,
354
- })
433
+ }
434
+ // 只在启用重排时加字段:默认路径的记录与旧版逐字节一致(不引入 undefined 键)。
435
+ if (rerank) {
436
+ cand.fused = Number(r.score.toFixed(3))
437
+ cand.vector = r.vector == null ? null : Number(r.vector.toFixed(3))
438
+ // 本轮是否靠语义救援才免于被 `support` 整条静音(0=没救、1=救了)。离线重放要靠它
439
+ // 区分"support 门拦的"与"coverage 门拦的"。
440
+ cand.rescue = vectorRescue ? 1 : 0
441
+ }
442
+ candidates.push(cand)
355
443
  }
356
444
  }
357
445
  return { hints, candidates, scoreQuery: q }
@@ -409,6 +497,7 @@ export function buildInjection(opts) {
409
497
  hintQuery: [ctx.intent || ctx.humanText || '', ...(ctx.targets || [])].filter(Boolean).join(' '),
410
498
  cfg,
411
499
  dropped,
500
+ rerank: opts.rerank || null,
412
501
  })
413
502
 
414
503
  // 常驻块文本。去重指纹只看稳定内容(任务标题/步骤/insights + 相关 insights):
@@ -646,6 +735,14 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
646
735
  silenceReason: silence.reason || 'cooldown',
647
736
  maxItems: silence.itemsLeft,
648
737
  maxChars: silence.charsLeft,
738
+ // 可选向量层:没装/没配就是 null → 提示通道与纯词法逐字段一致(闸门、注入条数都不变,
739
+ // 只有层内排序会用到余弦)。构造失败也在 createVectorRerank 内部吞掉并返回 null。
740
+ rerank: await createVectorRerank({
741
+ storeDir: memoryRoot,
742
+ items: vectorItemsFrom(store, globalStore),
743
+ vectorDir: cfg.vectorDir,
744
+ alpha: cfg.vectorAlpha,
745
+ }),
649
746
  })
650
747
 
651
748
  // 未注入 ≠ 无事发生:因预算被挤掉的条目按 cfg.budgetLog 留痕(默认 off,见 cfgEngine)。
package/src/chunker.js CHANGED
@@ -1,27 +1,45 @@
1
+ /**
2
+ * 惰性按行扫描:语义与 `text.split(/\r?\n/)` 完全一致(含 `\r\n` 与末尾空行),
3
+ * 但**不**一次性物化整份行数组——那是与文件同阶的一份拷贝。
4
+ */
5
+ function* iterLines(text) {
6
+ let start = 0
7
+ for (;;) {
8
+ const nl = text.indexOf('\n', start)
9
+ if (nl === -1) {
10
+ yield text.slice(start)
11
+ return
12
+ }
13
+ let end = nl
14
+ if (end > start && text.charCodeAt(end - 1) === 13) end--
15
+ yield text.slice(start, end)
16
+ start = nl + 1
17
+ }
18
+ }
19
+
20
+ /**
21
+ * 正文 → chunk。
22
+ *
23
+ * 2026-10-11 改为**按 section 流式**:原实现先把整份正文 `split(/\r?\n/)`,再把所有 section
24
+ * 的正文同时留在内存里,峰值与文件大小同阶(实测 PDF 边际 19×、单文件 50 MB → ~1.2 GB RSS)。
25
+ * 现在逐行惰性扫描、一个 section 处理完就放掉,并且**攒够 `maxChunks` 立刻停**。
26
+ *
27
+ * 两条等价性依据(都由差分测试钉住:新旧实现逐例对比随机文档 + 真实文件,要求逐字节一致):
28
+ * 1. section 之间互不影响——每个 section 的 block 只由它自己的行拼出来;
29
+ * 2. 达到 `maxChunks` 之后可以停——原实现在 while 里 break 后仍会推一次"剩余部分",
30
+ * 但那一次的下标必然 ≥ `maxChunks`,会被最后的 `.slice(0, maxChunks)` 丢弃。
31
+ * 于是只有"**永远不被保留**"的输入被略过,被保留的 chunk 与行号逐字不变。
32
+ */
1
33
  export function chunkText(text, chunkChars = 3000, maxChunks = 40) {
2
34
  if (!Number.isFinite(chunkChars) || chunkChars < 1) chunkChars = 3000
3
35
  if (!Number.isFinite(maxChunks) || maxChunks < 1) maxChunks = 40
4
- const lines = text.split(/\r?\n/)
5
- const sections = []
6
- let current = { title: '', lines: [], line: 1 }
7
- for (let i = 0; i < lines.length; i++) {
8
- const line = lines[i]
9
- if (/^\s*#{1,6}\s/.test(line)) {
10
- if (current.lines.length) {
11
- sections.push(current)
12
- current = { title: '', lines: [], line: i + 1 }
13
- }
14
- current.title = line.replace(/^\s*#{1,6}\s*/, '').trim()
15
- current.line = i + 1
16
- }
17
- current.lines.push(line)
18
- }
19
- if (current.lines.length) sections.push(current)
20
36
 
21
37
  const chunks = []
22
- for (const section of sections) {
38
+
39
+ /** 把一个 section 切成 chunk(与原实现逐字相同,只是改成按 section 调用)。 */
40
+ const flush = (section) => {
23
41
  const rawBlock = section.lines.join('\n')
24
- if (!rawBlock.trim()) continue
42
+ if (!rawBlock.trim()) return
25
43
  // `.trim()` 会吃掉段首的空白与换行——把它们算进行号,否则整段的引用行号会偏低。
26
44
  const lead = rawBlock.match(/^\s*/)[0]
27
45
  let line = section.line + (lead.match(/\n/g) || []).length
@@ -41,11 +59,26 @@ export function chunkText(text, chunkChars = 3000, maxChunks = 40) {
41
59
  block = rest.trim()
42
60
  if (chunks.length >= maxChunks) break
43
61
  }
44
- if (block) {
45
- chunks.push({ title: section.title, text: block, line })
62
+ // `chunks.length >= maxChunks` 时这次 push 的下标 ≥ maxChunks,原实现随后会把它 slice 掉。
63
+ if (block && chunks.length < maxChunks) chunks.push({ title: section.title, text: block, line })
64
+ }
65
+
66
+ let section = { title: '', lines: [], line: 1 }
67
+ let lineNo = 0
68
+ for (const line of iterLines(text)) {
69
+ lineNo++
70
+ if (/^\s*#{1,6}\s/.test(line)) {
71
+ if (section.lines.length) {
72
+ flush(section)
73
+ if (chunks.length >= maxChunks) return chunks
74
+ section = { title: '', lines: [], line: lineNo }
75
+ }
76
+ section.title = line.replace(/^\s*#{1,6}\s*/, '').trim()
77
+ section.line = lineNo
46
78
  }
47
- if (chunks.length >= maxChunks) break
79
+ section.lines.push(line)
48
80
  }
81
+ if (section.lines.length) flush(section)
49
82
 
50
83
  return chunks.filter((c) => c.text).slice(0, maxChunks)
51
- }
84
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { useEffect, useCallback, useRef, useState } from 'react'
7
7
  import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
8
+ import { service } from './services.ts'
8
9
  import css from './TaskPanel.module.css'
9
10
 
10
11
  export type InsightScope = 'task' | 'project' | 'global'
@@ -96,9 +97,10 @@ export function MemoryView({
96
97
 
97
98
  const runLine = useCallback(
98
99
  async (line: string): Promise<{ ok: boolean; text: string }> => {
99
- const commands = ctx?.remote?.commands
100
+ // 软探测(services.ts):`remote.commands` 是独立注册的扁平服务,按整名读(见 services.ts)。
101
+ const commands = service(ctx, 'remote.commands')
100
102
  if (!sessionId || !commands || typeof commands.execute !== 'function') {
101
- return { ok: false, text: 'no session / commands service' }
103
+ return { ok: false, text: 'data channel unavailable (missing client service)' }
102
104
  }
103
105
  try {
104
106
  const response = await commands.execute(sessionId, line, [])
@@ -13,6 +13,7 @@ import {
13
13
  IconQuestionOutline14,
14
14
  } from './icons.ts'
15
15
  import { createTranslate, zh, en } from './locales.ts'
16
+ import { missingServices, service } from './services.ts'
16
17
  import { useTaskData, useTaskDataActions, taskDataStore, parseTaskPayloadText, type TaskStep } from './task-data-store.ts'
17
18
  import { useTaskUI, useTaskUIActions, PANEL_VIEWS } from './task-ui-store.ts'
18
19
  import { MiniBar, TaskCard } from './TaskComponents.tsx'
@@ -27,20 +28,21 @@ const STATUS_CYCLE = ['pending', 'in_progress', 'completed'] as const
27
28
  const VIEW_CYCLE = PANEL_VIEWS
28
29
 
29
30
  function getT(ctx: any) {
30
- const locale = ctx?.locale?.getSnapshot?.()?.active === 'zh' ? zh : en
31
+ // 服务一律走软探测(services.ts):宿主的翻译服务不在时退英文,而不是抛错带崩整个面板。
32
+ const locale = service(ctx, 'locale')?.getSnapshot?.()?.active === 'zh' ? zh : en
31
33
  return createTranslate(locale)
32
34
  }
33
35
 
34
36
  function useSessionId(ctx: any): string | null {
35
37
  const [, force] = useState(0)
36
38
  useEffect(() => {
37
- const list = ctx?.sessions?.list
39
+ const list = service(ctx, 'sessions')?.list
38
40
  if (!list || typeof list.subscribe !== 'function') return
39
41
  return list.subscribe(() => force((n) => n + 1))
40
42
  }, [ctx])
41
43
  // 快照结构在 dsh 0.1.7 变过(current/items → ids/byId):解析与兼容都在 session-id.js,
42
44
  // 那里有单测;这里只负责订阅与取值。
43
- return pickSessionId(ctx?.sessions?.list?.getSnapshot?.())
45
+ return pickSessionId(service(ctx, 'sessions')?.list?.getSnapshot?.())
44
46
  }
45
47
 
46
48
  class PanelErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
@@ -71,6 +73,9 @@ function TaskPanelView({ ctx }: { ctx: any }) {
71
73
  const t = getT(ctx)
72
74
  const data = useTaskData()
73
75
  const ui = useTaskUI()
76
+ // 缺失的客户端服务:面板照常挂载,但必须把原因摆在界面上(否则用户看到的是
77
+ // "面板在、数据永远同步失败"这种没有因果的二次困惑)。
78
+ const degraded = missingServices(ctx)
74
79
  const sessionId = useSessionId(ctx)
75
80
  const [syncing, setSyncing] = useState(false)
76
81
  const [syncedAt, setSyncedAt] = useState(0)
@@ -104,9 +109,11 @@ function TaskPanelView({ ctx }: { ctx: any }) {
104
109
  }
105
110
 
106
111
  const runLine = async (line: string): Promise<boolean> => {
107
- const commands = ctx?.remote?.commands
112
+ // 软探测(services.ts):`remote.commands` 是**独立注册的扁平服务**,必须按整名读;
113
+ // `ctx.remote.commands` 走属性路径,会被 inject 门控挡下(本插件顶层 inject 为空)。
114
+ const commands = service(ctx, 'remote.commands')
108
115
  if (!sessionId || !commands || typeof commands.execute !== 'function') {
109
- setSyncError('no session / commands service')
116
+ setSyncError(t('panel.no-channel'))
110
117
  return false
111
118
  }
112
119
  let response: any
@@ -396,7 +403,11 @@ function TaskPanelView({ ctx }: { ctx: any }) {
396
403
  </div>
397
404
  </header>
398
405
 
399
- {!sessionId && <div className={css.notice}>{t('panel.no-session')}</div>}
406
+ {degraded.length > 0 && (
407
+ <div className={css.notice}>{t('panel.degraded', { names: degraded.join(', ') })}</div>
408
+ )}
409
+ {/* 会话服务本身缺失时,"还没有会话"是误导:上面那行的降级说明才是原因。 */}
410
+ {!sessionId && service(ctx, 'sessions') !== undefined && <div className={css.notice}>{t('panel.no-session')}</div>}
400
411
  {syncError && <div className={css.notice}>{t('panel.sync-failed')}: {syncError}</div>}
401
412
 
402
413
  {view !== 'task' ? (