@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.
@@ -4,6 +4,11 @@
4
4
  * dsh web (rc.1) 的 client 插件契约为 cordis client plugin:
5
5
  * export const inject = [<client 服务名>...]
6
6
  * export function apply(ctx) { ... }
7
+ *
8
+ * 本插件**不用顶层 `inject` 声明必需服务**(见 services.ts):它是装配期门控,缺一项宿主
9
+ * 就根本不调用 apply(),表现是"插件出问题、界面上却静默消失"。服务改由 `service()` 现场探测,
10
+ * 缺了照常挂载、面板上显示原因、日志里打一条点名缺失项的告警。
11
+ *
7
12
  * 面板注册进 `shell.overlay`(Frame 级浮动层,additive 列表槽):
8
13
  * 该槽由 ui-layout 的 AppFrame 声明渲染(scope root,独立于滚动容器),
9
14
  * 默认 click-through,条目自身需开启 pointer-events。
@@ -20,20 +25,28 @@ import { TaskCommandNode } from './TaskCommandNode.tsx'
20
25
  import { registerShowTaskPanelView } from './ShowTaskPanelNode.tsx'
21
26
  import { taskUIStore } from './task-ui-store.ts'
22
27
  import { createSlashSource } from './slash.ts'
28
+ import { DEGRADED_GRACE_MS, later, missingServices, service } from './services.ts'
23
29
 
24
30
  const NS = 'dsh-project-memory'
25
31
 
26
32
  export const name = NS
27
33
 
28
- /** Required client services: slots registry, session scopes, commands remote (data 通道). */
29
- export const inject = ['slots', 'sessions', 'remote', 'remote.commands', 'locale']
34
+ /**
35
+ * 顶层 `inject` **留空**(必需服务的软依赖清单在 services.ts 的 `REQUIRED_SERVICES`)。
36
+ *
37
+ * 这不是省略,而是契约选择:cordis 的顶层 inject 是装配期门控,缺一项就根本不调用
38
+ * `apply()` —— 整个 client 半边静默消失。留空后 apply() 一定会被调用,服务缺失由
39
+ * `missingServices()` 在运行时说清楚(面板上显示 + 日志告警)。
40
+ */
41
+ export const inject: readonly string[] = []
30
42
 
31
43
  /**
32
44
  * 注册自建的 `/` 菜单源(见 slash.ts)。
33
45
  *
34
46
  * 整段都是**可选增强**:宿主没有 `inputTriggers` 服务、或该服务换了契约时,绝不能因此
35
- * 让整个 client 插件挂掉——那会连任务面板一起消失。`inputTriggers` 因此不进顶层 `inject`
36
- * (顶层 inject 未满足时 cordis 根本不会调用 apply),而是走嵌套 inject + 两层 try/catch。
47
+ * 让整个 client 插件挂掉——那会连任务面板一起消失。`inputTriggers` 因此不进任何 `inject`
48
+ * 声明,而是走嵌套 `ctx.inject` + 两层 try/catch(顶层 inject 未满足时 cordis 根本不会
49
+ * 调用 apply,见 services.ts)。
37
50
  * @param ctx - client 根上下文
38
51
  */
39
52
  function registerSlashSource(ctx: any): void {
@@ -42,7 +55,10 @@ function registerSlashSource(ctx: any): void {
42
55
  return
43
56
  }
44
57
  try {
45
- ctx.inject(['inputTriggers', 'sessions', 'remote.commands'], (scope: any) => {
58
+ // 只等真正用到的两项:`inputTriggers` 是注册入口,`sessions` 用来消费触发 token。
59
+ // 那三行**不发宿主命令**(纯客户端开面板页),所以不把 `remote.commands` 写进这里 ——
60
+ // 少一个装配期门控,就少一种"菜单组永远不出现"的静默形态。
61
+ ctx.inject(['inputTriggers', 'sessions'], (scope: any) => {
46
62
  try {
47
63
  const inputTriggers = scope?.inputTriggers
48
64
  if (!inputTriggers || typeof inputTriggers.registerSource !== 'function') {
@@ -65,11 +81,19 @@ function registerSlashSource(ctx: any): void {
65
81
  }
66
82
  }
67
83
 
68
- export function apply(ctx: any): void {
69
- const slots = ctx?.slots
70
- if (!slots || typeof slots.inject !== 'function') {
71
- console.warn(`[${NS}] host has no slots service — task panel disabled`)
72
- } else {
84
+ /**
85
+ * 挂载任务面板(`shell.overlay` 浮层 + 会话内命令节点 + `show_task_panel` 工具视图)。
86
+ *
87
+ * `slots` 同样是软依赖:现成的就用;没有就**等它**(cordis 的 `ctx.inject` 是嵌套注入,
88
+ * 只门控这一段回调,插件本身照样挂载)。等不到时由 {@link reportDegradedLater} 说明原因。
89
+ * @param ctx - client 根上下文
90
+ */
91
+ function registerTaskPanel(ctx: any): void {
92
+ const mount = (slots: any): void => {
93
+ if (!slots || typeof slots.inject !== 'function') {
94
+ console.warn(`[${NS}] host has no slots service — task panel disabled`)
95
+ return
96
+ }
73
97
  try {
74
98
  slots.inject('shell.overlay', () => slots.register(
75
99
  {
@@ -100,5 +124,38 @@ export function apply(ctx: any): void {
100
124
  }
101
125
  }
102
126
 
127
+ if (typeof ctx?.inject === 'function') {
128
+ try {
129
+ ctx.inject(['slots'], (scope: any) => mount(scope?.slots ?? service(ctx, 'slots')))
130
+ return
131
+ } catch (err) {
132
+ console.warn(`[${NS}] slots injection failed:`, err)
133
+ }
134
+ }
135
+ mount(service(ctx, 'slots'))
136
+ }
137
+
138
+ /**
139
+ * 过了宽限期仍然读不到必需服务时,打**一条**点名缺失项的告警。
140
+ *
141
+ * 为什么不在 `apply()` 里立刻报:装配是异步的,apply 时某个服务还没 provide 是正常的
142
+ * (那样每次启动都会误报)。宽限期后还缺,就是真的缺 —— 这条日志是"静默消失"的反面。
143
+ * @param ctx - client 根上下文
144
+ */
145
+ function reportDegradedLater(ctx: any): void {
146
+ later(ctx, DEGRADED_GRACE_MS, () => {
147
+ const missing = missingServices(ctx)
148
+ if (missing.length === 0) return
149
+ console.warn(
150
+ `[${NS}] degraded: client service(s) unavailable in this assembly: ${missing.join(', ')}`
151
+ + ' — the client half is mounted anyway; the task panel shows the same reason.',
152
+ )
153
+ })
154
+ }
155
+
156
+ export function apply(ctx: any): void {
157
+ // 顶层不再有任何硬依赖:这里的三步都在缺服务时降级,绝不早退(早退就是静默消失)。
158
+ registerTaskPanel(ctx)
103
159
  registerSlashSource(ctx)
160
+ reportDegradedLater(ctx)
104
161
  }
@@ -21,6 +21,8 @@ export const zh = {
21
21
  'panel.empty': '暂无任务',
22
22
  'panel.empty-desc': '让模型开始工作并维护 todo 清单后会自动建档',
23
23
  'panel.no-session': '还没有会话',
24
+ 'panel.no-channel': '数据通道不可用(客户端服务缺失)',
25
+ 'panel.degraded': '插件降级:缺少客户端服务 {names}',
24
26
  'task.progress': '进度',
25
27
  'task.steps': '步骤',
26
28
  'task.files': '文件',
@@ -103,6 +105,8 @@ export const en = {
103
105
  'panel.empty': 'No Tasks',
104
106
  'panel.empty-desc': 'Tasks are created automatically when the model maintains a todo list',
105
107
  'panel.no-session': 'No session yet',
108
+ 'panel.no-channel': 'data channel unavailable (missing client service)',
109
+ 'panel.degraded': 'Plugin degraded — missing client service(s): {names}',
106
110
  'task.progress': 'Progress',
107
111
  'task.steps': 'Steps',
108
112
  'task.files': 'Files',
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Client 服务软探测 —— 顶层 `inject` 是「整半边静默消失」的开关,这里把它降级成运行时探测。
3
+ *
4
+ * cordis 的顶层 `inject` 是**装配期门控**:只要声明的一项在当前客户端装配里不可用,
5
+ * 它根本不会调用 `apply()`。这是插件能遇到的最坏失败形态 —— 没有面板、没有 `/` 组、
6
+ * 也没有任何报错(0.1.7 会话格式变更、0.2.0 装配差异都踩过这一条)。
7
+ *
8
+ * 所以本插件的 client 半边把必需服务全部当**软依赖**:
9
+ * - 顶层 `inject` 留空 → `apply()` 一定被调用,插件一定挂载;
10
+ * - 每个服务用 `ctx.get(name)` 现场读(cordis 里它**不需要 inject**),读不到就降级;
11
+ * - 缺什么由 {@link missingServices} 说清楚:面板上显示、日志里告警,而不是静默消失。
12
+ *
13
+ * 另一条与 `inject` 同源的坑:**属性路径(`ctx.remote.commands`)也是 inject 门控的**。
14
+ * 子命名空间在 cordis 里是**独立注册的扁平服务**(名字就叫 `remote.commands`,由 gateway 的
15
+ * `RemoteNamespaceService` 在嵌套 fiber 里 provide),读它只有 `ctx.get('remote.commands')`
16
+ * 这一条路不需要 inject;`ctx.remote.commands` 会走 ctx 代理,报
17
+ * `cannot get property "remote.commands" without inject` —— 于是"宿主明明有,插件却说缺"。
18
+ * 见 {@link service}:整名优先,属性路径只作老宿主回退。
19
+ */
20
+
21
+ /**
22
+ * 必需服务。带 `.` 的名字(`remote.commands`)是 cordis 里**独立注册的扁平服务名**,
23
+ * 不是"父服务上的属性"——只是老宿主可能把它挂在服务对象上,`service()` 才留了属性回退。
24
+ * 顺序即告警文案里的顺序,从"没有它就没有界面"到"没有它只是少个数据通道"。
25
+ */
26
+ export const REQUIRED_SERVICES = ['slots', 'sessions', 'remote', 'remote.commands', 'locale'] as const
27
+
28
+ /**
29
+ * 读一个服务(或它的属性路径),**永不抛出**。
30
+ *
31
+ * 读法有两条,顺序不能反:
32
+ * 1. **整名优先**:`ctx.get('remote.commands')`。cordis 里子命名空间就是独立注册的扁平服务,
33
+ * 这条路不经过 inject 门控 —— 它是"没有顶层 inject 的插件"读 `remote.commands` 的**唯一**可行路径。
34
+ * 2. **属性路径回退**:`ctx.get('remote').commands`。老宿主 / 测试替身把子命名空间挂在父服务对象上时走这条。
35
+ *
36
+ * `ctx.get()` 是 cordis 官方的"无 inject 读取"入口;老宿主没有它时回退到 `ctx[name]` —— 但那条路
37
+ * 既会因"没有 inject 又没有实现"**抛错**(而不是返回 undefined),也**读不到扁平子命名空间**,
38
+ * 所以必须整段接住:软依赖的全部意义就是不能让它带崩调用方,读不到就交给调用方按 undefined 处理。
39
+ * @param ctx - client 上下文(宿主没给上下文时返回 undefined)。
40
+ * @param path - 服务名,或 `服务名.属性.属性`。
41
+ * @returns 服务值;缺失/不可读时为 undefined。
42
+ */
43
+ export function service(ctx: any, path: string): any {
44
+ const whole = readService(ctx, path)
45
+ if (whole !== undefined) return whole
46
+ const [head, ...rest] = path.split('.')
47
+ if (rest.length === 0) return whole
48
+ let value = readService(ctx, head)
49
+ for (const key of rest) {
50
+ if (value === null || value === undefined) return undefined
51
+ try {
52
+ value = value[key]
53
+ } catch {
54
+ return undefined
55
+ }
56
+ }
57
+ return value
58
+ }
59
+
60
+ /**
61
+ * 读一层服务实现:先 `ctx.get(name)`,再回退到属性访问。
62
+ * @param ctx - client 上下文。
63
+ * @param name - 服务名(不含路径)。
64
+ * @returns 服务值,或 undefined。
65
+ */
66
+ function readService(ctx: any, name: string): any {
67
+ if (ctx === null || ctx === undefined) return undefined
68
+ try {
69
+ const get = ctx.get
70
+ if (typeof get === 'function') {
71
+ const found = get.call(ctx, name)
72
+ if (found !== undefined) return found
73
+ }
74
+ } catch {
75
+ // 服务未装配 / 读被拒:继续走属性回退,缺失由调用方按 undefined 处理。
76
+ }
77
+ try {
78
+ return ctx[name]
79
+ } catch {
80
+ return undefined
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 当前装配里读不到的必需服务。
86
+ * @param ctx - client 上下文。
87
+ * @param names - 待检查的服务路径,默认 {@link REQUIRED_SERVICES}。
88
+ * @returns 缺失的服务路径;全都在时为 `[]`。
89
+ */
90
+ export function missingServices(ctx: any, names: readonly string[] = REQUIRED_SERVICES): string[] {
91
+ return names.filter((name) => service(ctx, name) === undefined)
92
+ }
93
+
94
+ /**
95
+ * 降级检查的宽限期(毫秒)。装配是异步的:`apply()` 时某个服务还没到位**不算缺失**
96
+ * (它可能几百毫秒后才 provide),所以只在过了宽限期仍然读不到时才告警。
97
+ */
98
+ export const DEGRADED_GRACE_MS = 3000
99
+
100
+ /**
101
+ * 延后执行一次(宿主 ctx 有 `setTimeout` 就用它的,能随 fiber 一起回收)。
102
+ * @param ctx - client 上下文。
103
+ * @param delay - 毫秒。
104
+ * @param fn - 回调。
105
+ */
106
+ export function later(ctx: any, delay: number, fn: () => void): void {
107
+ try {
108
+ if (typeof ctx?.setTimeout === 'function') {
109
+ ctx.setTimeout(fn, delay)
110
+ return
111
+ }
112
+ const handle: any = (globalThis as any).setTimeout(fn, delay)
113
+ // Node(本仓测试就跑在 Node)里 pending 定时器会拖住进程退出;浏览器返回值是数字,这行是 no-op。
114
+ if (handle !== null && typeof handle === 'object' && typeof handle.unref === 'function') handle.unref()
115
+ } catch {
116
+ // 没有可用计时器:插件照常挂载,降级原因仍由面板渲染时显示。
117
+ }
118
+ }
@@ -29,6 +29,7 @@
29
29
  */
30
30
  import type { ComponentType } from 'react'
31
31
  import { createTranslate, en, zh } from './locales.ts'
32
+ import { service } from './services.ts'
32
33
  import type { PanelView } from './task-ui-store.ts'
33
34
  import { IconChecklistOutline16, IconGlobeOutline16, IconLightOutline16 } from './icons.ts'
34
35
 
@@ -53,7 +54,6 @@ interface SlashRow {
53
54
  readonly icon: ComponentType<{ size?: number; className?: string }>
54
55
  /** 额外搜索词:候选 name 是中文,拉丁输入(task / memory…)靠这些命中。 */
55
56
  readonly match: readonly string[]
56
- /** 点击后经 remote.commands.execute 执行的完整命令行。 */
57
57
  /** 点击后要打开的面板视图页。**纯客户端动作**,不绕宿主命令。 */
58
58
  readonly view: PanelView
59
59
  }
@@ -97,7 +97,8 @@ type Translate = (key: string, params?: Record<string, string | number>) => stri
97
97
 
98
98
  /** 按当前语言取翻译函数。 */
99
99
  function translator(ctx: any): Translate {
100
- const dict = ctx?.locale?.getSnapshot?.()?.active === 'zh' ? zh : en
100
+ // 软探测(services.ts):宿主没有翻译服务时退英文,而不是抛错。
101
+ const dict = service(ctx, 'locale')?.getSnapshot?.()?.active === 'zh' ? zh : en
101
102
  return createTranslate(dict) as unknown as Translate
102
103
  }
103
104
 
@@ -3,7 +3,7 @@
3
3
  // 纯函数 actInsight / listInsights 操作传入的 store/gs 内存对象,持久化由调用方
4
4
  // (命令 handler:store.commit + gs.commit)统一负责,便于单测。
5
5
  import { ProjectMemoryStore } from '../store.js'
6
- import { memoryRootFor } from '../util/fs.js'
6
+ import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
7
7
  import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, INSIGHT_KINDS } from '../insight-store.js'
8
8
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
@@ -231,7 +231,7 @@ const KIND_CONTENT = {
231
231
  const ALL_CONTENT = ['body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps']
232
232
 
233
233
  /** 编辑既有条目(title/kind/正文/trigger 等白名单字段)。任务级按 id 在任务池定位。 */
234
- export function editMemoryItem({ store, gs, scope, id, fields }) {
234
+ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
235
235
  if (!fields || typeof fields !== 'object') return { ok: false, text: 'edit 需要字段对象' }
236
236
  const applyTo = (item) => {
237
237
  let changed = false
@@ -264,7 +264,8 @@ export function editMemoryItem({ store, gs, scope, id, fields }) {
264
264
  }
265
265
  if (key === 'steps' || key === 'tags' || key === 'files' || key === 'symbols') {
266
266
  if (!Array.isArray(v)) continue
267
- item[key] = v.map(String)
267
+ // 写入期约束(与 save_lesson 同一判据):files 只收项目内相对路径,项目外/逃出根的丢弃。
268
+ item[key] = key === 'files' ? normalizeCitationFiles(v, root).files : v.map(String)
268
269
  changed = true
269
270
  continue
270
271
  }
@@ -381,7 +382,7 @@ export function insightCommandDefinition(config, ctx) {
381
382
  }
382
383
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
383
384
  const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
384
- const res = editMemoryItem({ store, gs, scope, id, fields })
385
+ const res = editMemoryItem({ store, gs, scope, id, fields, root })
385
386
  store.commit(() => 0)
386
387
  gs.commit()
387
388
  return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
@@ -106,6 +106,8 @@ export function taskCommandDefinition(config, ctx) {
106
106
  task.title = title
107
107
  task.updatedAt = new Date().toISOString()
108
108
  task.lastActiveAt = task.updatedAt
109
+ // 直接改 task 内容 → 必须标脏:save() 没脏标记会早退(改动静默丢失),驻留账也停在旧水位。
110
+ store.markTasksDirty()
109
111
  store.save()
110
112
  const note = `已改名「${oldTitle}」→「${title}」`
111
113
  return withTaskSnapshot(config, cwd, sid, store, note)
@@ -136,6 +138,7 @@ export function taskCommandDefinition(config, ctx) {
136
138
  task.steps = norm
137
139
  task.updatedAt = new Date().toISOString()
138
140
  task.lastActiveAt = task.updatedAt
141
+ store.markTasksDirty()
139
142
  store.save()
140
143
  if (shouldAdoptToHost(config)) {
141
144
  adoptStepsToSession(session, task)
@@ -154,6 +157,7 @@ export function taskCommandDefinition(config, ctx) {
154
157
  }
155
158
  task.updatedAt = new Date().toISOString()
156
159
  task.lastActiveAt = task.updatedAt
160
+ store.markTasksDirty() // switch 会解归档:这条也要落进 tasks.json(不只是 binding)
157
161
  store.save()
158
162
  // 反思钩子:切走旧任务异步收割(默认关)
159
163
  if (prevBound && prevBound !== task.id) {
@@ -173,6 +177,7 @@ export function taskCommandDefinition(config, ctx) {
173
177
  if (task.archived) return { kind: 'error', text: `[task] 已归档: ${task.title}` }
174
178
  task.archived = true
175
179
  task.updatedAt = new Date().toISOString()
180
+ store.markTasksDirty()
176
181
  store.save()
177
182
  // 反思钩子:归档即收割(默认关)
178
183
  fireReflect(config, { llm: ctx?.llm }, root, taskId, 'archive', resolveRoute(session ? { agent: { session } } : undefined, config))
@@ -47,7 +47,6 @@ export async function buildDocEntries(relPath, filePath, opts = {}) {
47
47
  type: 'doc',
48
48
  title: chunk.title || relPath,
49
49
  summary: summarizeText(chunk.text),
50
- blindSpots: '',
51
50
  keywords: extractKeywords(chunk.title, chunk.text),
52
51
  terms: extractTermText(chunk.text),
53
52
  hash,
package/src/index.js CHANGED
@@ -45,12 +45,11 @@ export const Config = Schema.object({
45
45
  watch: Schema.boolean().default(true),
46
46
  watchInterval: Schema.number().default(30),
47
47
  // 危险根护栏(issue #5):家目录 / 文件系统根 / 系统目录 / 包管理器前缀(/opt/homebrew …)
48
- // 整体扫描会吃满内存,默认一律拒绝。**自动路径永不越权**——懒索引、会话审计、任务桥在
49
- // 这类目录里始终零副作用;这个开关只放开**显式**工具调用(index_repo / watch_repo /
50
- // remember 等带 root 的调用)。
48
+ // 整体扫描会吃满内存,默认一律拒绝。懒索引、会话审计、任务桥在这类目录里始终零副作用;
49
+ // `autoIndexOnFirstUse` 不在此列——本开关同样放行它。其余只放开**显式**带 root 的工具调用。
51
50
  allowUnsafeRoots: Schema.boolean().default(false),
52
51
  // 单次扫描上限。超过即截断(并跳过"删除本轮未见到条目"的清理,避免把没扫到的文件误删)。
53
- // 显式设 0 表示不限制——自担风险。
52
+ // **不可取消**:0 / 负数 / 非数值一律回落默认值(见 util/fs.js 的 scanLimits)。
54
53
  maxScanFiles: Schema.number().default(DEFAULT_SCAN_FILES),
55
54
  maxScanDepth: Schema.number().default(DEFAULT_SCAN_DEPTH),
56
55
  tsPath: Schema.string(),
@@ -117,7 +116,21 @@ export const Config = Schema.object({
117
116
  hintMinCoverage: Schema.number().default(0.45),
118
117
  hintMinMatched: Schema.number().default(2),
119
118
  hintMinSupport: Schema.number().default(0.15),
120
- legacyScope: Schema.union(['filter', 'ignore']).default('filter'),
119
+ // 可选向量层(leanvec):**不装就是纯词法**,装了也只改经验/洞察层的**排序**——
120
+ // 闸门(覆盖率/共同词数)与返回条数都不变,doc/symbol 层完全不受影响。
121
+ // `vectorDir` 刻意**不给默认值**(与 relevanceMin 同一套约定:有默认值会让"是否启用"永远为真)。
122
+ // 解析顺序:本项显式路径 > 环境变量 DSH_LEANVEC_DIR > **可选依赖 `leanvec`**(装上即自动命中)。
123
+ // 目录里需有 dist/leanvec.f32 与 dist/leanvec.tokenizer.json。
124
+ // **填 `off` 可强制关闭**(连模型都不加载):装了可选依赖之后仍有退回纯词法的开关。
125
+ vectorDir: Schema.string(),
126
+ // 融合权重 (1-α)·BM25归一 + α·余弦。实测**小 k** 上 α=0.5 最优(k=3 64% vs 58%、k=5 69% vs 67%,
127
+ // α=0.75 时 k=5 到 72%),而 α=1(纯向量)明显更差(hit@10 53% vs 81%)——所以默认 0.5 不是 1。
128
+ vectorAlpha: Schema.number().default(0.5),
129
+ // legacy `trigger.scope` 的处置。默认 **ignore**:它的值由作者手写,几乎不可能落在
130
+ // 自动派生的项目画像 tag 空间里(实测唯一一条带 scope 的条目因此永远无法命中),
131
+ // 拿它当收窄条件只会判死条目。`readiness.js` 的注释一直写的是"默认忽略",这里此前
132
+ // 是 `'filter'` —— 注释与实现不一致,以注释为准。显式配 'filter' 可恢复旧语义。
133
+ legacyScope: Schema.union(['filter', 'ignore']).default('ignore'),
121
134
  auditLog: Schema.boolean().default(true),
122
135
  auditMaxBytes: Schema.number().default(262144),
123
136
  // 影子记录(admission-shadow.jsonl):**每步**一行,含全部候选的判据特征与场景。
@@ -154,6 +167,16 @@ export function apply(ctx, config) {
154
167
  // 跟踪会话路由(request/header 事件),为无会话上下文的召回期可选 LLM(查询扩展 / 反思)兜底
155
168
  ctx.on('session/event', (session, event) => {
156
169
  if (event?.type === 'request/header') rememberRoute(session)
170
+ // 会话活跃信号:有人正在跑回合时把 watch 轮询压到最低,回合结束立刻补扫一次(见 watch.js)。
171
+ // 这是"轮询只在空闲时发生"的落点 —— 交互期间把 I/O 全让给模型,停下那一刻才整理索引。
172
+ const key = session?.id ?? 'unknown'
173
+ if (event?.type === 'turn/start' || event?.type === 'step/start') watchManager.setSessionActive(key, true)
174
+ else if (event?.type === 'turn/end') watchManager.setSessionActive(key, false)
175
+ })
176
+ // 会话被销毁时也要摘掉活跃标记:否则一个没有正常 turn/end 的会话会把轮询**永久**压在兜底节拍
177
+ // (不会卡死,但"空闲时高速刷新"再也不会回来)。
178
+ ctx.on('session/disposed', (session) => {
179
+ watchManager.setSessionActive(session?.id ?? 'unknown', false)
157
180
  })
158
181
  ctx.tools.register(listTasksTool(config))
159
182
  ctx.tools.register(selectTaskTool(config, { llm: ctx.llm, ctx }))
File without changes
package/src/readiness.js CHANGED
@@ -199,7 +199,7 @@ function globToRegExp(pattern) {
199
199
  /**
200
200
  * 剥离**引用内容**:代码块、行内代码、引号内的路径/文件名、裸路径。
201
201
  *
202
- * 为什么必须剥:人类消息里的文件名是**数据**,不是意图。实测中"石啸天-LLM记忆方向调研.pptx"
202
+ * 为什么必须剥:人类消息里的文件名是**数据**,不是意图。实测中"示例调研.pptx"
203
203
  * 这个文件名让一条"做调研要先扫 curated 列表"的经验在改文件时间戳的任务里被注入。
204
204
  * @param {string} text - 人类消息原文
205
205
  * @returns {string} 只保留意图文字的版本
@@ -212,7 +212,7 @@ export function intentText(text) {
212
212
  .replace(/“[^”\n]*”/g, ' ')
213
213
  .replace(/[A-Za-z]:\\[^\s"']*/g, ' ')
214
214
  .replace(/(?:[A-Za-z0-9_.@-]+\/)+[A-Za-z0-9_.@-]+/g, ' ')
215
- // 带扩展名的**非 ASCII 文件名**(`石啸天-记忆方向调研.pptx` / `docs/面试演示-王金鹏.md`):
215
+ // 带扩展名的**非 ASCII 文件名**(`示例调研.pptx` / `docs/示例.md`):
216
216
  // 只挡 ASCII 路径不够——中文文件名整块留下,"调研""面试"这类子串照样触发 when.intents,
217
217
  // 正是引号剥离要防的那类假阳性。ASCII 裸名(如 de-TODO.md)保持原语义,不在这里动。
218
218
  .replace(/\S*[^\x00-\x7F]\S*\.[A-Za-z][A-Za-z0-9]{0,7}\b/g, ' ')
@@ -375,7 +375,10 @@ export function normalizeTrigger(it, opts = {}) {
375
375
  if (intents.length) when.intents = [...new Set(intents)]
376
376
  const out = { ...t, when }
377
377
  const scopeIgnored = Array.isArray(t.scope) && t.scope.length > 0
378
- if (scopeIgnored && opts.legacyScope !== 'ignore') out.guard = { ...(t.guard || {}), tags: t.scope }
378
+ // legacy `scope` → guard.tags **只在显式要求 filter 时**才做:它的值由作者手写,
379
+ // 几乎落不进自动派生的项目画像 tag 空间,当收窄条件用等于判死条目(实测唯一一条带
380
+ // scope 的条目因此永远不命中)。默认 ignore —— 与 `src/index.js` 的 schema 默认一致。
381
+ if (scopeIgnored && opts.legacyScope === 'filter') out.guard = { ...(t.guard || {}), tags: t.scope }
379
382
  return { ...it, trigger: out, triggerNormalized: { dropped, scopeIgnored } }
380
383
  }
381
384
 
package/src/recall.js CHANGED
@@ -17,7 +17,51 @@
17
17
  *
18
18
  * @module dsh-project-memory/recall
19
19
  */
20
- import { rankEntriesMergedScored, rankEntriesStreaming, rankExperienceScored } from './util/search.js'
20
+ import { rankEntriesMergedScored, rankEntriesStreaming, rankExperienceScored, tokenizeRaw, CJK_RANGE } from './util/search.js'
21
+
22
+ /**
23
+ * 短拉丁片段不算检索证据(只用于经验/洞察两层)。
24
+ *
25
+ * tokenizer 按 `[a-z0-9_]+` 切词,`no-op` / `--no-edit` 会留下 `no`、`op` 这类两字母片段。
26
+ * 它们在散文语料里没有独立语义,却因为稀缺而拿到不低的 BM25:查询 `zzz-no-such-topic-xyz`
27
+ * 就靠 `no` 命中一条无关笔记。所以这两层的查询词里,拉丁项短于 3 个字符的直接丢弃。
28
+ *
29
+ * 为什么只在这两层:doc/symbol 层是代码与路径,`js` / `id` 这类短标识符本来就该命中
30
+ * (见上方 `matchedFloor` 的注释)。两种模式(有/无向量)一律适用——闸门不能随向量层开关变形。
31
+ */
32
+ const MIN_LATIN_QUERY_TERM = 3
33
+ function gatedQueryText(q) {
34
+ return tokenizeRaw(String(q ?? ''))
35
+ .filter((t) => CJK_RANGE.test(t) || t.length >= MIN_LATIN_QUERY_TERM)
36
+ .join(' ')
37
+ }
38
+
39
+ /**
40
+ * 最小相关性闸门:命中的**不同查询词数**至少 min(2, 查询词数)。
41
+ *
42
+ * 为什么需要:`score > 0` 不是"相关"的证据。实测把 `zzz-no-such-topic-xyz` 丢进 query_memory,
43
+ * 它命中了 1 条无关经验——因为查询被 `-` 切出的 2 字符片段 `no` 恰好是那条经验里的一个真实 token
44
+ * (来自 `git commit --amend --no-edit`),于是单个片段就拿走了 3.13 分。提示通道早就有这条规则
45
+ * (`hintMinMatched`,默认 min(2, 词数)),**工具路径与这两层一直漏着**。
46
+ *
47
+ * ⚠ **只在没有向量层时生效**(`rerank` 为空)。这是同查询集 A/B 实测出来的(36 条、同一个 store):
48
+ * · 纯词法下加闸门:BM25 的 hit@1/3/5/10 = 39/50/58/69% **完全不变**,只是不再对乱码查询出声;
49
+ * · 有向量时加闸门:融合 hit@5/10 从 64/72% 掉到 58/64%,"完全没召回"从 10 涨到 13。
50
+ * 原因是结构性的:**向量救回来的那批,恰恰就是词法弱到不足 2 个命中的**——用词法的尺子去筛,
51
+ * 等于把向量的全部价值砍掉。有语义分时就该让语义分判质量,词法闸门不要越权。
52
+ *
53
+ * 只作用于 experience / insight 两层:它们是短标题语料,单片段命中几乎没有证据力;
54
+ * doc/symbol 层是代码与路径(`js` / `id` 这类单词查询本来就该命中),不动它。
55
+ * 单词查询不受影响:need = min(2, 1) = 1,与"score>0 即命中"等价。
56
+ */
57
+ function matchedFloor(scored, queries, hasVector) {
58
+ if (hasVector) return scored // 有语义分 → 不用词法的"命中词数"判质量
59
+ const qTokens = new Set()
60
+ for (const q of queries) for (const t of tokenizeRaw(String(q ?? ''))) qTokens.add(t)
61
+ const need = Math.min(2, qTokens.size)
62
+ if (need <= 1) return scored
63
+ return scored.filter((r) => (r.matched ?? 0) >= need)
64
+ }
21
65
 
22
66
  /** 各层先验:insight 是"踩过的坑",略高于普通文档;经验层已由 experience 文件服务,略低。 */
23
67
  export const LAYER_PRIORS = Object.freeze({
@@ -151,6 +195,57 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
151
195
  return out
152
196
  }
153
197
 
198
+ /**
199
+ * 向量融合(可选、默认关闭):只作用于**经验/洞察层**。
200
+ *
201
+ * 为什么只给这两层:它们的池子小(实测真实 store ≤103 条),融合代价 = 每查询一次编码(~2ms)
202
+ * + 池内点积(可忽略),且向量由调用方按条目缓存一次即可;而 doc/symbol 池是 10⁴ 量级
203
+ * (某真实 TS 仓库 15.6k 条目),同一做法要 60s/查询——所以那一层继续纯词法。
204
+ *
205
+ * 为什么是**融合**而不是"有向量就只用向量":实测(36 条刻意无词重叠的查询 / 103 条池)
206
+ * · 纯向量替换 BM25:hit@10 53% vs **81%**,明显更差;
207
+ * · 权重融合在小 k 上更优:k=3 64% vs 58%、k=5 72% vs 67%(α=0.75;α=0.5 时 64%/69%);
208
+ * · 并集召回最高(92%)但要返回 ~2k 条,模型可见的内容会翻倍。
209
+ * 所以取 α=0.5:拿到小 k 的收益,又不至于把 BM25 的正确项挤出 top-10。
210
+ *
211
+ * 融合必须在**全量** BM25 序上做(不是先截断再重排),否则"词法排 20 名但语义很近"的条目
212
+ * 永远进不来——那正是向量唯一能补的那类。截断到 limit 发生在融合之后。
213
+ *
214
+ * **边界**:`rankEntriesMergedScored` / `rankExperienceScored` 只返回 **BM25 分 > 0** 的条目,
215
+ * 所以本函数只能**重排**,**拉不进**零词重叠的条目——那需要"并集"形态(向量 top-k 追加到短名单)。
216
+ * 并集的召回更高(实测 hit@10 92% vs 81%)但返回条数约翻倍,对"只给模型少数几条"不友好,
217
+ * 故这里明确不做;要放宽时另开一个模式并重新量一遍。
218
+ *
219
+ * @param {{item: object, score: number}[]} scored - 已按 BM25 降序
220
+ * @param {string[]} queries
221
+ * @param {{score: (q: string, items: object[]) => Map<string, number>, alpha?: number}} [rerank]
222
+ * @returns {{item: object, score: number, vector?: number}[]}
223
+ */
224
+ function fuseVectorHits(scored, queries, rerank) {
225
+ if (!rerank || typeof rerank.score !== 'function' || !scored.length) return scored
226
+ const cosOf = new Map()
227
+ for (const q of queries) {
228
+ let m = null
229
+ try { m = rerank.score(q, scored.map((s) => s.item)) } catch { m = null } // 向量层异常不得影响召回
230
+ if (!(m instanceof Map)) continue
231
+ for (const [id, v] of m) {
232
+ if (typeof v !== 'number' || !Number.isFinite(v)) continue
233
+ if (!cosOf.has(id) || v > cosOf.get(id)) cosOf.set(id, v) // 与多查询的 BM25 合并同语义:取最高
234
+ }
235
+ }
236
+ if (!cosOf.size) return scored // 查询无法编码 / 没有向量 → 原样返回(降级到纯词法)
237
+ const alpha = Math.max(0, Math.min(1, typeof rerank.alpha === 'number' ? rerank.alpha : 0.5))
238
+ const top0 = scored[0].score || 1
239
+ const fused = scored.map((s) => {
240
+ const v = cosOf.get(s.item?.insightId) ?? cosOf.get(s.item?.id)
241
+ const has = typeof v === 'number'
242
+ // 没有向量分的条目只保留归一后的词法分(缺向量不等于不相关)
243
+ return { item: s.item, vector: has ? v : undefined, score: has ? (1 - alpha) * (s.score / top0) + alpha * v : s.score / top0 }
244
+ })
245
+ fused.sort((a, b) => b.score - a.score)
246
+ return fused
247
+ }
248
+
154
249
  /**
155
250
  * 按层召回:每层各自 top-k,桶内保留原始分与层内相对分。
156
251
  * @param {object} opts
@@ -161,6 +256,8 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
161
256
  * @param {string[]} [opts.layers] - 要召回的层;默认四层。
162
257
  * @param {number} [opts.limit] - 每层上限。
163
258
  * @param {string|null} [opts.boundTaskId] - 当前会话绑定的任务(决定 task 级可见性)。
259
+ * @param {object} [opts.rerank] - 可选向量融合器(**只作用于 experience / insight 层**)。
260
+ * 装了 leanvec 就传,没装就不传 → 行为与纯词法完全一致。见 {@link fuseVectorHits}。
164
261
  * @returns {{ layers: object[], flat: object[] }} layers 为分桶结果,flat 为归一化+先验后的跨层提示序。
165
262
  */
166
263
  export function recallItems(opts = {}) {
@@ -172,8 +269,11 @@ export function recallItems(opts = {}) {
172
269
  layers = ['doc', 'symbol', 'experience', 'insight'],
173
270
  limit = 8,
174
271
  boundTaskId = null,
272
+ rerank = null,
175
273
  } = opts
176
274
  const qs = (Array.isArray(queries) ? queries : [queries]).map((q) => String(q ?? '')).filter(Boolean)
275
+ // 经验/洞察两层用去掉短拉丁片段的查询(见 `gatedQueryText`);doc/symbol 层与向量编码仍用原查询。
276
+ const qsLayers = qs.map(gatedQueryText)
177
277
  const want = new Set(layers)
178
278
  const idf = store && typeof store.getIdfCache === 'function' ? store.getIdfCache() : {}
179
279
  const buckets = []
@@ -203,13 +303,17 @@ export function recallItems(opts = {}) {
203
303
  }
204
304
 
205
305
  if (want.has('experience')) {
206
- const scored = rankExperienceScored((store && store.experience) || [], qs, limit)
207
- if (scored.length) {
306
+ const expPool = (store && store.experience) || []
307
+ // 有向量时在**全量** BM25 序上融合(见 fuseVectorHits 注释),截断到 limit 放到融合之后;
308
+ // 没有向量时沿用原来的 limit 语义,输出与纯词法路径逐字段一致。
309
+ const scored0 = matchedFloor(rankExperienceScored(expPool, qsLayers, rerank ? expPool.length : limit), qsLayers, Boolean(rerank))
310
+ if (scored0.length) {
311
+ const scored = fuseVectorHits(scored0, qs, rerank).slice(0, limit)
208
312
  const top = scored[0].score || 1
209
313
  buckets.push({
210
314
  layer: 'experience',
211
315
  prior: LAYER_PRIORS.experience,
212
- hits: scored.map(({ item, score }) => ({ item, score, prior: LAYER_PRIORS.experience, weightedScore: score, rel: score / top })),
316
+ hits: scored.map(({ item, score, vector }) => ({ item, score, vector, prior: LAYER_PRIORS.experience, weightedScore: score, rel: score / top })),
213
317
  })
214
318
  }
215
319
  }
@@ -218,13 +322,14 @@ export function recallItems(opts = {}) {
218
322
  const pool = entries !== null
219
323
  ? entries.filter((e) => e && e.type === 'insight')
220
324
  : visibleInsights({ store, globalStore, boundTaskId }).map(insightToEntry)
221
- const scored = rankEntriesMergedScored(pool, qs, limit)
222
- if (scored.length) {
325
+ const scored0 = matchedFloor(rankEntriesMergedScored(pool, qsLayers, rerank ? pool.length : limit), qsLayers, Boolean(rerank))
326
+ if (scored0.length) {
327
+ const scored = fuseVectorHits(scored0.map((r) => ({ item: r.entry, score: r.score })), qs, rerank).slice(0, limit)
223
328
  const top = scored[0].score || 1
224
329
  buckets.push({
225
330
  layer: 'insight',
226
331
  prior: LAYER_PRIORS.insight,
227
- hits: scored.map(({ entry, score }) => ({ item: entry, score, prior: LAYER_PRIORS.insight, weightedScore: score, rel: score / top })),
332
+ hits: scored.map(({ item, score, vector }) => ({ item, score, vector, prior: LAYER_PRIORS.insight, weightedScore: score, rel: score / top })),
228
333
  })
229
334
  }
230
335
  }
@@ -193,7 +193,8 @@ export function onSessionEvent(config, session, event, meta) {
193
193
  if (task && !task.archived) {
194
194
  task.lastHumanAt = now
195
195
  task.updatedAt = now
196
- s._dirtyTasks = true
196
+ // 直接改了 task 内容就必须走标脏入口:只手置 _dirtyTasks 会漏掉驻留估算的新版本维。
197
+ s.markTasksDirty()
197
198
  }
198
199
  })
199
200
  } catch {
@@ -240,7 +241,7 @@ export function onSessionEvent(config, session, event, meta) {
240
241
  task.updatedAt = now
241
242
  task.lastActiveAt = now
242
243
  task.lastSessionId = sessionId
243
- s._dirtyTasks = true
244
+ s.markTasksDirty()
244
245
  })
245
246
  return
246
247
  }
@@ -267,7 +268,7 @@ export function onSessionEvent(config, session, event, meta) {
267
268
  if (!task || task.archived) return
268
269
  touchTaskFile(task, rel, kind, now)
269
270
  task.lastActiveAt = now
270
- s._dirtyTasks = true
271
+ s.markTasksDirty()
271
272
  })
272
273
  }
273
274
  }