@yolk_vat-y/dsh-project-memory 0.6.1 → 0.6.3

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.
@@ -12,6 +12,8 @@ import os from 'node:os'
12
12
  import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
13
13
  import { writeJsonAtomic } from './util/fs.js'
14
14
  import { backfillDerivedTriggers } from './readiness.js'
15
+ import { vectorText } from './vector-index.js'
16
+ import { tokenize } from './util/search.js'
15
17
 
16
18
  export const INSIGHT_KINDS = ['lesson', 'decision', 'procedure', 'experience']
17
19
  export const INSIGHT_SCOPES = ['task', 'project', 'global']
@@ -48,6 +50,19 @@ export function cfgInsight(config) {
48
50
  const cfg = {
49
51
  dedupOverlap: num(c.dedupOverlap, 0.7),
50
52
  reinforceBand: num(c.reinforceBand, 0.65),
53
+ // 向量带(需要 leanvec;没装就自动退化成上面的纯词法带)。阈值由真实 store 标定:
54
+ // 47 条 live 条目、1081 对的余弦 max=0.655 / p99=0.531;本机 4B 把同一条知识改写后与
55
+ // 原文的余弦 min=0.688 / p50=0.809。所以:
56
+ // · 0.90 自动覆盖 —— 落在负样本之上 0.245,只会命中逐字级再记录("非常非常相似");
57
+ // · 0.70 提示 —— 在全部 1081 对真实条目上零噪声,而改写后的再记录有 78% 落进来。
58
+ // 0.65 会开始误伤真实条目(1/1081),别往下调:提示是往上下文里加字的。
59
+ autoMergeCos: num(c.autoMergeCos, 0.9),
60
+ // 自动覆盖还要求"第一名明显领先第二名",否则同一话题撞两条时不知道该覆盖谁。
61
+ autoMergeMargin: num(c.autoMergeMargin, 0.05),
62
+ hintCos: num(c.hintCos, 0.7),
63
+ // `forget` 用关键词删除时的上限:超了不删、只列出来,逼调用方给更具体的词或逐个 id。
64
+ // 关键词删除是**真删**且没有撤销——一次 `forget 'pnpm'` 扫掉十几条精选记忆是不可接受的。
65
+ maxForgetMatches: num(c.maxForgetMatches, 10),
51
66
  maxProject: num(c.maxProject, 100),
52
67
  maxGlobalProcedures: num(c.maxGlobalProcedures, 200),
53
68
  promoteConfidence: num(c.promoteConfidence, 0.7),
@@ -150,35 +165,150 @@ export function carryUsageFields(copy, src) {
150
165
  if (src.lastHitAt) copy.lastHitAt = src.lastHitAt
151
166
  if (src.createdAt) copy.createdAt = src.createdAt
152
167
  if (src.triggerDerived) copy.triggerDerived = src.triggerDerived
168
+ // `prev` 是被自动覆盖/就地更新挤掉的那一版。它必须跟着条目走:promote/demote 走的是
169
+ // normalizeInsight 白名单,不带这一步的话,一次提升就把"还能还原"这件事丢掉了。
170
+ if (src.prev && typeof src.prev === 'object') copy.prev = src.prev
153
171
  return copy
154
172
  }
155
173
 
156
- /** 把 base 合并进既有条目(content 加固、成员/文件/符号并集、置信取高、记命中)。 */
174
+ /**
175
+ * 写一个字段,并把被挤掉的旧值留在 `prev` 单槽。
176
+ *
177
+ * 为什么是"单槽"而不是历史:历史要折叠、要压实、要每个读者都懂两个真相源(已经判过不做)。
178
+ * 这里只保留**上一个**值——刚好够"误覆盖后写回去",O(1)、无需压实、不构成第二个真相源。
179
+ * 空值不算旧值(`''`/undefined 不写 prev),所以首次填充不会产生噪声。
180
+ * @param {object} item - 条目(原地修改)
181
+ * @param {string} key - 字段名
182
+ * @param {unknown} next - 新值
183
+ * @param {string[]} replaced - 被真正改动过的字段名,调用方据此回报
184
+ */
185
+ function putField(item, key, next, replaced) {
186
+ const old = item[key]
187
+ if (JSON.stringify(old) === JSON.stringify(next)) return
188
+ if (old !== undefined && old !== null && old !== '' && !(Array.isArray(old) && !old.length)) {
189
+ if (!item.prev || typeof item.prev !== 'object' || Array.isArray(item.prev)) item.prev = {}
190
+ item.prev[key] = old
191
+ }
192
+ item[key] = next
193
+ replaced.push(key)
194
+ }
195
+
196
+ /** 自动合并会改写的正文字段(title 也在内:0.90 以上的两条标题本就近乎同一句)。 */
197
+ const MERGE_FIELDS = ['title', 'pattern', 'fix', 'choice', 'reason', 'problem', 'solution', 'body']
198
+
199
+ /**
200
+ * 把 base 合并进既有条目:**正文取新值**(旧值进 `prev`),成员/文件/符号并集,置信取高,记命中。
201
+ *
202
+ * 与旧实现的区别就是那一个 `if (b && !existing[f])`:以前字段已有值就**静默丢掉新文本**,
203
+ * 于是"我记错了,改成正确的"永远落不进去(只加 hitCount)。现在反过来——新值落地、旧值可还原。
204
+ * 提升路径只传成员/文件/符号/置信,不传正文字段,所以它们的语义一字未变。
205
+ * @returns {{item: object, replaced: string[]}} 被改动的字段名(供调用方回报)
206
+ */
157
207
  export function mergeInto(existing, base, cfg, nowIso) {
158
208
  const now = nowIso || new Date().toISOString()
159
209
  existing.sourceTaskIds = unionStrings(existing.sourceTaskIds, base.sourceTaskIds)
160
210
  existing.files = unionStrings(existing.files, base.files)
161
211
  existing.symbols = unionStrings(existing.symbols, base.symbols)
162
212
  existing.tags = unionStrings(existing.tags, base.tags)
163
- for (const [f, b] of [
164
- ['pattern', base.pattern],
165
- ['fix', base.fix],
166
- ['choice', base.choice],
167
- ['reason', base.reason],
168
- ['problem', base.problem],
169
- ['solution', base.solution],
170
- ['body', base.body],
171
- ]) {
172
- if (b && !existing[f]) existing[f] = String(b)
173
- }
174
- if (!existing.steps && Array.isArray(base.steps) && base.steps.length) existing.steps = base.steps.map(String)
175
- if (!existing.trigger && base.trigger) existing.trigger = base.trigger
213
+ const replaced = []
214
+ for (const f of MERGE_FIELDS) {
215
+ const b = base[f]
216
+ if (b === undefined || b === null || b === '') continue
217
+ putField(existing, f, String(b), replaced)
218
+ }
219
+ if (Array.isArray(base.steps) && base.steps.length) putField(existing, 'steps', base.steps.map(String), replaced)
220
+ if (base.trigger && typeof base.trigger === 'object') putField(existing, 'trigger', base.trigger, replaced)
176
221
  existing.confidence = Math.max(num(existing.confidence, 0.5), num(base.confidence, 0.5))
177
222
  existing.hitCount = (existing.hitCount || 0) + 1
178
223
  existing.lastHitAt = now
179
224
  existing.updatedAt = now
180
225
  if (existing.archived) existing.archived = false // 重新被使用 → 复活
181
- return existing
226
+ return { item: existing, replaced }
227
+ }
228
+
229
+ /** 就地更新的可写字段(比自动合并宽:kind/confidence/files 等显式改动也允许)。 */
230
+ const UPDATE_FIELDS = ['title', 'kind', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps', 'trigger', 'files', 'symbols', 'tags', 'confidence']
231
+ const UPDATE_ARRAYS = ['steps', 'files', 'symbols', 'tags']
232
+
233
+ /** 显式就地更新(`save_lesson` 带 id):只动调用方给的字段,其余原样,旧值进 `prev`。 */
234
+ export function applyUpdate(item, raw, nowIso) {
235
+ const now = nowIso || new Date().toISOString()
236
+ const replaced = []
237
+ for (const f of UPDATE_FIELDS) {
238
+ const v = raw[f]
239
+ if (v === undefined || v === null || v === '') continue
240
+ if (f === 'kind') {
241
+ if (INSIGHT_KINDS.includes(v)) putField(item, 'kind', v, replaced)
242
+ continue
243
+ }
244
+ if (f === 'confidence') {
245
+ const n = num(v, NaN)
246
+ if (Number.isFinite(n)) putField(item, 'confidence', Math.max(0, Math.min(1, n)), replaced)
247
+ continue
248
+ }
249
+ if (UPDATE_ARRAYS.includes(f)) {
250
+ if (!Array.isArray(v) || !v.length) continue
251
+ putField(item, f, [...new Set(v.map((x) => String(x)))], replaced)
252
+ continue
253
+ }
254
+ if (f === 'trigger') {
255
+ if (typeof v === 'object') putField(item, 'trigger', v, replaced)
256
+ continue
257
+ }
258
+ putField(item, f, String(v), replaced)
259
+ }
260
+ item.updatedAt = now
261
+ if (item.archived) item.archived = false
262
+ return replaced
263
+ }
264
+
265
+ /**
266
+ * 向量近邻:拿 base 的标题去问可选向量层,返回池内最像的一条与第二名。
267
+ *
268
+ * 判据用**余弦**而不是词法重叠,是因为词法在这份 store 上根本够不到阈值:实测 1081 对里
269
+ * `insightMatchText` 的最大值只有 0.256,而 `cfgInsight` 的合并带是 0.70——那条自动通道
270
+ * 实际上只在"逐字重写"时才可能触发。余弦(标题编码)同一份池子上 max=0.655 / p99=0.531,
271
+ * 配 0.90 自动覆盖 / 0.70 提示两条带才有分辨力(标定见 cfgInsight 注释)。
272
+ *
273
+ * 没有向量(leanvec 未装/未配)→ 返回 null,调用方逐字段退回原来的纯词法行为。
274
+ * @param {string} text - 本次要写入的文本(用 {@link vectorText} 的口径)
275
+ * @param {object[]} items - 候选池
276
+ * @param {(text: string, items: object[]) => Map<string, number>} [cosine] - 向量打分(同步)
277
+ * @returns {{item: object, top1: number, top2: number}|null}
278
+ */
279
+ export function vectorNear(text, items, cosine) {
280
+ if (typeof cosine !== 'function' || !text || !Array.isArray(items) || !items.length) return null
281
+ let m = null
282
+ try { m = cosine(text, items) } catch { return null }
283
+ if (!(m instanceof Map)) return null
284
+ let top1 = -1
285
+ let top2 = -1
286
+ let item = null
287
+ for (const it of items) {
288
+ if (!it || it.archived) continue
289
+ const v = m.get(it.id)
290
+ if (typeof v !== 'number' || !Number.isFinite(v)) continue
291
+ if (v > top1) {
292
+ top2 = top1
293
+ top1 = v
294
+ item = it
295
+ } else if (v > top2) top2 = v
296
+ }
297
+ if (!item) return null
298
+ return { item, top1, top2: top2 < 0 ? 0 : top2 }
299
+ }
300
+
301
+ /** 近邻是否够"较高"(提示带);够就返回给调用方回报的形状。 */
302
+ function hintOf(near, cfg) {
303
+ if (!near || near.top1 < cfg.hintCos) return null
304
+ return { id: near.item.id, cos: Number(near.top1.toFixed(3)), title: String(near.item.title || '').slice(0, 40) }
305
+ }
306
+
307
+ /** 自动覆盖判定:够高**且**第一名明显领先第二名(否则不知道该覆盖谁)。 */
308
+ function autoMergeTarget(near, cfg) {
309
+ if (!near || near.top1 < cfg.autoMergeCos) return null
310
+ if (near.top1 - near.top2 < cfg.autoMergeMargin) return null
311
+ return near
182
312
  }
183
313
 
184
314
  /**
@@ -378,44 +508,283 @@ export class GlobalStore {
378
508
 
379
509
  // ---- 单条保存:scope 路由 ----
380
510
 
511
+ /**
512
+ * 按 id 在三个 home 里找一条(global → project → 各任务的 task.insights[])。
513
+ *
514
+ * 为什么要有它:`id` 是全局键,模型不该为了改一条记忆先搞清它在哪一层——那正是"散"。
515
+ * 找到后 scope 用条目自己声明的,调用方据此决定往哪个文件落盘。
516
+ * @returns {{scope: string, item: object, taskId?: string}|null}
517
+ */
518
+ export function findInsightAnywhere({ store, globalStore } = {}, id) {
519
+ if (!id) return null
520
+ if (globalStore && typeof globalStore.items === 'function') {
521
+ const it = globalStore.items().find((i) => i && i.id === id)
522
+ if (it) return { scope: it.scope || 'global', item: it }
523
+ }
524
+ if (store && typeof store.insightItems === 'function') {
525
+ const it = store.insightItems().find((i) => i && i.id === id)
526
+ if (it) return { scope: it.scope || 'project', item: it }
527
+ }
528
+ const tasks = store && typeof store.getTasks === 'function' ? store.getTasks() || [] : []
529
+ for (const t of tasks) {
530
+ const it = (t.insights || []).find((i) => i && i.id === id)
531
+ if (it) return { scope: it.scope || 'task', item: it, taskId: t.id }
532
+ }
533
+ return null
534
+ }
535
+
536
+ /** 一条记忆用于关键词匹配的全文(insight 与旧经验笔记共用一套口径)。 */
537
+ function memoryText(it) {
538
+ if (!it) return ''
539
+ return [it.title, it.problem, it.pattern, it.fix, it.solution, it.choice, it.reason, it.body, ...(Array.isArray(it.steps) ? it.steps : [])]
540
+ .filter(Boolean)
541
+ .join(' ')
542
+ }
543
+
544
+ /**
545
+ * 关键词匹配度:**查询侧覆盖率**(命中词 / 查询词数),沿用旧经验层 `removeExperience` 的口径。
546
+ *
547
+ * 为什么不是 `normalizedTokenOverlap`(两侧取大):删除查询通常很短(一个词),
548
+ * 用两侧取大算出来的分会被长正文稀释到接近 0,"删掉 pnpm 那条"就永远删不掉。
549
+ * 这也与旧行为一致——旧层的删除一直是这个公式,换层不该顺带改判据。
550
+ */
551
+ function queryCoverage(query, text) {
552
+ const q = tokenize(query)
553
+ if (!q.length) return 0
554
+ const t = new Set(tokenize(text))
555
+ if (!t.size) return 0
556
+ let hit = 0
557
+ for (const x of q) if (t.has(x)) hit++
558
+ return hit / q.length
559
+ }
560
+
561
+ /**
562
+ * 最近删除的保留条数。
563
+ *
564
+ * 删除仍然是**真删**(工具描述里的 "no undo" 不变):这里只是把刚被删掉的条目按层
565
+ * 追加进同目录的 {@link DELETED_FILE},滚动保留最近 5 条,供人/模型事后自己找回来。
566
+ *
567
+ * 为什么是 5:够覆盖"刚删错一条/一批"的窗口,又不足以在盘上长期留一份正文副本;
568
+ * 为什么按层分文件:project/task 条目落在项目 store 目录、global 落在 global 文件目录,
569
+ * 与各自真相源同源,删库/搬家时不会对不上。
570
+ */
571
+ export const DELETED_KEEP = 5
572
+
573
+ /** 删除留痕文件名(与 store 同目录)。 */
574
+ export const DELETED_FILE = 'deleted.json'
575
+
576
+ /** 某层 store 目录下的留痕文件绝对路径。 */
577
+ export function deletedFilePath(dir) {
578
+ return dir ? path.join(dir, DELETED_FILE) : null
579
+ }
580
+
581
+ /**
582
+ * 把即将被删的条目写进各自层的留痕文件(滚动保留最近 {@link DELETED_KEEP} 条)。
583
+ *
584
+ * 契约:**永不抛、永不挡删除**。留痕是旁路,写失败只丢留痕,不允许因此让删除失败或半途而废。
585
+ * @param {{store?: object, globalStore?: object}} stores - 两个 store;按条目的 `home` 选目录
586
+ * @param {Array<object>} entries - 完整条目副本,须带 `home`(`global` 走 global 目录,其余走 store 目录)与可选 `taskId`
587
+ * @returns {string[]} 实际写入的留痕文件路径(去重)
588
+ */
589
+ export function recordDeleted({ store, globalStore } = {}, entries = []) {
590
+ const now = new Date().toISOString()
591
+ const byDir = new Map()
592
+ for (const e of entries) {
593
+ if (!e || !e.id) continue
594
+ const dir = e.home === 'global'
595
+ ? (globalStore && globalStore.file ? path.dirname(globalStore.file) : null)
596
+ : (store ? store.dir : null)
597
+ if (!dir) continue
598
+ const batch = byDir.get(dir) || []
599
+ batch.push({ ...e, deletedAt: now })
600
+ byDir.set(dir, batch)
601
+ }
602
+ const written = []
603
+ for (const [dir, batch] of byDir) {
604
+ const file = deletedFilePath(dir)
605
+ let prev = []
606
+ try {
607
+ const doc = JSON.parse(readFileSync(file, 'utf8'))
608
+ if (doc && Array.isArray(doc.items)) prev = doc.items
609
+ } catch {
610
+ // 首次删除(文件不存在)或留痕文件损坏:从空开始,不因旁路数据带崩删除。
611
+ }
612
+ try {
613
+ writeJsonAtomic(file, { version: 1, updatedAt: now, items: [...batch, ...prev].slice(0, DELETED_KEEP) })
614
+ written.push(file)
615
+ } catch {
616
+ // 写不进去(只读盘 / 权限)就放弃留痕:删除本身照常进行。
617
+ }
618
+ }
619
+ return [...new Set(written)]
620
+ }
621
+
622
+ /**
623
+ * 全层删除:task 内嵌 / project / global。一套判据、一次调用。
624
+ *
625
+ * 为什么是"全层一套"而不是给 insight 再开一条通道:对模型来说这本来就是一件事——
626
+ * "把那条记错的删掉",它不该先搞清自己在哪个层。
627
+ * @param {object} o
628
+ * @param {string} o.idOrQuery - 精确 id,或用于匹配的关键词
629
+ * @param {number} [o.maxMatches] - 关键词命中上限;超过则**一条都不删**,只回报候选
630
+ * @returns {{ok: boolean, removed?: object[], matches?: object[], tooMany?: boolean, keptIn?: string[]}}
631
+ */
632
+ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 } = {}) {
633
+ const query = String(idOrQuery ?? '').trim()
634
+ if (!query) return { ok: false, removed: [], matches: [] }
635
+ const at = (home, item, taskId) => ({
636
+ id: item.id,
637
+ home,
638
+ taskId,
639
+ title: String(item.title || item.problem || '(untitled)').slice(0, 60),
640
+ })
641
+ const pools = { project: [], global: [], task: [] }
642
+ for (const it of (store && typeof store.insightItems === 'function' ? store.insightItems() : []) || []) pools.project.push(at('project', it))
643
+ for (const it of (globalStore && typeof globalStore.items === 'function' ? globalStore.items() : []) || []) pools.global.push(at('global', it))
644
+ for (const t of (store && typeof store.getTasks === 'function' ? store.getTasks() : []) || []) {
645
+ for (const it of t.insights || []) pools.task.push(at('task', it, t.id))
646
+ }
647
+
648
+ // 1) 精确 id:直接删那一条,不做关键词匹配(id 是模型手里唯一无歧义的键)
649
+ const byId = []
650
+ for (const [home, list] of Object.entries(pools)) {
651
+ const hit = list.find((x) => x.id === query)
652
+ if (hit) byId.push({ ...hit, home })
653
+ }
654
+ if (byId.length) {
655
+ const keptIn = removeEntries({ store, globalStore }, byId)
656
+ return { ok: true, removed: byId, keptIn }
657
+ }
658
+
659
+ // 2) 关键词:查询侧覆盖率 ≥ 0.5(与旧经验层同判据)
660
+ const matches = []
661
+ const textOf = (home, id) => {
662
+ if (home === 'project') return memoryText((store.insightItems() || []).find((x) => x.id === id))
663
+ if (home === 'global') return memoryText((globalStore.items() || []).find((x) => x.id === id))
664
+ for (const t of store.getTasks() || []) {
665
+ const it = (t.insights || []).find((x) => x.id === id)
666
+ if (it) return memoryText(it)
667
+ }
668
+ return ''
669
+ }
670
+ for (const list of Object.values(pools)) {
671
+ for (const x of list) if (queryCoverage(query, textOf(x.home, x.id)) >= 0.5) matches.push(x)
672
+ }
673
+ if (matches.length > maxMatches) return { ok: false, tooMany: true, matches, removed: [] }
674
+ const keptIn = removeEntries({ store, globalStore }, matches)
675
+ return { ok: true, removed: matches, keptIn }
676
+ }
677
+
678
+ /** 按 home 把条目从各自真相源里移除;删除前先把**完整条目**写进留痕文件。 */
679
+ function removeEntries({ store, globalStore }, entries) {
680
+ // 传进来的 entries 是 at() 的摘要(只有 id/home/title),留痕要的是正文,
681
+ // 所以这里按 id 回真相源取完整对象——顺序在 splice 之前,取不到就跳过留痕(不挡删除)。
682
+ const full = []
683
+ for (const e of entries) {
684
+ if (e.home === 'project') {
685
+ const it = (store.insightItems() || []).find((x) => x.id === e.id)
686
+ if (it) full.push({ ...it, home: 'project' })
687
+ } else if (e.home === 'global') {
688
+ const it = (globalStore.items() || []).find((x) => x.id === e.id)
689
+ if (it) full.push({ ...it, home: 'global' })
690
+ } else if (e.home === 'task') {
691
+ const task = store.getTask(e.taskId)
692
+ const it = (task?.insights || []).find((x) => x.id === e.id)
693
+ if (it) full.push({ ...it, home: 'task', taskId: e.taskId })
694
+ }
695
+ }
696
+ const keptIn = recordDeleted({ store, globalStore }, full)
697
+
698
+ const projectIds = new Set()
699
+ const globalIds = new Set()
700
+ const taskIds = new Map()
701
+ for (const e of entries) {
702
+ if (e.home === 'project') projectIds.add(e.id)
703
+ else if (e.home === 'global') globalIds.add(e.id)
704
+ else if (e.home === 'task') taskIds.set(e.taskId, [...(taskIds.get(e.taskId) || []), e.id])
705
+ }
706
+ if (projectIds.size) store.replaceInsightItems(store.insightItems().filter((i) => !projectIds.has(i.id)))
707
+ if (globalIds.size) {
708
+ const items = globalStore.items()
709
+ for (let i = items.length - 1; i >= 0; i--) if (globalIds.has(items[i].id)) items.splice(i, 1)
710
+ globalStore.markDirty()
711
+ }
712
+ for (const [taskId, ids] of taskIds) {
713
+ const task = store.getTask(taskId)
714
+ if (!task) continue
715
+ task.insights = (task.insights || []).filter((i) => !ids.includes(i.id))
716
+ store.markTasksDirty()
717
+ }
718
+ return keptIn
719
+ }
720
+
381
721
  /**
382
722
  * 统一入口。scope: task 需要 taskId(store 内须存在该任务);project 走 store 的 insights 文档;
383
723
  * global 走 globalStore。
384
- * 返回 { ok, action: 'created'|'merged'|'reinforced'|'linked-project'|'linked-global'|'promoted'|…, id, hint }
724
+ *
725
+ * `raw.id` 给定时走**就地更新**(忽略 scope 路由:条目留在它原来的 home,只覆盖显式给的字段,
726
+ * 旧值进 `prev`)。`cosine` 给定时启用向量带:≥ autoMergeCos 且领先第二名 ≥ autoMergeMargin
727
+ * → 自动覆盖;≥ hintCos → 新建但回报近邻 id。两者都不给就是原来的纯词法行为。
728
+ * 返回 { ok, action: 'created'|'merged'|'auto-merged'|'reinforced'|'updated'|'linked-project'|…, id, replaced, near, hint }
385
729
  */
386
- export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso }) {
730
+ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null }) {
387
731
  const cfg2 = cfg || cfgInsight({})
388
732
  const now = nowIso || new Date().toISOString()
389
733
  const secretField = containsSecretFields(raw)
390
734
  if (secretField) {
391
735
  return { ok: false, error: `内容疑似包含密钥/token/私钥形态数据(字段: ${secretField}),已拒绝写入` }
392
736
  }
737
+ if (raw && raw.id) {
738
+ const found = findInsightAnywhere({ store, globalStore }, raw.id)
739
+ if (!found) return { ok: false, error: `找不到要更新的条目: ${raw.id}(可能已被删除/提升;用 query_memory 重新确认 id)` }
740
+ const replaced = applyUpdate(found.item, raw, now)
741
+ if (found.scope === 'global') globalStore.markDirty()
742
+ else if (found.scope === 'task') store.markTasksDirty()
743
+ else store.replaceInsightItems(store.insightItems())
744
+ return {
745
+ ok: true,
746
+ action: 'updated',
747
+ id: raw.id,
748
+ scope: found.scope,
749
+ replaced,
750
+ hint: replaced.length ? `已就地更新(覆盖字段:${replaced.join('/')},旧值在 prev)` : '没有字段变化',
751
+ }
752
+ }
393
753
  const s = scope || 'project'
394
754
  if (!INSIGHT_SCOPES.includes(s)) return { ok: false, error: `非法 scope: ${s}` }
395
755
  if (s === 'global') {
396
756
  if (!globalStore) return { ok: false, error: 'global 存储未初始化' }
397
- const res = upsertIntoPool(globalStore.items(), raw, cfg2, now, { source, scope: 'global' })
757
+ const res = upsertIntoPool(globalStore.items(), raw, cfg2, now, { source, scope: 'global', cosine })
398
758
  if (res.action === 'created') pruneItems(globalStore.items(), cfg2.maxGlobalProcedures, now)
399
759
  globalStore.markDirty()
400
- return { ok: true, ...res, scope: 'global' }
760
+ return { ok: true, ...res, scope: 'global', hint: res.hint || buildHint(res) }
401
761
  }
402
762
  if (s === 'task') {
403
763
  if (!store || !taskId) return { ok: false, error: 'task 级写入需要 taskId' }
404
764
  const task = store.getTask(taskId)
405
765
  if (!task) return { ok: false, error: `任务不存在: ${taskId}` }
406
- return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source)
766
+ return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine)
407
767
  }
408
- return saveProjectInsight(store, globalStore, raw, cfg2, now, source)
768
+ return saveProjectInsight(store, globalStore, raw, cfg2, now, source, cosine)
409
769
  }
410
770
 
411
- /** 在 items 池内 upsert:≥ dedup 合并;≥ reinforceBand 强化;否则新建。raw 需已过密文检查。 */
771
+ /**
772
+ * 在 items 池内 upsert:向量带(自动覆盖/提示)优先,其次原来的词法带(合并/强化/新建)。
773
+ * raw 需已过密文检查。
774
+ */
412
775
  function upsertIntoPool(items, raw, cfg, nowIso, extra = {}) {
413
776
  const base = { ...raw, source: extra.source, sourceTaskIds: extra.sourceTaskIds || raw.sourceTaskIds }
414
777
  const text = insightMatchText(base)
778
+ const near = vectorNear(vectorText(base), items, extra.cosine)
779
+ const target = autoMergeTarget(near, cfg)
780
+ if (target) {
781
+ const { replaced } = mergeInto(target.item, base, cfg, nowIso)
782
+ return { action: 'auto-merged', id: target.item.id, replaced, cos: Number(target.top1.toFixed(3)) }
783
+ }
415
784
  const hit = findBestOverlapMatch(text, items)
416
785
  if (hit && hit.score >= cfg.dedupOverlap) {
417
- mergeInto(hit.item, base, cfg, nowIso)
418
- return { action: 'merged', id: hit.item.id }
786
+ const { replaced } = mergeInto(hit.item, base, cfg, nowIso)
787
+ return { action: 'merged', id: hit.item.id, replaced }
419
788
  }
420
789
  if (hit && hit.score >= cfg.reinforceBand) {
421
790
  reinforceOnly(hit.item, base, nowIso)
@@ -423,15 +792,16 @@ function upsertIntoPool(items, raw, cfg, nowIso, extra = {}) {
423
792
  }
424
793
  const ins = normalizeInsight(base, { scope: extra.scope || 'project', source: extra.source, nowIso })
425
794
  items.push(ins)
426
- return { action: 'created', id: ins.id }
795
+ const hint = hintOf(near, cfg)
796
+ return hint ? { action: 'created', id: ins.id, near: hint } : { action: 'created', id: ins.id }
427
797
  }
428
798
 
429
799
  // ---- scope = project ----
430
800
 
431
- function saveProjectInsight(store, globalStore, raw, cfg, now, source) {
801
+ function saveProjectInsight(store, globalStore, raw, cfg, now, source, cosine) {
432
802
  const items = store.insightItems()
433
- const res = upsertIntoPool(items, raw, cfg, now, { source, scope: 'project' })
434
- store.replaceInsightItems(items) // 一律标脏(created/merged/reinforced 都改了数组)
803
+ const res = upsertIntoPool(items, raw, cfg, now, { source, scope: 'project', cosine })
804
+ store.replaceInsightItems(items) // 一律标脏(created/merged/auto-merged/reinforced 都改了数组)
435
805
  applyDecay(items, cfg, now)
436
806
  const pruned = pruneItems(items, cfg.maxProject, now)
437
807
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
@@ -443,6 +813,13 @@ function buildHint(res, pruned, promoted) {
443
813
  if (res.action === 'created') bits.push('已新建')
444
814
  else if (res.action === 'merged') bits.push('已与既有条目合并')
445
815
  else if (res.action === 'reinforced') bits.push('近重复,已强化命中')
816
+ else if (res.action === 'auto-merged') bits.push(`相似度 ${res.cos},已自动覆盖既有条目`)
817
+ if (Array.isArray(res.replaced) && res.replaced.length) {
818
+ bits.push(`覆盖字段 ${res.replaced.join('/')}(旧值留在 prev:用同一个 id 再写一次即可写回)`)
819
+ }
820
+ if (res.near && res.near.id !== res.id) {
821
+ bits.push(`近邻 ${res.near.id}(相似度 ${res.near.cos}:《${res.near.title}》)——若这是同一条知识,带 id=${res.near.id} 再写一次即可就地覆盖;确认过时的用 forget 删掉它`)
822
+ }
446
823
  if (pruned && pruned.removed) bits.push(`容量清理 ${pruned.removed} 条`)
447
824
  if (promoted) bits.push(`自动提升 global ${promoted} 条`)
448
825
  return bits.length ? bits.join(';') : ''
@@ -450,34 +827,62 @@ function buildHint(res, pruned, promoted) {
450
827
 
451
828
  // ---- scope = task ----
452
829
 
453
- function saveTaskInsight(store, globalStore, task, raw, cfg, now, source) {
830
+ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine) {
454
831
  // 1) 已有 project 级知识 → 挂成员/命中,不再在 task 层重复存
455
832
  const pjItems = store.insightItems()
456
833
  const base = { ...raw, source, sourceTaskIds: [task.id] }
457
834
  const text = insightMatchText(base)
835
+ const pjNear = vectorNear(vectorText(base), pjItems, cosine)
836
+ const pjTarget = autoMergeTarget(pjNear, cfg)
837
+ if (pjTarget) {
838
+ const { replaced } = mergeInto(pjTarget.item, base, cfg, now)
839
+ store.replaceInsightItems(pjItems)
840
+ applyDecay(pjItems, cfg, now)
841
+ pruneItems(pjItems, cfg.maxProject, now)
842
+ const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
843
+ return { ok: true, action: 'auto-merged', id: pjTarget.item.id, scope: 'project', replaced, cos: Number(pjTarget.top1.toFixed(3)), hint: `相似度 ${pjTarget.top1.toFixed(3)},已自动覆盖 project 级既有条目${replaced.length ? `(覆盖字段 ${replaced.join('/')})` : ''}${promoted ? ';已自动提升 global' : ''}` }
844
+ }
458
845
  const pjHit = findBestOverlapMatch(text, pjItems)
459
846
  if (pjHit && pjHit.score >= cfg.dedupOverlap) {
460
- mergeInto(pjHit.item, base, cfg, now)
847
+ const { replaced } = mergeInto(pjHit.item, base, cfg, now)
461
848
  store.replaceInsightItems(pjItems)
462
849
  applyDecay(pjItems, cfg, now)
463
850
  pruneItems(pjItems, cfg.maxProject, now)
464
851
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
465
- return { ok: true, action: 'linked-project', id: pjHit.item.id, scope: 'project', hint: `该知识已在 project 级,累计第 ${(pjHit.item.sourceTaskIds || []).length} 个任务命中${promoted ? ';已自动提升 global' : ''}` }
852
+ return { ok: true, action: 'linked-project', id: pjHit.item.id, scope: 'project', replaced, hint: `该知识已在 project 级,累计第 ${(pjHit.item.sourceTaskIds || []).length} 个任务命中${promoted ? ';已自动提升 global' : ''}` }
466
853
  }
467
854
  // 2) 已有 global 级知识 → 同样只挂命中
468
855
  if (globalStore) {
856
+ const glNear = vectorNear(vectorText(base), globalStore.items(), cosine)
857
+ const glTarget = autoMergeTarget(glNear, cfg)
858
+ if (glTarget) {
859
+ const { replaced } = mergeInto(glTarget.item, base, cfg, now)
860
+ globalStore.markDirty()
861
+ return { ok: true, action: 'auto-merged', id: glTarget.item.id, scope: 'global', replaced, cos: Number(glTarget.top1.toFixed(3)), hint: `相似度 ${glTarget.top1.toFixed(3)},已自动覆盖 global 级既有条目${replaced.length ? `(覆盖字段 ${replaced.join('/')})` : ''}` }
862
+ }
469
863
  const glHit = findBestOverlapMatch(text, globalStore.items())
470
864
  if (glHit && glHit.score >= cfg.dedupOverlap) {
471
- mergeInto(glHit.item, base, cfg, now)
865
+ const { replaced } = mergeInto(glHit.item, base, cfg, now)
472
866
  globalStore.markDirty()
473
- return { ok: true, action: 'linked-global', id: glHit.item.id, scope: 'global', hint: `该知识已在 global 级,累计第 ${(glHit.item.sourceTaskIds || []).length} 个任务命中` }
867
+ return { ok: true, action: 'linked-global', id: glHit.item.id, scope: 'global', replaced, hint: `该知识已在 global 级,累计第 ${(glHit.item.sourceTaskIds || []).length} 个任务命中` }
474
868
  }
475
869
  }
476
870
  // 3) 跨任务池去重合并(同一坑只留一份,sourceTaskIds 累积)
477
871
  const pool = allTaskInsights(store)
872
+ const poolNear = vectorNear(vectorText(base), pool, cosine)
873
+ const poolTarget = autoMergeTarget(poolNear, cfg)
874
+ if (poolTarget) {
875
+ const { replaced } = mergeInto(poolTarget.item, base, cfg, now)
876
+ store.markTasksDirty()
877
+ const holder = taskContaining(store, poolTarget.item.id)
878
+ if (holder) {
879
+ const promoted = promoteAllTasksToProject(store, globalStore, cfg, now)
880
+ return { ok: true, action: 'auto-merged', id: poolTarget.item.id, taskId: holder.id, scope: 'task', replaced, cos: Number(poolTarget.top1.toFixed(3)), hint: `相似度 ${poolTarget.top1.toFixed(3)},已自动覆盖任务 ${holder.id} 的既有条目${replaced.length ? `(覆盖字段 ${replaced.join('/')})` : ''}${promoted ? `;自动提升 project ${promoted} 条` : ''}` }
881
+ }
882
+ }
478
883
  const hit = findBestOverlapMatch(text, pool)
479
884
  if (hit && hit.score >= cfg.dedupOverlap) {
480
- mergeInto(hit.item, base, cfg, now)
885
+ const { replaced } = mergeInto(hit.item, base, cfg, now)
481
886
  const holder = taskContaining(store, hit.item.id)
482
887
  if (holder) {
483
888
  store.markTasksDirty()
@@ -489,7 +894,8 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source) {
489
894
  action: 'merged',
490
895
  id: hit.item.id,
491
896
  taskId: holderId,
492
- hint: `跨任务去重:并入任务 ${holderId} 既有条目(现 ${size} 个任务命中)${promoted ? `;自动提升 project ${promoted} 条` : ''}`,
897
+ replaced,
898
+ hint: `跨任务去重:并入任务 ${holderId} 既有条目(现 ${size} 个任务命中)${replaced.length ? `,覆盖字段 ${replaced.join('/')}` : ''}${promoted ? `;自动提升 project ${promoted} 条` : ''}`,
493
899
  }
494
900
  }
495
901
  }
package/src/lazy.js CHANGED
@@ -4,6 +4,7 @@ import { findProjectRoot, isUnsafeRoot, memoryRootFor, relativePath, storeKey }
4
4
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
5
5
  import { ProjectMemoryStore } from './store.js'
6
6
  import { onFileObserved } from './enhancer.js'
7
+ import { sessionWorkingDir } from './util/session-dir.js'
7
8
 
8
9
  // 根推导策略已收敛到 util/fs.js(唯一实现)。这里重新导出,保持既有 import 路径可用。
9
10
  export { findProjectRoot }
@@ -80,12 +81,13 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
80
81
  }
81
82
 
82
83
  // 第三个参数是宿主工具执行上下文(tool-fs / str-replace-editor 都以 `exec` 发射),
83
- // 取它的 `agent.session.header.cwd` 作为**本次读取所在会话**的工作目录——比
84
- // process.cwd() 精确(web profile 下同一进程可能有多个会话/项目)。
84
+ // 取它的会话工作目录作为**本次读取所在会话**的工作目录——比 process.cwd() 精确
85
+ // (web profile 下同一进程可能有多个会话/项目)。0.2.1+ 该目录由 workingDirectory
86
+ // 投影决定(cd 后会变),见 util/session-dir.js。
85
87
  ctx.on('fs/observed', (target, observation, actor) => {
86
88
  if (!target || !observation || observation.kind !== 'present') return
87
89
  if (typeof target.displayPath !== 'string' || !target.displayPath) return
88
- queue(target.displayPath, actor?.agent?.session?.header?.cwd)
90
+ queue(target.displayPath, sessionWorkingDir(actor?.agent?.session, { agent: actor?.agent }))
89
91
  })
90
92
 
91
93
  ctx.effect(() => () => {
package/src/ops.js CHANGED
@@ -90,8 +90,19 @@ const SHELL_OP_RULES = [
90
90
  [/\b(curl|wget|web_fetch)\b/, 'fetch-web'],
91
91
  ]
92
92
 
93
- /** 会改动文件系统的 shell 动作前缀:只有这些命令的路径才算"写目标"。 */
94
- const SHELL_WRITE_RE = /\b(rm|rmdir|unlink|shred|mv|cp|touch|tee|truncate|mkdir)\b|>>?\s*\S|\bsed\s+-i\b/
93
+ /**
94
+ * 会改动文件系统的 shell 动作:只有这些命令的路径才算"写目标"。
95
+ *
96
+ * 重定向这一支要排除"丢弃输出",否则 `2>/dev/null`、`2>&1`、`>/dev/null` 这些
97
+ * **纯读命令的惯用写法**会被当成写盘:实测 `ls .agents 2>/dev/null | head` 抽出
98
+ * targets=['.agents']、`cat package.json 2>&1` 抽出 ['package.json'] —— 写目标正是
99
+ * `when.writes` 的匹配面,于是"读/列目录"会误触发一条 `writes:['package.json']` 的教训。
100
+ *
101
+ * 规则:`>` / `>>` / `2>` 后面的目标若是 `&`(合并 fd)或 `/dev/null`(丢弃),不算写;
102
+ * `> file`、`2> file`、`1>> file` 仍算写。
103
+ */
104
+ const SHELL_WRITE_RE =
105
+ /\b(rm|rmdir|unlink|shred|mv|cp|touch|tee|truncate|mkdir)\b|(?:^|[^>])[0-9]?>>?\s*(?!&|\/dev\/null(?:\b|$))\S|\bsed\s+-i\b/
95
106
 
96
107
  const WSL_HINT_RE = /\/mnt\/[a-z]\//i
97
108