@yolk_vat-y/dsh-project-memory 0.5.5 → 0.5.7

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.
@@ -9,13 +9,15 @@ import { createHash } from 'node:crypto'
9
9
  import { createUserMessage } from '@deepseek-ai/dsh-llm'
10
10
  import { ProjectMemoryStore } from './store.js'
11
11
  import { memoryRootFor } from './util/fs.js'
12
- import { insightMatchText } from './similarity.js'
13
- import { normalizedTokenOverlap } from './similarity.js'
12
+ import { insightMatchText, normalizedTokenOverlap } from './similarity.js'
13
+ import { BoundedMap, SessionCache } from './util/session-cache.js'
14
14
  import { cfgInsight, GlobalStore, defaultGlobalFile } from './insight-store.js'
15
15
  import { projectTags } from './project-profile.js'
16
16
  import { rankEntriesMergedScored } from './util/search.js'
17
- import { insightToEntry } from './recall.js'
18
- import { buildReadinessContext, hintQueryText, matchTrigger, relativeHits } from './readiness.js'
17
+ import { insightToEntry, insightScoringText } from './recall.js'
18
+ import { buildReadinessContext, hintQueryText, idfCoverage, matchTrigger, normalizeTrigger, relativeHits } from './readiness.js'
19
+ import { activityFromCalls } from './ops.js'
20
+ import { appendInjectionAudit, auditRecordFrom, cfgAudit } from './audit.js'
19
21
 
20
22
  export const INJECT_MARK = '[Memory Inject]'
21
23
 
@@ -40,6 +42,8 @@ export function cfgEngine(config) {
40
42
  relevanceMin: typeof c.relevanceMin === 'number' ? c.relevanceMin : null,
41
43
  // resident 任务卡最多显示几个"编辑中"文件(纯写权重,最近写优先)
42
44
  editedMax: typeof c.editedMax === 'number' ? c.editedMax : 3,
45
+ // 常驻任务卡总开关(entryOn:false = 只做条目注入,不回声任务卡)
46
+ entryOn: c.entryOn !== false,
43
47
  // 模型自己写/维护任务清单后、尚无新人类消息时,不把任务卡再回声给模型(省 token)
44
48
  skipEchoSelfTodo: c.skipEchoSelfTodo !== false,
45
49
  // 预算审计日志级别(stderr)。默认 off:预算挤掉低优先级条目是正常降级,不是故障,
@@ -52,6 +56,25 @@ export function cfgEngine(config) {
52
56
  // 0(默认)= 内容没变就不再注入:注入消息会留在会话历史里(宿主不压缩历史),
53
57
  // 整块重发同一条 1200 字 procedure 只是重复占位。>0 用于历史可能被外部裁剪的场景。
54
58
  reinjectItemsAfter: typeof c.reinjectItemsAfter === 'number' && c.reinjectItemsAfter >= 0 ? c.reinjectItemsAfter : 0,
59
+ // ---- S2/S3/S4 新增(准入化改造) ----
60
+ // 旧 `scope` 的处理:'filter'(默认,保留旧语义——不静默改用户数据)或 'ignore'。
61
+ // 注意:实测里唯一带 scope 的条目,其值不在项目画像 tag 空间内,等于被判死刑;
62
+ // 自检会把它报出来,由作者决定改值还是改语义。
63
+ legacyScope: c.legacyScope === 'ignore' ? 'ignore' : 'filter',
64
+ // 条目通道的步间隔:两次"条目注入"之间至少隔这么多步(常驻任务卡不受限——它是状态快照,
65
+ // 内容变了就该更新)。这是"不频繁"的主要旋钮。
66
+ gateCooldownSteps: typeof c.gateCooldownSteps === 'number' && c.gateCooldownSteps >= 0 ? c.gateCooldownSteps : 2,
67
+ // 每会话条目注入的上限(条数 / 字符):预算只能是上限,不是目标。
68
+ maxItemsPerSession: typeof c.maxItemsPerSession === 'number' && c.maxItemsPerSession >= 0 ? c.maxItemsPerSession : 12,
69
+ maxItemCharsPerSession: typeof c.maxItemCharsPerSession === 'number' && c.maxItemCharsPerSession >= 0 ? c.maxItemCharsPerSession : 4000,
70
+ // 提示通道的**绝对**下限(IDF 加权覆盖率):相对阈值分不出"有信号"和"矮子里拔将军"。
71
+ // null = 关闭(回到只有相对阈值的老行为)。
72
+ hintMinCoverage: typeof c.hintMinCoverage === 'number' && c.hintMinCoverage >= 0 ? c.hintMinCoverage : 0.3,
73
+ // 提示通道还要求至少这么多个共同词:单个通用词("插件")也能拿到 coverage=1.00。
74
+ hintMinMatched: typeof c.hintMinMatched === 'number' && c.hintMinMatched >= 0 ? c.hintMinMatched : 2,
75
+ // 通道级沉默:查询里能在语料中找到对应的词占比低于这个值时,整条提示通道本轮不出声。
76
+ // 长句子里只有一两个词碰巧命中,coverage 会虚高到 1.00——这条门就是为它设的。
77
+ hintMinSupport: typeof c.hintMinSupport === 'number' && c.hintMinSupport >= 0 ? c.hintMinSupport : 0.15,
55
78
  }
56
79
  }
57
80
 
@@ -74,6 +97,9 @@ export function lastUserText(messages) {
74
97
  // 真人消息优先:本插件注入的块也是 role=user,若按"最后一条 user"取,
75
98
  // 上一步的注入块会变成这一步的就绪查询(自激:拿自己注入的内容再检索一遍)。
76
99
  if (m.source && m.source.kind === 'user') return t.trim()
100
+ // 本插件注入的块同样是 role=user。无 source 的老宿主下若把它当兜底查询,
101
+ // 就成了"拿自己上一步注入的内容再检索一遍"的自激——正是 kind==='user' 这道闸要防的。
102
+ if (m.source && m.source.plugin === 'dsh-project-memory') continue
77
103
  if (!fallback) fallback = t.trim() // 无 source 的消息(老宿主 / 测试)兜底
78
104
  }
79
105
  return fallback
@@ -121,17 +147,26 @@ export function buildEntryContent(task, cfg, { withEdited = true } = {}) {
121
147
  if (!task) return ''
122
148
  const c = cfg || {}
123
149
  const steps = (task.steps || []).map((s) => (typeof s === 'string' ? s : s.content || s.text || '').slice(0, 80))
124
- const card = [`任务: ${task.title || '(untitled)'}`, `进度: ${steps.filter((s) => true).length ? `${steps.length} 步` : ''}`, ...steps.slice(0, 12).map((s, i) => ` ${i + 1}. ${s}`)]
150
+ const progress = steps.length ? `${steps.length} 步` : ''
151
+ const card = [
152
+ `任务: ${task.title || '(untitled)'}`,
153
+ `进度: ${progress}`,
154
+ ...steps.slice(0, 12).map((s, i) => ` ${i + 1}. ${s}`),
155
+ ]
125
156
  const insights = linesOf(task.insights)
126
- const edited = editedFiles(task, c.editedMax || 3)
157
+ // 0 是合法值(= 不显示):cfgEngine 已归一成数字,这里不能再用 `||` 把 0 顶回默认。
158
+ const maxEdited = Number.isFinite(c.editedMax) ? c.editedMax : 3
159
+ const maxInsights = Number.isFinite(c.entryMaxInsights) ? c.entryMaxInsights : 6
160
+ const edited = editedFiles(task, maxEdited)
127
161
  const parts = [...card]
128
162
  if (withEdited && edited.length) parts.push(` 编辑中: ${edited.join(', ')}`)
129
- if (insights.length) parts.push(`任务记忆:`, ...insights.slice(0, c.entryMaxInsights || 6))
163
+ if (insights.length) parts.push(`任务记忆:`, ...insights.slice(0, maxInsights))
130
164
  return parts.join('\n')
131
165
  }
132
166
 
133
- /** 候选池:project + global + 绑定任务(同一 id 只取一次;归档/草稿不进注入)。 */
134
- function insightCandidates(store, globalStore, task) {
167
+ /** 候选池:project + global + 绑定任务(同一 id 只取一次;归档/草稿不进注入)。
168
+ * 候选在进入匹配前统一走旧 trigger → 新 schema 的归一(幂等,纯内存,不落盘)。 */
169
+ function insightCandidates(store, globalStore, task, opts) {
135
170
  const out = []
136
171
  const seen = new Set()
137
172
  const push = (it) => {
@@ -139,7 +174,7 @@ function insightCandidates(store, globalStore, task) {
139
174
  const key = it.id || `${it.kind}:${it.title}`
140
175
  if (seen.has(key)) return
141
176
  seen.add(key)
142
- out.push(it)
177
+ out.push(normalizeTrigger(it, { legacyScope: opts?.legacyScope }))
143
178
  }
144
179
  for (const it of (store ? store.insightItems() : []) || []) push(it)
145
180
  for (const it of (globalStore ? globalStore.items() : []) || []) push(it)
@@ -161,11 +196,85 @@ export function insightItemHash(it) {
161
196
 
162
197
  /** 把正文塞进剩余预算:放不下就截断;连"有用前缀"都留不下就返回 null(由调用方记 dropped)。 */
163
198
  export function fitBody(body, remaining, min = MIN_BODY_CHARS.hint) {
164
- if (remaining <= min) return null
199
+ if (remaining < min) return null
165
200
  if (body.length <= remaining) return body
166
201
  return `${body.slice(0, remaining - 1)}…`
167
202
  }
168
203
 
204
+ /**
205
+ * 通道 1:authored trigger 命中(确定性、全文、优先级 1)。procedure 先于其它 kind(步骤更完整)。
206
+ * 准入化(S2):只有 `when`(op / 写目标 / 意图词)能触发,guard 只能收窄;
207
+ * **没有 `when` 的条目在这里永远不命中**(降级为可发现 + 按需拉取)。
208
+ */
209
+ function collectTriggered(cands, ctx) {
210
+ const hits = []
211
+ for (const it of cands) {
212
+ const why = matchTrigger(it.trigger, ctx)
213
+ if (why) hits.push({ it, why })
214
+ }
215
+ hits.sort(
216
+ (a, b) => (a.it.kind === 'procedure' ? 0 : 1) - (b.it.kind === 'procedure' ? 0 : 1)
217
+ || String(a.it.id).localeCompare(String(b.it.id)),
218
+ )
219
+ return hits
220
+ }
221
+
222
+ /**
223
+ * 通道 2:统计信号(提示态、优先级 2)。**双门槛**:层内相对阈值 + IDF 加权覆盖率(绝对下限)。
224
+ * 查询只用「人类消息的意图文字 + 本次写目标」:原始工具参数不是查询文本,它们正是
225
+ * `dcterms→rm`、`*.pptx→论文笔记` 那类假阳性的来源。被门槛拦下的记进 dropped,不静默。
226
+ */
227
+ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped }) {
228
+ const hints = []
229
+ if (!cands.length) return hints
230
+ if (typeof cfg.relevanceMin === 'number') {
231
+ // 兼容:显式 relevanceMin → 旧的绝对 overlap 判据(老 profile 行为不变)
232
+ for (const it of cands) {
233
+ const score = normalizedTokenOverlap(humanText || query || '', insightMatchText(it))
234
+ if (score >= cfg.relevanceMin) hints.push({ it, score, why: `overlap:${score.toFixed(3)}` })
235
+ }
236
+ hints.sort((a, b) => b.score - a.score)
237
+ return hints
238
+ }
239
+ const q = hintQueryText(hintQuery)
240
+ if (!q) return hints
241
+ const byId = new Map(cands.map((it) => [it.id, it]))
242
+ // 覆盖率语料必须与 BM25 排序同源(insightScoringText):否则"只在 fix/solution 里有匹配"
243
+ // 的查询词 df=0 → supportRatio=0 → 整条提示通道沉默,而排序明明给了它高分。
244
+ const corpus = cands.map((it) => insightScoringText(it))
245
+ // 查询与被测覆盖率的文本用**同一个**过滤后的查询:否则缩写(wsl/npm)会在 BM25 里被剔除、
246
+ // 却仍在覆盖率里计分,"至少两个共同词"就被它们凑够了。
247
+ const scored = rankEntriesMergedScored(cands.map(insightToEntry), [q], cands.length)
248
+ const coverage = new Map(cands.map((it, i) => [it.id, idfCoverage(q, corpus[i], corpus)]))
249
+ const qStats = coverage.get(cands[0].id) || { supported: 0, terms: 0 }
250
+ const supportRatio = qStats.terms > 0 ? qStats.supported / qStats.terms : 0
251
+ // 通道级沉默:查询里绝大多数词在语料里根本没有对应 → "覆盖率 1.00"只是假象。
252
+ const channelThin = typeof cfg.hintMinSupport === 'number' && supportRatio < cfg.hintMinSupport
253
+ for (const r of relativeHits(scored, { ratioMin: cfg.signalMinRatio })) {
254
+ const it = byId.get(r.entry.insightId)
255
+ if (!it) continue
256
+ const ev = coverage.get(it.id) || { coverage: 0, matched: 0, supported: 0, terms: 0 }
257
+ if (channelThin) {
258
+ dropped.push({ id: it.id, channel: 'hint', reason: `support:${supportRatio.toFixed(2)}` })
259
+ continue
260
+ }
261
+ // 绝对门槛:覆盖率下限 + 共同词数下限(查询本身很短时下限按可用词数收敛)。
262
+ if (typeof cfg.hintMinCoverage === 'number' && ev.coverage < cfg.hintMinCoverage) {
263
+ dropped.push({ id: it.id, channel: 'hint', reason: `coverage:${ev.coverage.toFixed(2)}` })
264
+ continue
265
+ }
266
+ // 共同词数下限按**查询本身的词数**收敛(查询很短时不强求两个),而不是按"语料能表示的词数":
267
+ // 后者在长而杂的查询上会退化成 1,一个碰巧命中的通用词就能过闸。
268
+ const needMatched = Math.min(typeof cfg.hintMinMatched === 'number' ? cfg.hintMinMatched : 2, ev.terms)
269
+ if (ev.matched < needMatched) {
270
+ dropped.push({ id: it.id, channel: 'hint', reason: `thin:${ev.matched}` })
271
+ continue
272
+ }
273
+ hints.push({ it, score: r.score, why: `relative:${(r.score / (scored[0].score || 1)).toFixed(2)} cov:${ev.coverage.toFixed(2)}/${ev.matched}` })
274
+ }
275
+ return hints
276
+ }
277
+
169
278
  /**
170
279
  * 构建注入内容(不写盘、无副作用)。
171
280
  *
@@ -181,144 +290,160 @@ export function buildInjection(opts) {
181
290
  const { query, task, globalStore, cfg } = opts
182
291
  const store = opts.store || null
183
292
  const tags = opts.projectTagsList || []
184
- const ctx = buildReadinessContext(opts.readiness || { humanText: query || '' })
293
+ const ctx = buildReadinessContext({ ...(opts.readiness || { humanText: query || '' }), tags })
185
294
  const labels = []
186
295
  const reasons = []
187
296
  const dropped = []
188
297
  const parts = []
189
- const budgetChars = (cfg.maxTokens || 400) * 3
298
+ // 预算只能是上限,不是目标。两条额度分开:
299
+ // stepBudget —— 单轮(常驻块 + 条目)共享的 maxTokens;
300
+ // itemBudget —— 条目还受会话字符额度约束;**常驻块不占这条**(它是状态快照,文档明说不受限)。
301
+ // 旧实现把两者取小成同一个 budgetChars,会话额度用尽后连任务卡都被截成 `…(截断)`。
302
+ const quotaChars = typeof opts.maxChars === 'number' ? opts.maxChars : Infinity
303
+ const maxItems = typeof opts.maxItems === 'number' ? opts.maxItems : Infinity
304
+ const skipItems = opts.skipItems === true
305
+ const stepBudget = Math.max(0, (cfg.maxTokens || 400) * 3)
306
+ const itemBudget = Math.max(0, Math.min(stepBudget, quotaChars))
190
307
 
191
308
  const skipItem = typeof opts.skipItem === 'function' ? opts.skipItem : null
192
- const cands = insightCandidates(store, globalStore, task).filter((it) => !(skipItem && skipItem(it)))
309
+ const cands = insightCandidates(store, globalStore, task, cfg).filter((it) => !(skipItem && skipItem(it)))
193
310
 
194
- // 通道 1:authored trigger —— 确定性、全文、优先级 1。procedure 先于其它 kind(步骤更完整)。
195
- const triggered = []
196
- for (const it of cands) {
197
- const why = matchTrigger(it.trigger, ctx)
198
- if (!why) continue
199
- const scope = it.trigger?.scope
200
- if (Array.isArray(scope) && scope.length && tags.length && !scope.some((s) => tags.includes(s))) continue
201
- triggered.push({ it, why })
311
+ // 两条通道:authored trigger(确定性、全文、优先级 1)→ 统计信号提示(优先级 2)。
312
+ const triggered = collectTriggered(cands, ctx)
313
+ if (skipItems) {
314
+ // 会话级限流命中:条目通道本轮整体沉默,但把"本该注入什么"记进 dropped——不做静默降级。
315
+ for (const { it } of triggered) dropped.push({ id: it.id, channel: 'trigger', reason: opts.silenceReason || 'cooldown' })
202
316
  }
203
- triggered.sort(
204
- (a, b) => (a.it.kind === 'procedure' ? 0 : 1) - (b.it.kind === 'procedure' ? 0 : 1)
205
- || String(a.it.id).localeCompare(String(b.it.id)),
206
- )
207
-
208
- // 通道 2:统计信号 —— 提示态、优先级 2,判据是层内相对阈值(尺度无关)。
209
- // procedure 只走 trigger 通道:否则会被统计通道绕过 trigger.scope 的画像过滤。
317
+ // procedure 不进提示通道:它要过 trigger.scope(见 scoreHints 注释)。
210
318
  const consumed = new Set(triggered.map((t) => t.it.id))
211
- const hintCands = cands.filter((it) => !consumed.has(it.id) && it.kind !== 'procedure')
212
- const hints = []
213
- if (hintCands.length) {
214
- if (typeof cfg.relevanceMin === 'number') {
215
- // 兼容:显式 relevanceMin → 旧的绝对 overlap 判据(老 profile 行为不变)
216
- for (const it of hintCands) {
217
- const score = normalizedTokenOverlap(ctx.humanText || query || '', insightMatchText(it))
218
- if (score >= cfg.relevanceMin) hints.push({ it, score, why: `overlap:${score.toFixed(3)}` })
219
- }
220
- hints.sort((a, b) => b.score - a.score)
221
- } else {
222
- const byId = new Map(hintCands.map((it) => [it.id, it]))
223
- // 提示查询先剔除 1–2 字符的拉丁缩写(PR/CI/OS):它们一个巧合命中就能当上该层最高分。
224
- const scored = rankEntriesMergedScored(
225
- hintCands.map(insightToEntry),
226
- [hintQueryText(ctx.humanText), hintQueryText(ctx.actionText)].filter(Boolean),
227
- hintCands.length,
228
- )
229
- for (const r of relativeHits(scored, { ratioMin: cfg.signalMinRatio })) {
230
- const it = byId.get(r.entry.insightId)
231
- if (it) hints.push({ it, score: r.score, why: `relative:${(r.score / (scored[0].score || 1)).toFixed(2)}` })
232
- }
233
- }
234
- }
319
+ const hintCands = skipItems ? [] : cands.filter((it) => !consumed.has(it.id) && it.kind !== 'procedure')
320
+ const hints = scoreHints({
321
+ cands: hintCands,
322
+ query,
323
+ humanText: ctx.humanText,
324
+ hintQuery: [ctx.intent || ctx.humanText || '', ...(ctx.targets || [])].filter(Boolean).join(' '),
325
+ cfg,
326
+ dropped,
327
+ })
235
328
 
236
329
  // 常驻块文本。去重指纹只看稳定内容(任务标题/步骤/insights + 相关 insights):
237
330
  // “编辑中”随每次写文件变化,若参与指纹会导致每写一个文件就重发整块(噪音 + token 浪费)。
238
- const echo = shouldEchoTaskCard(task, cfg)
331
+ const echo = cfg.entryOn !== false && shouldEchoTaskCard(task, cfg)
239
332
  const entry = echo ? buildEntryContent(task, cfg) : ''
240
333
  const entryStable = echo ? buildEntryContent(task, cfg, { withEdited: false }) : ''
241
334
  let used = entry.length
335
+ let itemUsed = 0
336
+ let itemCount = 0
242
337
 
243
- for (const { it, why } of triggered) {
244
- const body = fitBody(insightBody(it), budgetChars - used, MIN_BODY_CHARS.trigger)
245
- if (body === null) {
246
- dropped.push({ id: it.id, channel: 'trigger', reason: 'budget' })
247
- continue
338
+ /** 把一组候选按优先级放进剩余预算:放不下的进 dropped(quota / budget),不静默。 */
339
+ const place = (channel, list, minChars, labelOf) => {
340
+ for (const { it, why } of list) {
341
+ if (itemCount >= maxItems) {
342
+ dropped.push({ id: it.id, channel, reason: 'quota' })
343
+ continue
344
+ }
345
+ // 条目同时受"单轮剩余"与"会话字符剩余"约束;常驻块只占前者。
346
+ const remaining = Math.min(stepBudget - used, itemBudget - itemUsed)
347
+ const body = fitBody(insightBody(it), remaining, minChars)
348
+ if (body === null) {
349
+ dropped.push({ id: it.id, channel, reason: 'budget' })
350
+ continue
351
+ }
352
+ used += body.length + 1
353
+ itemUsed += body.length + 1
354
+ itemCount++
355
+ parts.push(body)
356
+ labels.push(labelOf(it))
357
+ reasons.push({ id: it.id, channel, why, hash: insightItemHash(it), chars: body.length })
248
358
  }
249
- used += body.length + 1
250
- parts.push(body)
251
- labels.push(it.kind === 'procedure' ? 'procedure' : it.kind)
252
- reasons.push({ id: it.id, channel: 'trigger', why, hash: insightItemHash(it) })
253
359
  }
254
- for (const { it, why } of hints) {
255
- const body = fitBody(insightBody(it), budgetChars - used, MIN_BODY_CHARS.hint)
256
- if (body === null) {
257
- dropped.push({ id: it.id, channel: 'hint', reason: 'budget' })
258
- continue
259
- }
260
- used += body.length + 1
261
- parts.push(body)
262
- labels.push('hint')
263
- reasons.push({ id: it.id, channel: 'hint', why, hash: insightItemHash(it) })
360
+ // 限流命中时条目通道整体沉默:triggered 已在上方记进 dropped,这里不再重复排程。
361
+ if (!skipItems) {
362
+ place('trigger', triggered, MIN_BODY_CHARS.trigger, (it) => it.kind)
363
+ place('hint', hints, MIN_BODY_CHARS.hint, () => 'hint')
264
364
  }
265
365
 
266
366
  const total = [entry, ...parts].filter(Boolean)
267
- if (!total.length) return { text: '', labels, reasons, dropped }
268
- const clamp = (t) => (t.length > budgetChars ? `${t.slice(0, budgetChars)}\n…(截断)` : t)
367
+ if (!total.length) return { text: '', entry, labels, reasons, dropped }
368
+ // 整块只受单轮预算(maxTokens)约束;会话条目额度已在 place() 里单独扣过。
369
+ const clamp = (t) => (t.length > stepBudget ? `${t.slice(0, stepBudget)}\n…(截断)` : t)
269
370
  const dedupeText = clamp([entryStable, ...parts].filter(Boolean).join('\n'))
270
- return { text: clamp(total.join('\n')), labels, reasons, dropped, dedupeText }
371
+ return { text: clamp(total.join('\n')), entry, entryStable, labels, reasons, dropped, dedupeText, itemChars: itemUsed }
271
372
  }
272
373
 
273
- /** 注册 agent/pre-step 监听,向每步请求的 enter 决策追加记忆消息(默认开)。
274
- * 宿主瀑布事件签名为 (payload, next):payload.agent.session 提供会话(header.cwd=项目根)。
275
- * 任何异常/无会话 cwd → 原样返回默认决策,零副作用,绝不让宿主请求受影响。
374
+ // 每会话状态的会话数上限:六张表共用(旧实现把同一个 200 在五处各写一遍)。
375
+ const SESSION_STATE_MAX = 200
376
+ // 单会话已注入条目表的条数上限。
377
+ const INJECTED_ITEMS_MAX = 600
378
+ // 单会话保留的 tool/call 观察窗口(够覆盖"最近几步在做什么")。
379
+ const OBSERVED_CALLS_MAX = 8
380
+
381
+ /**
382
+ * 注入引擎的「每会话一份」状态。
383
+ *
384
+ * 之前六张表散在 installAutoInject 里、各自 hand-roll 淘汰循环,同一个
385
+ * `while (map.size > CAP) map.delete(map.keys().next().value)` 抄了五遍:容量上限写在五处,
386
+ * 抄漏一处就是无界增长,dispose 时也漏清两张表。容量只在这里定义一次。
276
387
  */
277
- export function installAutoInject(ctx, config) {
278
- const auto = (config && config.autoContext) || {}
279
- if (auto.enabled === false) return
280
- const cfg = cfgEngine(config)
281
- // 每个会话一份“上次注入指纹”。用单个变量会让并发会话互相抑制注入。
282
- const lastFpBySession = new Map()
283
- const LAST_FP_MAX = 200
284
- // 每个会话一份"上次预算丢弃指纹":预算把条目挤出去时必须留痕一次,而不是静默(degraded 可见性)。
285
- const lastDroppedBySession = new Map()
286
- // 条目级去重记忆:sessionId → Map(insightId → { hash, step })。注入的消息留在会话历史里
287
- // (宿主只追加、不压缩),所以"整块指纹变了"不等于"内容都是新的"——同一份 procedure 会因为
288
- // 滑动工具窗口、任务卡更新、预算截断边界变化被整块重发(实测 66 步注入 20 次,其中同一份
289
- // 1732 字 procedure 重发 3 次、另一份 1008 字的 6 次)。这里按条目记账,正文没变就不再排程。
290
- const injectedBySession = new Map()
291
- const INJECTED_ITEMS_MAX = 600
292
- // 会话步数:为 reinjectItemsAfter 提供时间轴(>0 时才用得上)。
293
- const stepBySession = new Map()
294
- // 反应窗口:本会话最近观察到的 tool/call(参数里有 git commit / npm publish / 改动的路径)。
295
- // 宿主没有"工具执行前拦截"钩子,所以这是 pre-step 之外唯一能拿到的动作事实。
296
- const observedBySession = new Map()
297
- const OBSERVED_MAX = 8
298
- const OBSERVED_SESSIONS = 200
388
+ class InjectionSessions {
389
+ constructor() {
390
+ const cache = (create) => new SessionCache({ maxSessions: SESSION_STATE_MAX, create })
391
+ // 上次注入指纹:用单个变量会让并发会话互相抑制注入。
392
+ this.lastText = cache()
393
+ // 上次预算丢弃签名:预算把条目挤出去时必须留痕一次,而不是静默(degraded 可见性)。
394
+ this.lastDropped = cache()
395
+ // 条目级去重记忆:insightId → { hash, step }。注入的消息留在 append-only 的会话历史里,
396
+ // 所以"整块指纹变了"不等于"内容都是新的":滑动工具窗口 / 任务卡更新 / 预算截断边界都会
397
+ // 让同一份 procedure 被整块重发(实测 66 步注入 20 次,同一份 1732 字重发 3 次)。
398
+ this.items = cache(() => new BoundedMap(INJECTED_ITEMS_MAX))
399
+ // 会话步数:为 reinjectItemsAfter 提供时间轴。
400
+ this.step = cache(() => 0)
401
+ // 会话级条目额度(S3):条数 / 字符 / 上次"条目注入"的步号。常驻任务卡不占额度——
402
+ // 它是状态快照,内容变了就该更新;被限流的是记忆条目的推送。
403
+ this.quota = cache(() => ({ items: 0, chars: 0, lastStep: -Infinity }))
404
+ // 反应窗口:本会话最近观察到的 tool/call(参数里有 git commit / npm publish / 改动的路径)。
405
+ // 宿主没有"工具执行前拦截"钩子,所以这是 pre-step 之外唯一能拿到的动作事实。
406
+ this.observed = cache(() => [])
407
+ this._all = Object.values(this)
408
+ }
409
+
410
+ clear() {
411
+ for (const cache of this._all) cache.clear()
412
+ }
413
+ }
414
+
415
+ /** 记录会话里的 tool/call:ops.js 从这些参数解析出 op / 写目标 / 主机。 */
416
+ function installCallObserver(ctx, sessions) {
299
417
  ctx.on('session/event', (session, event) => {
300
418
  try {
301
419
  if (!event || event.type !== 'tool/call') return
302
- const sid = session && session.id
303
- if (!sid) return
420
+ const sessionId = session && session.id
421
+ if (!sessionId) return
304
422
  const data = event.data || {}
305
- const rec = observedBySession.get(sid) || []
306
- rec.push({ name: String(data.name || ''), arguments: String(data.arguments || '') })
307
- while (rec.length > OBSERVED_MAX) rec.shift()
308
- observedBySession.set(sid, rec)
309
- while (observedBySession.size > OBSERVED_SESSIONS) {
310
- observedBySession.delete(observedBySession.keys().next().value)
311
- }
423
+ const calls = sessions.observed.ensure(sessionId)
424
+ calls.push({ name: String(data.name || ''), arguments: String(data.arguments || '') })
425
+ if (calls.length > OBSERVED_CALLS_MAX) calls.shift()
312
426
  } catch {
313
427
  // 观察失败绝不影响宿主请求
314
428
  }
315
429
  })
430
+ }
431
+
432
+ /** 注册 agent/pre-step 监听,向每步请求的 enter 决策追加记忆消息(默认开)。
433
+ * 宿主瀑布事件签名为 (payload, next):payload.agent.session 提供会话(header.cwd=项目根)。
434
+ * 任何异常/无会话 cwd → 原样返回默认决策,零副作用,绝不让宿主请求受影响。
435
+ */
436
+ export function installAutoInject(ctx, config) {
437
+ const auto = (config && config.autoContext) || {}
438
+ if (auto.enabled === false) return
439
+ const cfg = cfgEngine(config)
440
+ // 审计配置同 cfg:安装时解析一次(与 autoContext 其余开关一致)。
441
+ const audit = cfgAudit(config)
442
+ const sessions = new InjectionSessions()
443
+
444
+ installCallObserver(ctx, sessions)
316
445
  if (typeof ctx.effect === 'function') {
317
- ctx.effect(() => () => {
318
- observedBySession.clear()
319
- injectedBySession.clear()
320
- stepBySession.clear()
321
- })
446
+ ctx.effect(() => () => sessions.clear())
322
447
  }
323
448
  ctx.on('agent/pre-step', async (payload, next) => {
324
449
  // 宿主契约是 waterfall(payload, next),next 一定存在;但一旦宿主版本漂移、或事件被当
@@ -330,90 +455,151 @@ export function installAutoInject(ctx, config) {
330
455
  if (!decision) return fallback()
331
456
  if (decision.kind !== 'enter') return decision
332
457
  try {
333
- const agent = payload && payload.agent
334
- const session = agent && agent.session
335
- const root = session && session.header && session.header.cwd
336
- const sessionId = session && session.id
337
- if (!root || !sessionId) return decision
338
- const query = lastUserText(decision.messages)
339
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
340
- const globalStore = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
341
- const boundTaskId = store.getBoundTaskId(sessionId) ? store.getBoundTaskId(sessionId) : null
342
- const task = boundTaskId ? store.getTask(boundTaskId) : null
343
- // 两个窗口合并进同一个就绪上下文:人类消息(先发)+ 已观察动作(反应)。
344
- const observed = observedBySession.get(sessionId) || []
345
- const readiness = buildReadinessContext({
346
- humanText: query || '',
347
- actionText: observed.map((c) => `${c.name} ${c.arguments}`).join('\n'),
348
- })
349
- // 条目级去重:本会话已注入过、且正文未变的条目不再参与排程(cfg.reinjectItemsAfter=0 时永久,
350
- // >0 时走冷却步数,用于历史可能被外部裁剪的场景)。正文变了(编辑过 insight)立刻允许重发。
351
- const stepNo = (stepBySession.get(sessionId) || 0) + 1
352
- stepBySession.set(sessionId, stepNo)
353
- while (stepBySession.size > LAST_FP_MAX) stepBySession.delete(stepBySession.keys().next().value)
354
- const seen = injectedBySession.get(sessionId) || new Map()
355
- injectedBySession.set(sessionId, seen)
356
- while (injectedBySession.size > LAST_FP_MAX) injectedBySession.delete(injectedBySession.keys().next().value)
357
- const cooldown = cfg.reinjectItemsAfter || 0
358
- const skipItem = cooldown === 0
359
- ? (it) => {
360
- const rec = seen.get(it.id)
361
- return Boolean(rec) && rec.hash === insightItemHash(it)
362
- }
363
- : (it) => {
364
- const rec = seen.get(it.id)
365
- return Boolean(rec) && rec.hash === insightItemHash(it) && stepNo - rec.step < cooldown
366
- }
367
- const built = buildInjection({ query: query || '', readiness, task, store, globalStore, projectTagsList: projectTags(root), cfg, skipItem })
368
- const fp = fingerprint(built.dedupeText ?? built.text)
369
- const shouldInject = Boolean(built.text) && fp !== lastFpBySession.get(sessionId)
370
- let injectMessage = null
371
- if (shouldInject) {
372
- // 以宿主 createUserMessage 构造的完整 user 消息追加(带 id/source,plan-mode narration 同款)。
373
- // 裸 {role,content} 消息缺 source 会让宿主逐条读 message.source.kind 时崩溃。
374
- lastFpBySession.set(sessionId, fp)
375
- if (lastFpBySession.size > LAST_FP_MAX) lastFpBySession.delete(lastFpBySession.keys().next().value)
376
- // 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
377
- for (const r of built.reasons) {
378
- if (r && r.id && r.hash) seen.set(r.id, { hash: r.hash, step: stepNo })
379
- }
380
- while (seen.size > INJECTED_ITEMS_MAX) seen.delete(seen.keys().next().value)
381
- injectMessage = createUserMessage({
382
- content: [{ type: 'text', text: `\n\n${INJECT_MARK} auto-context\n${built.text}` }],
383
- // 这一块是「同一生产者后续快照会取代的当前状态」,不是一次性通知。
384
- // 宿主 ContextFormed 是判别联合:snapshot 必须带 sections(notice 才需要 summary)。
385
- // 通道不变(仍走 agent/pre-step 追加 user 消息),只修语义。
386
- source: {
387
- kind: 'plugin',
388
- plugin: 'dsh-project-memory',
389
- form: 'snapshot',
390
- sections: [{ name: 'project-memory', text: built.text }],
391
- },
392
- })
393
- }
394
- // 未注入 ≠ 无事发生:因预算被挤掉的条目按 cfg.budgetLog 留痕(默认 off,见 cfgEngine)。
395
- // 留痕仍然记账(去重 + 上限),只是默认不外泄到用户的终端。
396
- if (built.dropped && built.dropped.length && cfg.budgetLog !== 'off') {
397
- const sig = built.dropped.map((d) => `${d.id}:${d.reason}`).join(',')
398
- if (lastDroppedBySession.get(sessionId) !== sig) {
399
- const seenBefore = lastDroppedBySession.has(sessionId)
400
- lastDroppedBySession.set(sessionId, sig)
401
- while (lastDroppedBySession.size > LAST_FP_MAX) {
402
- lastDroppedBySession.delete(lastDroppedBySession.keys().next().value)
403
- }
404
- // once:只有本会话第一次丢弃出声,之后继续记账但保持安静。
405
- if (cfg.budgetLog === 'all' || !seenBefore) {
406
- console.error(
407
- `[dsh-project-memory] auto-inject degraded: ${built.dropped.length} insight(s) kept out by budget — `
408
- + built.dropped.map((d) => `${d.id}(${d.reason})`).join(', '),
409
- )
410
- }
411
- }
412
- }
413
- if (injectMessage) return { ...decision, messages: [...decision.messages, injectMessage] }
458
+ return (await injectForStep({ payload, decision, config, cfg, audit, sessions })) || decision
414
459
  } catch (err) {
415
460
  console.error(`[dsh-project-memory] auto-inject skipped: ${err?.message || err}`)
461
+ return decision
416
462
  }
417
- return decision
463
+ })
464
+ }
465
+
466
+ /**
467
+ * 一个 pre-step 的注入决策:解析会话 → 排程 → 必要时构造消息。
468
+ * 返回 null 表示本步无事可做(交回原决策)。
469
+ */
470
+ async function injectForStep({ payload, decision, config, cfg, audit, sessions }) {
471
+ const session = payload && payload.agent && payload.agent.session
472
+ const root = session && session.header && session.header.cwd
473
+ const sessionId = session && session.id
474
+ if (!root || !sessionId) return null
475
+
476
+ const query = lastUserText(decision.messages)
477
+ const memoryRoot = memoryRootFor(root, config.memoryDir)
478
+ const store = new ProjectMemoryStore(memoryRoot).load()
479
+ const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
480
+ const boundTaskId = store.getBoundTaskId(sessionId)
481
+ const task = boundTaskId ? store.getTask(boundTaskId) : null
482
+
483
+ // 两个窗口合并进同一个就绪上下文:人类消息(先发)+ 已观察动作(反应)。
484
+ // 动作平面(S1):把"最近做过什么"解析成 op / 写目标 / 主机——不再把原始参数当文本搜。
485
+ const observed = sessions.observed.ensure(sessionId)
486
+ const activity = activityFromCalls(observed)
487
+ const readiness = buildReadinessContext({
488
+ humanText: query || '',
489
+ actionText: observed.map((c) => `${c.name} ${c.arguments}`).join('\n'),
490
+ ops: activity.ops,
491
+ targets: activity.targets,
492
+ hosts: activity.hosts,
493
+ })
494
+
495
+ const stepNo = sessions.step.ensure(sessionId) + 1
496
+ sessions.step.set(sessionId, stepNo)
497
+ const quota = sessions.quota.ensure(sessionId)
498
+ const silence = sessionSilence({ cfg, quota, stepNo })
499
+ // 条目级去重:本会话已注入过、且正文未变的条目不再参与排程(正文被编辑过 → 立刻允许重发)。
500
+ const skipItem = makeSkipItem(sessions.items.ensure(sessionId), stepNo, cfg.reinjectItemsAfter || 0)
501
+
502
+ const built = buildInjection({
503
+ query: query || '',
504
+ readiness,
505
+ task,
506
+ store,
507
+ globalStore,
508
+ projectTagsList: projectTags(root),
509
+ cfg,
510
+ skipItem,
511
+ skipItems: silence.reason !== null,
512
+ silenceReason: silence.reason || 'cooldown',
513
+ maxItems: silence.itemsLeft,
514
+ maxChars: silence.charsLeft,
515
+ })
516
+
517
+ // 未注入 ≠ 无事发生:因预算被挤掉的条目按 cfg.budgetLog 留痕(默认 off,见 cfgEngine)。
518
+ // 留痕仍然记账(去重 + 上限),只是默认不外泄到用户的终端。
519
+ recordDropped({ sessions, sessionId, dropped: built.dropped, budgetLog: cfg.budgetLog })
520
+
521
+ const fp = fingerprint(built.dedupeText ?? built.text)
522
+ if (!built.text || fp === sessions.lastText.peek(sessionId)) return null
523
+ sessions.lastText.set(sessionId, fp)
524
+
525
+ // 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
526
+ const seen = sessions.items.ensure(sessionId)
527
+ for (const r of built.reasons) {
528
+ if (r && r.id && r.hash) seen.set(r.id, { hash: r.hash, step: stepNo })
529
+ }
530
+ // 会话额度只被"条目"消耗;任务卡不算(否则任务一多就把记忆挤没了)。
531
+ if (built.reasons.length) {
532
+ quota.items += built.reasons.length
533
+ quota.chars += typeof built.itemChars === 'number' ? built.itemChars : 0
534
+ quota.lastStep = stepNo
535
+ }
536
+
537
+ // S0 观测:只记真的进了上下文的那一次(dropped 单独出现不写,否则每步刷屏)。
538
+ appendInjectionAudit(memoryRoot, auditRecordFrom({
539
+ sessionId,
540
+ root,
541
+ step: stepNo,
542
+ text: built.text,
543
+ labels: built.labels,
544
+ reasons: built.reasons,
545
+ dropped: built.dropped,
546
+ budget: { items: quota.items, chars: quota.chars, lastStep: Number.isFinite(quota.lastStep) ? quota.lastStep : null },
547
+ silence: silence.reason,
548
+ }), audit)
549
+
550
+ return { ...decision, messages: [...decision.messages, injectionMessage(built.text)] }
551
+ }
552
+
553
+ /**
554
+ * 会话级限流(S3):冷却步数 / 条目条数 / 条目字符。三个任一触顶 → 条目通道整体沉默,
555
+ * 但本轮"本该注入什么"仍会进 dropped(不做静默降级)。
556
+ */
557
+ function sessionSilence({ cfg, quota, stepNo }) {
558
+ const cooling = Number.isFinite(quota.lastStep) && stepNo - quota.lastStep < cfg.gateCooldownSteps
559
+ const itemsLeft = Math.max(0, cfg.maxItemsPerSession - quota.items)
560
+ const charsLeft = Math.max(0, cfg.maxItemCharsPerSession - quota.chars)
561
+ const reason = cooling ? 'cooldown'
562
+ : itemsLeft === 0 ? 'session-items'
563
+ : charsLeft === 0 ? 'session-chars' : null
564
+ return { reason, itemsLeft, charsLeft }
565
+ }
566
+
567
+ /** 条目级去重判据:会话里注入过且正文未变 → 跳过。cooldown=0 永久有效,>0 走步数冷却。 */
568
+ function makeSkipItem(seen, stepNo, cooldown) {
569
+ return (it) => {
570
+ const rec = seen.get(it.id)
571
+ if (!rec || rec.hash !== insightItemHash(it)) return false
572
+ return cooldown === 0 || stepNo - rec.step < cooldown
573
+ }
574
+ }
575
+
576
+ /** 预算丢弃的留痕(cfg.budgetLog):once=每会话首次,all=丢弃组合每变一次。 */
577
+ function recordDropped({ sessions, sessionId, dropped, budgetLog }) {
578
+ if (!dropped || !dropped.length || budgetLog === 'off') return
579
+ const signature = dropped.map((d) => `${d.id}:${d.reason}`).join(',')
580
+ const previous = sessions.lastDropped.peek(sessionId)
581
+ if (previous === signature) return
582
+ sessions.lastDropped.set(sessionId, signature)
583
+ if (budgetLog === 'all' || previous === undefined) {
584
+ console.error(
585
+ `[dsh-project-memory] auto-inject degraded: ${dropped.length} insight(s) kept out by budget — `
586
+ + dropped.map((d) => `${d.id}(${d.reason})`).join(', '),
587
+ )
588
+ }
589
+ }
590
+
591
+ /** 追加的注入消息:必须是带 source 的完整消息——裸 {role,content} 会让宿主读 message.source 时崩。 */
592
+ function injectionMessage(text) {
593
+ return createUserMessage({
594
+ content: [{ type: 'text', text: `\n\n${INJECT_MARK} auto-context\n${text}` }],
595
+ // 这一块是「同一生产者后续快照会取代的当前状态」,不是一次性通知。
596
+ // 宿主 ContextFormed 是判别联合:snapshot 必须带 sections(notice 才需要 summary)。
597
+ // 通道不变(仍走 agent/pre-step 追加 user 消息),只修语义。
598
+ source: {
599
+ kind: 'plugin',
600
+ plugin: 'dsh-project-memory',
601
+ form: 'snapshot',
602
+ sections: [{ name: 'project-memory', text }],
603
+ },
418
604
  })
419
605
  }