@yolk_vat-y/dsh-project-memory 0.5.6 → 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,12 +9,12 @@ 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'
17
+ import { insightToEntry, insightScoringText } from './recall.js'
18
18
  import { buildReadinessContext, hintQueryText, idfCoverage, matchTrigger, normalizeTrigger, relativeHits } from './readiness.js'
19
19
  import { activityFromCalls } from './ops.js'
20
20
  import { appendInjectionAudit, auditRecordFrom, cfgAudit } from './audit.js'
@@ -42,6 +42,8 @@ export function cfgEngine(config) {
42
42
  relevanceMin: typeof c.relevanceMin === 'number' ? c.relevanceMin : null,
43
43
  // resident 任务卡最多显示几个"编辑中"文件(纯写权重,最近写优先)
44
44
  editedMax: typeof c.editedMax === 'number' ? c.editedMax : 3,
45
+ // 常驻任务卡总开关(entryOn:false = 只做条目注入,不回声任务卡)
46
+ entryOn: c.entryOn !== false,
45
47
  // 模型自己写/维护任务清单后、尚无新人类消息时,不把任务卡再回声给模型(省 token)
46
48
  skipEchoSelfTodo: c.skipEchoSelfTodo !== false,
47
49
  // 预算审计日志级别(stderr)。默认 off:预算挤掉低优先级条目是正常降级,不是故障,
@@ -95,6 +97,9 @@ export function lastUserText(messages) {
95
97
  // 真人消息优先:本插件注入的块也是 role=user,若按"最后一条 user"取,
96
98
  // 上一步的注入块会变成这一步的就绪查询(自激:拿自己注入的内容再检索一遍)。
97
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
98
103
  if (!fallback) fallback = t.trim() // 无 source 的消息(老宿主 / 测试)兜底
99
104
  }
100
105
  return fallback
@@ -142,12 +147,20 @@ export function buildEntryContent(task, cfg, { withEdited = true } = {}) {
142
147
  if (!task) return ''
143
148
  const c = cfg || {}
144
149
  const steps = (task.steps || []).map((s) => (typeof s === 'string' ? s : s.content || s.text || '').slice(0, 80))
145
- 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
+ ]
146
156
  const insights = linesOf(task.insights)
147
- 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)
148
161
  const parts = [...card]
149
162
  if (withEdited && edited.length) parts.push(` 编辑中: ${edited.join(', ')}`)
150
- if (insights.length) parts.push(`任务记忆:`, ...insights.slice(0, c.entryMaxInsights || 6))
163
+ if (insights.length) parts.push(`任务记忆:`, ...insights.slice(0, maxInsights))
151
164
  return parts.join('\n')
152
165
  }
153
166
 
@@ -183,11 +196,85 @@ export function insightItemHash(it) {
183
196
 
184
197
  /** 把正文塞进剩余预算:放不下就截断;连"有用前缀"都留不下就返回 null(由调用方记 dropped)。 */
185
198
  export function fitBody(body, remaining, min = MIN_BODY_CHARS.hint) {
186
- if (remaining <= min) return null
199
+ if (remaining < min) return null
187
200
  if (body.length <= remaining) return body
188
201
  return `${body.slice(0, remaining - 1)}…`
189
202
  }
190
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
+
191
278
  /**
192
279
  * 构建注入内容(不写盘、无副作用)。
193
280
  *
@@ -208,131 +295,138 @@ export function buildInjection(opts) {
208
295
  const reasons = []
209
296
  const dropped = []
210
297
  const parts = []
211
- // 预算只能是上限,不是目标:单轮额度(maxTokens)与会话级剩余额度取小者。
298
+ // 预算只能是上限,不是目标。两条额度分开:
299
+ // stepBudget —— 单轮(常驻块 + 条目)共享的 maxTokens;
300
+ // itemBudget —— 条目还受会话字符额度约束;**常驻块不占这条**(它是状态快照,文档明说不受限)。
301
+ // 旧实现把两者取小成同一个 budgetChars,会话额度用尽后连任务卡都被截成 `…(截断)`。
212
302
  const quotaChars = typeof opts.maxChars === 'number' ? opts.maxChars : Infinity
213
303
  const maxItems = typeof opts.maxItems === 'number' ? opts.maxItems : Infinity
214
304
  const skipItems = opts.skipItems === true
215
- const budgetChars = Math.max(0, Math.min((cfg.maxTokens || 400) * 3, quotaChars))
305
+ const stepBudget = Math.max(0, (cfg.maxTokens || 400) * 3)
306
+ const itemBudget = Math.max(0, Math.min(stepBudget, quotaChars))
216
307
 
217
308
  const skipItem = typeof opts.skipItem === 'function' ? opts.skipItem : null
218
309
  const cands = insightCandidates(store, globalStore, task, cfg).filter((it) => !(skipItem && skipItem(it)))
219
310
 
220
- // 通道 1:authored trigger —— 确定性、全文、优先级 1。procedure 先于其它 kind(步骤更完整)。
221
- // 准入化(S2):只有 `when`(op / 写目标 / 意图词)能触发,guard 只能收窄;
222
- // **没有 `when` 的条目在这里永远不命中**(降级为可发现 + 按需拉取)。
223
- const triggered = []
224
- for (const it of cands) {
225
- const why = matchTrigger(it.trigger, ctx)
226
- if (!why) continue
227
- triggered.push({ it, why })
228
- }
229
- triggered.sort(
230
- (a, b) => (a.it.kind === 'procedure' ? 0 : 1) - (b.it.kind === 'procedure' ? 0 : 1)
231
- || String(a.it.id).localeCompare(String(b.it.id)),
232
- )
311
+ // 两条通道:authored trigger(确定性、全文、优先级 1)→ 统计信号提示(优先级 2)。
312
+ const triggered = collectTriggered(cands, ctx)
233
313
  if (skipItems) {
234
314
  // 会话级限流命中:条目通道本轮整体沉默,但把"本该注入什么"记进 dropped——不做静默降级。
235
- for (const t of triggered) dropped.push({ id: t.it.id, channel: 'trigger', reason: opts.silenceReason || 'cooldown' })
315
+ for (const { it } of triggered) dropped.push({ id: it.id, channel: 'trigger', reason: opts.silenceReason || 'cooldown' })
236
316
  }
237
-
238
- // 通道 2:统计信号 —— 提示态、优先级 2。**双门槛**:层内相对阈值 + IDF 加权覆盖率(绝对下限)。
239
- // 查询只用「人类消息的意图文字 + 本次写目标」:原始工具参数不再进查询,它们正是
240
- // `dcterms→rm`、`*.pptx→论文笔记` 那类假阳性的来源。procedure 不进本通道(要过 trigger.scope)。
317
+ // procedure 不进提示通道:它要过 trigger.scope(见 scoreHints 注释)。
241
318
  const consumed = new Set(triggered.map((t) => t.it.id))
242
319
  const hintCands = skipItems ? [] : cands.filter((it) => !consumed.has(it.id) && it.kind !== 'procedure')
243
- const hintQuery = [ctx.intent || ctx.humanText || '', ...(ctx.targets || [])].filter(Boolean).join(' ')
244
- const hints = []
245
- if (hintCands.length) {
246
- if (typeof cfg.relevanceMin === 'number') {
247
- // 兼容:显式 relevanceMin → 旧的绝对 overlap 判据(老 profile 行为不变)
248
- for (const it of hintCands) {
249
- const score = normalizedTokenOverlap(ctx.humanText || query || '', insightMatchText(it))
250
- if (score >= cfg.relevanceMin) hints.push({ it, score, why: `overlap:${score.toFixed(3)}` })
251
- }
252
- hints.sort((a, b) => b.score - a.score)
253
- } else if (hintQueryText(hintQuery)) {
254
- const byId = new Map(hintCands.map((it) => [it.id, it]))
255
- const corpus = hintCands.map((it) => insightMatchText(it))
256
- // 查询与被测覆盖率的文本用**同一个**过滤后的查询:否则缩写(wsl/npm)会在 BM25 里被剔除、
257
- // 却仍在覆盖率里计分,"至少两个共同词"就被它们凑够了。
258
- const q = hintQueryText(hintQuery)
259
- const scored = rankEntriesMergedScored(hintCands.map(insightToEntry), [q], hintCands.length)
260
- const coverage = new Map(hintCands.map((it, i) => [it.id, idfCoverage(q, corpus[i], corpus)]))
261
- const qStats = coverage.get(hintCands[0].id) || { supported: 0, terms: 0 }
262
- const supportRatio = qStats.terms > 0 ? qStats.supported / qStats.terms : 0
263
- // 通道级沉默:查询里绝大多数词在语料里根本没有对应 → "覆盖率 1.00"只是假象。
264
- const channelThin = typeof cfg.hintMinSupport === 'number' && supportRatio < cfg.hintMinSupport
265
- for (const r of relativeHits(scored, { ratioMin: cfg.signalMinRatio })) {
266
- const it = byId.get(r.entry.insightId)
267
- if (!it) continue
268
- const ev = coverage.get(it.id) || { coverage: 0, matched: 0, supported: 0, terms: 0 }
269
- if (channelThin) {
270
- dropped.push({ id: it.id, channel: 'hint', reason: `support:${supportRatio.toFixed(2)}` })
271
- continue
272
- }
273
- // 绝对门槛:覆盖率下限 + 共同词数下限(查询本身很短时下限按可用词数收敛)。
274
- if (typeof cfg.hintMinCoverage === 'number' && ev.coverage < cfg.hintMinCoverage) {
275
- dropped.push({ id: it.id, channel: 'hint', reason: `coverage:${ev.coverage.toFixed(2)}` })
276
- continue
277
- }
278
- const needMatched = Math.min(typeof cfg.hintMinMatched === 'number' ? cfg.hintMinMatched : 2, ev.supported)
279
- if (ev.matched < needMatched) {
280
- dropped.push({ id: it.id, channel: 'hint', reason: `thin:${ev.matched}` })
281
- continue
282
- }
283
- hints.push({ it, score: r.score, why: `relative:${(r.score / (scored[0].score || 1)).toFixed(2)} cov:${ev.coverage.toFixed(2)}/${ev.matched}` })
284
- }
285
- }
286
- }
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
+ })
287
328
 
288
329
  // 常驻块文本。去重指纹只看稳定内容(任务标题/步骤/insights + 相关 insights):
289
330
  // “编辑中”随每次写文件变化,若参与指纹会导致每写一个文件就重发整块(噪音 + token 浪费)。
290
- const echo = shouldEchoTaskCard(task, cfg)
331
+ const echo = cfg.entryOn !== false && shouldEchoTaskCard(task, cfg)
291
332
  const entry = echo ? buildEntryContent(task, cfg) : ''
292
333
  const entryStable = echo ? buildEntryContent(task, cfg, { withEdited: false }) : ''
293
334
  let used = entry.length
335
+ let itemUsed = 0
294
336
  let itemCount = 0
295
337
 
296
- for (const { it, why } of triggered) {
297
- if (skipItems) break
298
- if (itemCount >= maxItems) {
299
- dropped.push({ id: it.id, channel: 'trigger', reason: 'quota' })
300
- continue
301
- }
302
- const body = fitBody(insightBody(it), budgetChars - used, MIN_BODY_CHARS.trigger)
303
- if (body === null) {
304
- dropped.push({ id: it.id, channel: 'trigger', reason: 'budget' })
305
- 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 })
306
358
  }
307
- used += body.length + 1
308
- itemCount++
309
- parts.push(body)
310
- labels.push(it.kind === 'procedure' ? 'procedure' : it.kind)
311
- reasons.push({ id: it.id, channel: 'trigger', why, hash: insightItemHash(it), chars: body.length })
312
359
  }
313
- for (const { it, why } of hints) {
314
- if (skipItems) break
315
- if (itemCount >= maxItems) {
316
- dropped.push({ id: it.id, channel: 'hint', reason: 'quota' })
317
- continue
318
- }
319
- const body = fitBody(insightBody(it), budgetChars - used, MIN_BODY_CHARS.hint)
320
- if (body === null) {
321
- dropped.push({ id: it.id, channel: 'hint', reason: 'budget' })
322
- continue
323
- }
324
- used += body.length + 1
325
- itemCount++
326
- parts.push(body)
327
- labels.push('hint')
328
- reasons.push({ id: it.id, channel: 'hint', why, hash: insightItemHash(it), chars: body.length })
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')
329
364
  }
330
365
 
331
366
  const total = [entry, ...parts].filter(Boolean)
332
367
  if (!total.length) return { text: '', entry, labels, reasons, dropped }
333
- const clamp = (t) => (t.length > budgetChars ? `${t.slice(0, budgetChars)}\n…(截断)` : t)
368
+ // 整块只受单轮预算(maxTokens)约束;会话条目额度已在 place() 里单独扣过。
369
+ const clamp = (t) => (t.length > stepBudget ? `${t.slice(0, stepBudget)}\n…(截断)` : t)
334
370
  const dedupeText = clamp([entryStable, ...parts].filter(Boolean).join('\n'))
335
- return { text: clamp(total.join('\n')), entry, entryStable, labels, reasons, dropped, dedupeText, itemChars: used - entry.length }
371
+ return { text: clamp(total.join('\n')), entry, entryStable, labels, reasons, dropped, dedupeText, itemChars: itemUsed }
372
+ }
373
+
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 时也漏清两张表。容量只在这里定义一次。
387
+ */
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) {
417
+ ctx.on('session/event', (session, event) => {
418
+ try {
419
+ if (!event || event.type !== 'tool/call') return
420
+ const sessionId = session && session.id
421
+ if (!sessionId) return
422
+ const data = event.data || {}
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()
426
+ } catch {
427
+ // 观察失败绝不影响宿主请求
428
+ }
429
+ })
336
430
  }
337
431
 
338
432
  /** 注册 agent/pre-step 监听,向每步请求的 enter 决策追加记忆消息(默认开)。
@@ -345,51 +439,11 @@ export function installAutoInject(ctx, config) {
345
439
  const cfg = cfgEngine(config)
346
440
  // 审计配置同 cfg:安装时解析一次(与 autoContext 其余开关一致)。
347
441
  const audit = cfgAudit(config)
348
- // 每个会话一份“上次注入指纹”。用单个变量会让并发会话互相抑制注入。
349
- const lastFpBySession = new Map()
350
- const LAST_FP_MAX = 200
351
- // 每个会话一份"上次预算丢弃指纹":预算把条目挤出去时必须留痕一次,而不是静默(degraded 可见性)。
352
- const lastDroppedBySession = new Map()
353
- // 条目级去重记忆:sessionId → Map(insightId → { hash, step })。注入的消息留在会话历史里
354
- // (宿主只追加、不压缩),所以"整块指纹变了"不等于"内容都是新的"——同一份 procedure 会因为
355
- // 滑动工具窗口、任务卡更新、预算截断边界变化被整块重发(实测 66 步注入 20 次,其中同一份
356
- // 1732 字 procedure 重发 3 次、另一份 1008 字的 6 次)。这里按条目记账,正文没变就不再排程。
357
- const injectedBySession = new Map()
358
- const INJECTED_ITEMS_MAX = 600
359
- // 会话步数:为 reinjectItemsAfter 提供时间轴(>0 时才用得上)。
360
- const stepBySession = new Map()
361
- // 会话级条目额度(S3):条数 / 字符 / 上次"条目注入"的步号。常驻任务卡不占这个额度——
362
- // 它是状态快照,内容变了就该更新;被限流的是记忆条目的推送。
363
- const budgetBySession = new Map()
364
- // 反应窗口:本会话最近观察到的 tool/call(参数里有 git commit / npm publish / 改动的路径)。
365
- // 宿主没有"工具执行前拦截"钩子,所以这是 pre-step 之外唯一能拿到的动作事实。
366
- const observedBySession = new Map()
367
- const OBSERVED_MAX = 8
368
- const OBSERVED_SESSIONS = 200
369
- ctx.on('session/event', (session, event) => {
370
- try {
371
- if (!event || event.type !== 'tool/call') return
372
- const sid = session && session.id
373
- if (!sid) return
374
- const data = event.data || {}
375
- const rec = observedBySession.get(sid) || []
376
- rec.push({ name: String(data.name || ''), arguments: String(data.arguments || '') })
377
- while (rec.length > OBSERVED_MAX) rec.shift()
378
- observedBySession.set(sid, rec)
379
- while (observedBySession.size > OBSERVED_SESSIONS) {
380
- observedBySession.delete(observedBySession.keys().next().value)
381
- }
382
- } catch {
383
- // 观察失败绝不影响宿主请求
384
- }
385
- })
442
+ const sessions = new InjectionSessions()
443
+
444
+ installCallObserver(ctx, sessions)
386
445
  if (typeof ctx.effect === 'function') {
387
- ctx.effect(() => () => {
388
- observedBySession.clear()
389
- injectedBySession.clear()
390
- stepBySession.clear()
391
- budgetBySession.clear()
392
- })
446
+ ctx.effect(() => () => sessions.clear())
393
447
  }
394
448
  ctx.on('agent/pre-step', async (payload, next) => {
395
449
  // 宿主契约是 waterfall(payload, next),next 一定存在;但一旦宿主版本漂移、或事件被当
@@ -401,140 +455,151 @@ export function installAutoInject(ctx, config) {
401
455
  if (!decision) return fallback()
402
456
  if (decision.kind !== 'enter') return decision
403
457
  try {
404
- const agent = payload && payload.agent
405
- const session = agent && agent.session
406
- const root = session && session.header && session.header.cwd
407
- const sessionId = session && session.id
408
- if (!root || !sessionId) return decision
409
- const query = lastUserText(decision.messages)
410
- const memoryRoot = memoryRootFor(root, config.memoryDir)
411
- const store = new ProjectMemoryStore(memoryRoot).load()
412
- const globalStore = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
413
- const boundTaskId = store.getBoundTaskId(sessionId) ? store.getBoundTaskId(sessionId) : null
414
- const task = boundTaskId ? store.getTask(boundTaskId) : null
415
- // 两个窗口合并进同一个就绪上下文:人类消息(先发)+ 已观察动作(反应)。
416
- // 动作平面(S1):把"最近做过什么"解析成 op / 写目标 / 主机——不再把原始参数当文本搜。
417
- const observed = observedBySession.get(sessionId) || []
418
- const activity = activityFromCalls(observed)
419
- const readiness = buildReadinessContext({
420
- humanText: query || '',
421
- actionText: observed.map((c) => `${c.name} ${c.arguments}`).join('\n'),
422
- ops: activity.ops,
423
- targets: activity.targets,
424
- hosts: activity.hosts,
425
- })
426
- // 条目级去重:本会话已注入过、且正文未变的条目不再参与排程(cfg.reinjectItemsAfter=0 时永久,
427
- // >0 时走冷却步数,用于历史可能被外部裁剪的场景)。正文变了(编辑过 insight)立刻允许重发。
428
- const stepNo = (stepBySession.get(sessionId) || 0) + 1
429
- stepBySession.set(sessionId, stepNo)
430
- while (stepBySession.size > LAST_FP_MAX) stepBySession.delete(stepBySession.keys().next().value)
431
- const seen = injectedBySession.get(sessionId) || new Map()
432
- injectedBySession.set(sessionId, seen)
433
- while (injectedBySession.size > LAST_FP_MAX) injectedBySession.delete(injectedBySession.keys().next().value)
434
- const cooldown = cfg.reinjectItemsAfter || 0
435
- const skipItem = cooldown === 0
436
- ? (it) => {
437
- const rec = seen.get(it.id)
438
- return Boolean(rec) && rec.hash === insightItemHash(it)
439
- }
440
- : (it) => {
441
- const rec = seen.get(it.id)
442
- return Boolean(rec) && rec.hash === insightItemHash(it) && stepNo - rec.step < cooldown
443
- }
444
- // 会话级限流(S3):冷却步数 / 条目条数 / 条目字符。三个任一触顶 → 条目通道整体沉默,
445
- // 但本轮"本该注入什么"仍会进 dropped(不做静默降级)。
446
- const budget = budgetBySession.get(sessionId) || { items: 0, chars: 0, lastStep: -Infinity }
447
- budgetBySession.set(sessionId, budget)
448
- while (budgetBySession.size > LAST_FP_MAX) budgetBySession.delete(budgetBySession.keys().next().value)
449
- const cooling = Number.isFinite(budget.lastStep) && stepNo - budget.lastStep < cfg.gateCooldownSteps
450
- const itemsLeft = Math.max(0, cfg.maxItemsPerSession - budget.items)
451
- const charsLeft = Math.max(0, cfg.maxItemCharsPerSession - budget.chars)
452
- const silenceReason = cooling ? 'cooldown'
453
- : itemsLeft === 0 ? 'session-items'
454
- : charsLeft === 0 ? 'session-chars' : null
455
- const built = buildInjection({
456
- query: query || '',
457
- readiness,
458
- task,
459
- store,
460
- globalStore,
461
- projectTagsList: projectTags(root),
462
- cfg,
463
- skipItem,
464
- skipItems: silenceReason !== null,
465
- silenceReason: silenceReason || 'cooldown',
466
- maxItems: itemsLeft,
467
- maxChars: charsLeft,
468
- })
469
- const fp = fingerprint(built.dedupeText ?? built.text)
470
- const shouldInject = Boolean(built.text) && fp !== lastFpBySession.get(sessionId)
471
- let injectMessage = null
472
- if (shouldInject) {
473
- // 以宿主 createUserMessage 构造的完整 user 消息追加(带 id/source,plan-mode narration 同款)。
474
- // 裸 {role,content} 消息缺 source 会让宿主逐条读 message.source.kind 时崩溃。
475
- lastFpBySession.set(sessionId, fp)
476
- if (lastFpBySession.size > LAST_FP_MAX) lastFpBySession.delete(lastFpBySession.keys().next().value)
477
- // 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
478
- for (const r of built.reasons) {
479
- if (r && r.id && r.hash) seen.set(r.id, { hash: r.hash, step: stepNo })
480
- }
481
- while (seen.size > INJECTED_ITEMS_MAX) seen.delete(seen.keys().next().value)
482
- // 会话额度只被"条目"消耗;任务卡不算(否则任务一多就把记忆挤没了)。
483
- if (built.reasons.length) {
484
- budget.items += built.reasons.length
485
- budget.chars += typeof built.itemChars === 'number' ? built.itemChars : 0
486
- budget.lastStep = stepNo
487
- }
488
- injectMessage = createUserMessage({
489
- content: [{ type: 'text', text: `\n\n${INJECT_MARK} auto-context\n${built.text}` }],
490
- // 这一块是「同一生产者后续快照会取代的当前状态」,不是一次性通知。
491
- // 宿主 ContextFormed 是判别联合:snapshot 必须带 sections(notice 才需要 summary)。
492
- // 通道不变(仍走 agent/pre-step 追加 user 消息),只修语义。
493
- source: {
494
- kind: 'plugin',
495
- plugin: 'dsh-project-memory',
496
- form: 'snapshot',
497
- sections: [{ name: 'project-memory', text: built.text }],
498
- },
499
- })
500
- }
501
- // 未注入 ≠ 无事发生:因预算被挤掉的条目按 cfg.budgetLog 留痕(默认 off,见 cfgEngine)。
502
- // 留痕仍然记账(去重 + 上限),只是默认不外泄到用户的终端。
503
- if (built.dropped && built.dropped.length && cfg.budgetLog !== 'off') {
504
- const sig = built.dropped.map((d) => `${d.id}:${d.reason}`).join(',')
505
- if (lastDroppedBySession.get(sessionId) !== sig) {
506
- const seenBefore = lastDroppedBySession.has(sessionId)
507
- lastDroppedBySession.set(sessionId, sig)
508
- while (lastDroppedBySession.size > LAST_FP_MAX) {
509
- lastDroppedBySession.delete(lastDroppedBySession.keys().next().value)
510
- }
511
- // once:只有本会话第一次丢弃出声,之后继续记账但保持安静。
512
- if (cfg.budgetLog === 'all' || !seenBefore) {
513
- console.error(
514
- `[dsh-project-memory] auto-inject degraded: ${built.dropped.length} insight(s) kept out by budget — `
515
- + built.dropped.map((d) => `${d.id}(${d.reason})`).join(', '),
516
- )
517
- }
518
- }
519
- }
520
- if (injectMessage) {
521
- // S0 观测:只记真的进了上下文的那一次(dropped 单独出现不写,否则每步刷屏)。
522
- appendInjectionAudit(memoryRoot, auditRecordFrom({
523
- sessionId,
524
- root,
525
- step: stepNo,
526
- text: built.text,
527
- labels: built.labels,
528
- reasons: built.reasons,
529
- dropped: built.dropped,
530
- budget: { items: budget.items, chars: budget.chars, lastStep: Number.isFinite(budget.lastStep) ? budget.lastStep : null },
531
- silence: silenceReason,
532
- }), audit)
533
- return { ...decision, messages: [...decision.messages, injectMessage] }
534
- }
458
+ return (await injectForStep({ payload, decision, config, cfg, audit, sessions })) || decision
535
459
  } catch (err) {
536
460
  console.error(`[dsh-project-memory] auto-inject skipped: ${err?.message || err}`)
461
+ return decision
537
462
  }
538
- 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
+ },
539
604
  })
540
605
  }