@yolk_vat-y/dsh-project-memory 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -2
- package/README.md +10 -10
- package/README.zh-CN.md +10 -10
- package/client/client.js +363 -123
- package/client/client.js.map +1 -1
- package/package.json +11 -8
- package/src/auto-inject.js +25 -1
- package/src/client/MemoryView.tsx +157 -44
- package/src/client/TaskPanel.module.css +23 -0
- package/src/client/locales.ts +10 -0
- package/src/client/paging.js +165 -0
- package/src/commands/insight-actions.js +85 -11
- package/src/commands/invocation.js +4 -1
- package/src/commands/task-actions.js +5 -0
- package/src/index.js +10 -0
- package/src/insight-store.js +361 -35
- package/src/lazy.js +5 -3
- package/src/recall.js +13 -8
- package/src/setup/taskbridge.js +13 -7
- package/src/store.js +170 -131
- package/src/tools/forget.js +26 -6
- package/src/tools/lesson-tools.js +21 -8
- package/src/tools/query-memory.js +10 -4
- package/src/tools/remember.js +30 -14
- package/src/tools/task-tools.js +3 -0
- package/src/types.js +8 -1
- package/src/util/fs.js +3 -1
- package/src/util/session-dir.js +48 -0
- package/src/vector-index.js +3 -2
package/src/insight-store.js
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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,203 @@ 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
|
+
* 全层删除:task 内嵌 / project / global。一套判据、一次调用。
|
|
563
|
+
*
|
|
564
|
+
* 为什么是"全层一套"而不是给 insight 再开一条通道:对模型来说这本来就是一件事——
|
|
565
|
+
* "把那条记错的删掉",它不该先搞清自己在哪个层。
|
|
566
|
+
* @param {object} o
|
|
567
|
+
* @param {string} o.idOrQuery - 精确 id,或用于匹配的关键词
|
|
568
|
+
* @param {number} [o.maxMatches] - 关键词命中上限;超过则**一条都不删**,只回报候选
|
|
569
|
+
* @returns {{ok: boolean, removed?: object[], matches?: object[], tooMany?: boolean}}
|
|
570
|
+
*/
|
|
571
|
+
export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 } = {}) {
|
|
572
|
+
const query = String(idOrQuery ?? '').trim()
|
|
573
|
+
if (!query) return { ok: false, removed: [], matches: [] }
|
|
574
|
+
const at = (home, item, taskId) => ({
|
|
575
|
+
id: item.id,
|
|
576
|
+
home,
|
|
577
|
+
taskId,
|
|
578
|
+
title: String(item.title || item.problem || '(untitled)').slice(0, 60),
|
|
579
|
+
})
|
|
580
|
+
const pools = { project: [], global: [], task: [] }
|
|
581
|
+
for (const it of (store && typeof store.insightItems === 'function' ? store.insightItems() : []) || []) pools.project.push(at('project', it))
|
|
582
|
+
for (const it of (globalStore && typeof globalStore.items === 'function' ? globalStore.items() : []) || []) pools.global.push(at('global', it))
|
|
583
|
+
for (const t of (store && typeof store.getTasks === 'function' ? store.getTasks() : []) || []) {
|
|
584
|
+
for (const it of t.insights || []) pools.task.push(at('task', it, t.id))
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// 1) 精确 id:直接删那一条,不做关键词匹配(id 是模型手里唯一无歧义的键)
|
|
588
|
+
const byId = []
|
|
589
|
+
for (const [home, list] of Object.entries(pools)) {
|
|
590
|
+
const hit = list.find((x) => x.id === query)
|
|
591
|
+
if (hit) byId.push({ ...hit, home })
|
|
592
|
+
}
|
|
593
|
+
if (byId.length) {
|
|
594
|
+
removeEntries({ store, globalStore }, byId)
|
|
595
|
+
return { ok: true, removed: byId }
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// 2) 关键词:查询侧覆盖率 ≥ 0.5(与旧经验层同判据)
|
|
599
|
+
const matches = []
|
|
600
|
+
const textOf = (home, id) => {
|
|
601
|
+
if (home === 'project') return memoryText((store.insightItems() || []).find((x) => x.id === id))
|
|
602
|
+
if (home === 'global') return memoryText((globalStore.items() || []).find((x) => x.id === id))
|
|
603
|
+
for (const t of store.getTasks() || []) {
|
|
604
|
+
const it = (t.insights || []).find((x) => x.id === id)
|
|
605
|
+
if (it) return memoryText(it)
|
|
606
|
+
}
|
|
607
|
+
return ''
|
|
608
|
+
}
|
|
609
|
+
for (const list of Object.values(pools)) {
|
|
610
|
+
for (const x of list) if (queryCoverage(query, textOf(x.home, x.id)) >= 0.5) matches.push(x)
|
|
611
|
+
}
|
|
612
|
+
if (matches.length > maxMatches) return { ok: false, tooMany: true, matches, removed: [] }
|
|
613
|
+
removeEntries({ store, globalStore }, matches)
|
|
614
|
+
return { ok: true, removed: matches }
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 按 home 把条目从各自真相源里移除。 */
|
|
618
|
+
function removeEntries({ store, globalStore }, entries) {
|
|
619
|
+
const projectIds = new Set()
|
|
620
|
+
const globalIds = new Set()
|
|
621
|
+
const taskIds = new Map()
|
|
622
|
+
for (const e of entries) {
|
|
623
|
+
if (e.home === 'project') projectIds.add(e.id)
|
|
624
|
+
else if (e.home === 'global') globalIds.add(e.id)
|
|
625
|
+
else if (e.home === 'task') taskIds.set(e.taskId, [...(taskIds.get(e.taskId) || []), e.id])
|
|
626
|
+
}
|
|
627
|
+
if (projectIds.size) store.replaceInsightItems(store.insightItems().filter((i) => !projectIds.has(i.id)))
|
|
628
|
+
if (globalIds.size) {
|
|
629
|
+
const items = globalStore.items()
|
|
630
|
+
for (let i = items.length - 1; i >= 0; i--) if (globalIds.has(items[i].id)) items.splice(i, 1)
|
|
631
|
+
globalStore.markDirty()
|
|
632
|
+
}
|
|
633
|
+
for (const [taskId, ids] of taskIds) {
|
|
634
|
+
const task = store.getTask(taskId)
|
|
635
|
+
if (!task) continue
|
|
636
|
+
task.insights = (task.insights || []).filter((i) => !ids.includes(i.id))
|
|
637
|
+
store.markTasksDirty()
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
381
641
|
/**
|
|
382
642
|
* 统一入口。scope: task 需要 taskId(store 内须存在该任务);project 走 store 的 insights 文档;
|
|
383
643
|
* global 走 globalStore。
|
|
384
|
-
*
|
|
644
|
+
*
|
|
645
|
+
* `raw.id` 给定时走**就地更新**(忽略 scope 路由:条目留在它原来的 home,只覆盖显式给的字段,
|
|
646
|
+
* 旧值进 `prev`)。`cosine` 给定时启用向量带:≥ autoMergeCos 且领先第二名 ≥ autoMergeMargin
|
|
647
|
+
* → 自动覆盖;≥ hintCos → 新建但回报近邻 id。两者都不给就是原来的纯词法行为。
|
|
648
|
+
* 返回 { ok, action: 'created'|'merged'|'auto-merged'|'reinforced'|'updated'|'linked-project'|…, id, replaced, near, hint }
|
|
385
649
|
*/
|
|
386
|
-
export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso }) {
|
|
650
|
+
export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null }) {
|
|
387
651
|
const cfg2 = cfg || cfgInsight({})
|
|
388
652
|
const now = nowIso || new Date().toISOString()
|
|
389
653
|
const secretField = containsSecretFields(raw)
|
|
390
654
|
if (secretField) {
|
|
391
655
|
return { ok: false, error: `内容疑似包含密钥/token/私钥形态数据(字段: ${secretField}),已拒绝写入` }
|
|
392
656
|
}
|
|
657
|
+
if (raw && raw.id) {
|
|
658
|
+
const found = findInsightAnywhere({ store, globalStore }, raw.id)
|
|
659
|
+
if (!found) return { ok: false, error: `找不到要更新的条目: ${raw.id}(可能已被删除/提升;用 query_memory 重新确认 id)` }
|
|
660
|
+
const replaced = applyUpdate(found.item, raw, now)
|
|
661
|
+
if (found.scope === 'global') globalStore.markDirty()
|
|
662
|
+
else if (found.scope === 'task') store.markTasksDirty()
|
|
663
|
+
else store.replaceInsightItems(store.insightItems())
|
|
664
|
+
return {
|
|
665
|
+
ok: true,
|
|
666
|
+
action: 'updated',
|
|
667
|
+
id: raw.id,
|
|
668
|
+
scope: found.scope,
|
|
669
|
+
replaced,
|
|
670
|
+
hint: replaced.length ? `已就地更新(覆盖字段:${replaced.join('/')},旧值在 prev)` : '没有字段变化',
|
|
671
|
+
}
|
|
672
|
+
}
|
|
393
673
|
const s = scope || 'project'
|
|
394
674
|
if (!INSIGHT_SCOPES.includes(s)) return { ok: false, error: `非法 scope: ${s}` }
|
|
395
675
|
if (s === 'global') {
|
|
396
676
|
if (!globalStore) return { ok: false, error: 'global 存储未初始化' }
|
|
397
|
-
const res = upsertIntoPool(globalStore.items(), raw, cfg2, now, { source, scope: 'global' })
|
|
677
|
+
const res = upsertIntoPool(globalStore.items(), raw, cfg2, now, { source, scope: 'global', cosine })
|
|
398
678
|
if (res.action === 'created') pruneItems(globalStore.items(), cfg2.maxGlobalProcedures, now)
|
|
399
679
|
globalStore.markDirty()
|
|
400
|
-
return { ok: true, ...res, scope: 'global' }
|
|
680
|
+
return { ok: true, ...res, scope: 'global', hint: res.hint || buildHint(res) }
|
|
401
681
|
}
|
|
402
682
|
if (s === 'task') {
|
|
403
683
|
if (!store || !taskId) return { ok: false, error: 'task 级写入需要 taskId' }
|
|
404
684
|
const task = store.getTask(taskId)
|
|
405
685
|
if (!task) return { ok: false, error: `任务不存在: ${taskId}` }
|
|
406
|
-
return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source)
|
|
686
|
+
return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine)
|
|
407
687
|
}
|
|
408
|
-
return saveProjectInsight(store, globalStore, raw, cfg2, now, source)
|
|
688
|
+
return saveProjectInsight(store, globalStore, raw, cfg2, now, source, cosine)
|
|
409
689
|
}
|
|
410
690
|
|
|
411
|
-
/**
|
|
691
|
+
/**
|
|
692
|
+
* 在 items 池内 upsert:向量带(自动覆盖/提示)优先,其次原来的词法带(合并/强化/新建)。
|
|
693
|
+
* raw 需已过密文检查。
|
|
694
|
+
*/
|
|
412
695
|
function upsertIntoPool(items, raw, cfg, nowIso, extra = {}) {
|
|
413
696
|
const base = { ...raw, source: extra.source, sourceTaskIds: extra.sourceTaskIds || raw.sourceTaskIds }
|
|
414
697
|
const text = insightMatchText(base)
|
|
698
|
+
const near = vectorNear(vectorText(base), items, extra.cosine)
|
|
699
|
+
const target = autoMergeTarget(near, cfg)
|
|
700
|
+
if (target) {
|
|
701
|
+
const { replaced } = mergeInto(target.item, base, cfg, nowIso)
|
|
702
|
+
return { action: 'auto-merged', id: target.item.id, replaced, cos: Number(target.top1.toFixed(3)) }
|
|
703
|
+
}
|
|
415
704
|
const hit = findBestOverlapMatch(text, items)
|
|
416
705
|
if (hit && hit.score >= cfg.dedupOverlap) {
|
|
417
|
-
mergeInto(hit.item, base, cfg, nowIso)
|
|
418
|
-
return { action: 'merged', id: hit.item.id }
|
|
706
|
+
const { replaced } = mergeInto(hit.item, base, cfg, nowIso)
|
|
707
|
+
return { action: 'merged', id: hit.item.id, replaced }
|
|
419
708
|
}
|
|
420
709
|
if (hit && hit.score >= cfg.reinforceBand) {
|
|
421
710
|
reinforceOnly(hit.item, base, nowIso)
|
|
@@ -423,15 +712,16 @@ function upsertIntoPool(items, raw, cfg, nowIso, extra = {}) {
|
|
|
423
712
|
}
|
|
424
713
|
const ins = normalizeInsight(base, { scope: extra.scope || 'project', source: extra.source, nowIso })
|
|
425
714
|
items.push(ins)
|
|
426
|
-
|
|
715
|
+
const hint = hintOf(near, cfg)
|
|
716
|
+
return hint ? { action: 'created', id: ins.id, near: hint } : { action: 'created', id: ins.id }
|
|
427
717
|
}
|
|
428
718
|
|
|
429
719
|
// ---- scope = project ----
|
|
430
720
|
|
|
431
|
-
function saveProjectInsight(store, globalStore, raw, cfg, now, source) {
|
|
721
|
+
function saveProjectInsight(store, globalStore, raw, cfg, now, source, cosine) {
|
|
432
722
|
const items = store.insightItems()
|
|
433
|
-
const res = upsertIntoPool(items, raw, cfg, now, { source, scope: 'project' })
|
|
434
|
-
store.replaceInsightItems(items) // 一律标脏(created/merged/reinforced 都改了数组)
|
|
723
|
+
const res = upsertIntoPool(items, raw, cfg, now, { source, scope: 'project', cosine })
|
|
724
|
+
store.replaceInsightItems(items) // 一律标脏(created/merged/auto-merged/reinforced 都改了数组)
|
|
435
725
|
applyDecay(items, cfg, now)
|
|
436
726
|
const pruned = pruneItems(items, cfg.maxProject, now)
|
|
437
727
|
const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
|
|
@@ -443,6 +733,13 @@ function buildHint(res, pruned, promoted) {
|
|
|
443
733
|
if (res.action === 'created') bits.push('已新建')
|
|
444
734
|
else if (res.action === 'merged') bits.push('已与既有条目合并')
|
|
445
735
|
else if (res.action === 'reinforced') bits.push('近重复,已强化命中')
|
|
736
|
+
else if (res.action === 'auto-merged') bits.push(`相似度 ${res.cos},已自动覆盖既有条目`)
|
|
737
|
+
if (Array.isArray(res.replaced) && res.replaced.length) {
|
|
738
|
+
bits.push(`覆盖字段 ${res.replaced.join('/')}(旧值留在 prev:用同一个 id 再写一次即可写回)`)
|
|
739
|
+
}
|
|
740
|
+
if (res.near && res.near.id !== res.id) {
|
|
741
|
+
bits.push(`近邻 ${res.near.id}(相似度 ${res.near.cos}:《${res.near.title}》)——若这是同一条知识,带 id=${res.near.id} 再写一次即可就地覆盖;确认过时的用 forget 删掉它`)
|
|
742
|
+
}
|
|
446
743
|
if (pruned && pruned.removed) bits.push(`容量清理 ${pruned.removed} 条`)
|
|
447
744
|
if (promoted) bits.push(`自动提升 global ${promoted} 条`)
|
|
448
745
|
return bits.length ? bits.join(';') : ''
|
|
@@ -450,34 +747,62 @@ function buildHint(res, pruned, promoted) {
|
|
|
450
747
|
|
|
451
748
|
// ---- scope = task ----
|
|
452
749
|
|
|
453
|
-
function saveTaskInsight(store, globalStore, task, raw, cfg, now, source) {
|
|
750
|
+
function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine) {
|
|
454
751
|
// 1) 已有 project 级知识 → 挂成员/命中,不再在 task 层重复存
|
|
455
752
|
const pjItems = store.insightItems()
|
|
456
753
|
const base = { ...raw, source, sourceTaskIds: [task.id] }
|
|
457
754
|
const text = insightMatchText(base)
|
|
755
|
+
const pjNear = vectorNear(vectorText(base), pjItems, cosine)
|
|
756
|
+
const pjTarget = autoMergeTarget(pjNear, cfg)
|
|
757
|
+
if (pjTarget) {
|
|
758
|
+
const { replaced } = mergeInto(pjTarget.item, base, cfg, now)
|
|
759
|
+
store.replaceInsightItems(pjItems)
|
|
760
|
+
applyDecay(pjItems, cfg, now)
|
|
761
|
+
pruneItems(pjItems, cfg.maxProject, now)
|
|
762
|
+
const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
|
|
763
|
+
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' : ''}` }
|
|
764
|
+
}
|
|
458
765
|
const pjHit = findBestOverlapMatch(text, pjItems)
|
|
459
766
|
if (pjHit && pjHit.score >= cfg.dedupOverlap) {
|
|
460
|
-
mergeInto(pjHit.item, base, cfg, now)
|
|
767
|
+
const { replaced } = mergeInto(pjHit.item, base, cfg, now)
|
|
461
768
|
store.replaceInsightItems(pjItems)
|
|
462
769
|
applyDecay(pjItems, cfg, now)
|
|
463
770
|
pruneItems(pjItems, cfg.maxProject, now)
|
|
464
771
|
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' : ''}` }
|
|
772
|
+
return { ok: true, action: 'linked-project', id: pjHit.item.id, scope: 'project', replaced, hint: `该知识已在 project 级,累计第 ${(pjHit.item.sourceTaskIds || []).length} 个任务命中${promoted ? ';已自动提升 global' : ''}` }
|
|
466
773
|
}
|
|
467
774
|
// 2) 已有 global 级知识 → 同样只挂命中
|
|
468
775
|
if (globalStore) {
|
|
776
|
+
const glNear = vectorNear(vectorText(base), globalStore.items(), cosine)
|
|
777
|
+
const glTarget = autoMergeTarget(glNear, cfg)
|
|
778
|
+
if (glTarget) {
|
|
779
|
+
const { replaced } = mergeInto(glTarget.item, base, cfg, now)
|
|
780
|
+
globalStore.markDirty()
|
|
781
|
+
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('/')})` : ''}` }
|
|
782
|
+
}
|
|
469
783
|
const glHit = findBestOverlapMatch(text, globalStore.items())
|
|
470
784
|
if (glHit && glHit.score >= cfg.dedupOverlap) {
|
|
471
|
-
mergeInto(glHit.item, base, cfg, now)
|
|
785
|
+
const { replaced } = mergeInto(glHit.item, base, cfg, now)
|
|
472
786
|
globalStore.markDirty()
|
|
473
|
-
return { ok: true, action: 'linked-global', id: glHit.item.id, scope: 'global', hint: `该知识已在 global 级,累计第 ${(glHit.item.sourceTaskIds || []).length} 个任务命中` }
|
|
787
|
+
return { ok: true, action: 'linked-global', id: glHit.item.id, scope: 'global', replaced, hint: `该知识已在 global 级,累计第 ${(glHit.item.sourceTaskIds || []).length} 个任务命中` }
|
|
474
788
|
}
|
|
475
789
|
}
|
|
476
790
|
// 3) 跨任务池去重合并(同一坑只留一份,sourceTaskIds 累积)
|
|
477
791
|
const pool = allTaskInsights(store)
|
|
792
|
+
const poolNear = vectorNear(vectorText(base), pool, cosine)
|
|
793
|
+
const poolTarget = autoMergeTarget(poolNear, cfg)
|
|
794
|
+
if (poolTarget) {
|
|
795
|
+
const { replaced } = mergeInto(poolTarget.item, base, cfg, now)
|
|
796
|
+
store.markTasksDirty()
|
|
797
|
+
const holder = taskContaining(store, poolTarget.item.id)
|
|
798
|
+
if (holder) {
|
|
799
|
+
const promoted = promoteAllTasksToProject(store, globalStore, cfg, now)
|
|
800
|
+
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} 条` : ''}` }
|
|
801
|
+
}
|
|
802
|
+
}
|
|
478
803
|
const hit = findBestOverlapMatch(text, pool)
|
|
479
804
|
if (hit && hit.score >= cfg.dedupOverlap) {
|
|
480
|
-
mergeInto(hit.item, base, cfg, now)
|
|
805
|
+
const { replaced } = mergeInto(hit.item, base, cfg, now)
|
|
481
806
|
const holder = taskContaining(store, hit.item.id)
|
|
482
807
|
if (holder) {
|
|
483
808
|
store.markTasksDirty()
|
|
@@ -489,7 +814,8 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source) {
|
|
|
489
814
|
action: 'merged',
|
|
490
815
|
id: hit.item.id,
|
|
491
816
|
taskId: holderId,
|
|
492
|
-
|
|
817
|
+
replaced,
|
|
818
|
+
hint: `跨任务去重:并入任务 ${holderId} 既有条目(现 ${size} 个任务命中)${replaced.length ? `,覆盖字段 ${replaced.join('/')}` : ''}${promoted ? `;自动提升 project ${promoted} 条` : ''}`,
|
|
493
819
|
}
|
|
494
820
|
}
|
|
495
821
|
}
|
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
|
-
//
|
|
84
|
-
//
|
|
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?.
|
|
90
|
+
queue(target.displayPath, sessionWorkingDir(actor?.agent?.session, { agent: actor?.agent }))
|
|
89
91
|
})
|
|
90
92
|
|
|
91
93
|
ctx.effect(() => () => {
|
package/src/recall.js
CHANGED
|
@@ -63,7 +63,7 @@ function matchedFloor(scored, queries, hasVector) {
|
|
|
63
63
|
return scored.filter((r) => (r.matched ?? 0) >= need)
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
/** 各层先验:insight 是"踩过的坑"
|
|
66
|
+
/** 各层先验:insight 是"踩过的坑",略高于普通文档;经验笔记(同库、kind 区分)留痕价值略低。 */
|
|
67
67
|
export const LAYER_PRIORS = Object.freeze({
|
|
68
68
|
insight: 1.15,
|
|
69
69
|
doc: 1,
|
|
@@ -164,8 +164,8 @@ export function insightScoringText(ins) {
|
|
|
164
164
|
* 召回可见的 insight 集合:作用域可见性跟随会话绑定。
|
|
165
165
|
* - project / global:始终可见(归档除外);
|
|
166
166
|
* - task:只在该会话绑定了对应任务时可见(任务私有,不泄露给别的会话);
|
|
167
|
-
* -
|
|
168
|
-
*
|
|
167
|
+
* - `kind:'experience'`(v0.4 经验笔记,加载时导入)**也在这里**——统一存储后没有第二个真相源,
|
|
168
|
+
* 它由 experience 那一桶按 kind 取走;本函数不做排除(排除会让同一内容在别的视图里消失)。
|
|
169
169
|
* @param {{ store?: object, globalStore?: object, boundTaskId?: string|null }} opts
|
|
170
170
|
* @returns {object[]} 可检索的 insight 条目。
|
|
171
171
|
*/
|
|
@@ -175,7 +175,6 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
|
|
|
175
175
|
if (!it || it.archived) continue
|
|
176
176
|
if (it.scope === 'task') continue
|
|
177
177
|
if (it.draft === true) continue
|
|
178
|
-
if (it.kind === 'experience' && it.source === 'migrate') continue // v0.4 影子,交给 experience 层
|
|
179
178
|
out.push(it)
|
|
180
179
|
}
|
|
181
180
|
for (const it of (globalStore && typeof globalStore.items === 'function' ? globalStore.items() : []) || []) {
|
|
@@ -249,7 +248,7 @@ function fuseVectorHits(scored, queries, rerank) {
|
|
|
249
248
|
/**
|
|
250
249
|
* 按层召回:每层各自 top-k,桶内保留原始分与层内相对分。
|
|
251
250
|
* @param {object} opts
|
|
252
|
-
* @param {object} [opts.store] - ProjectMemoryStore;提供 doc/symbol
|
|
251
|
+
* @param {object} [opts.store] - ProjectMemoryStore;提供 doc/symbol 池与 IDF 缓存。
|
|
253
252
|
* @param {object} [opts.globalStore] - GlobalStore;提供 global 级 insight。
|
|
254
253
|
* @param {object[]} [opts.entries] - 直接给定检索池(测试/自定义场景),优先于 store。
|
|
255
254
|
* @param {string[]|string} [opts.queries] - 一条或多条查询(LLM 扩展变体也走这里)。
|
|
@@ -303,7 +302,13 @@ export function recallItems(opts = {}) {
|
|
|
303
302
|
}
|
|
304
303
|
|
|
305
304
|
if (want.has('experience')) {
|
|
306
|
-
|
|
305
|
+
// 经验层不再是第二个 store:它就是 `kind:'experience'` 的 insight(v0.4 的旧笔记在加载时导入、
|
|
306
|
+
// 旧文件归档为 experience.json.migrated)。池子与 insight 层同源,所以两边必须**互斥**:
|
|
307
|
+
// insight 桶排除 experience,否则同一内容会同时出现在 `## Insights` 与 `## Experience` 里。
|
|
308
|
+
// `entries` 给了就用给的:那是一份"调用方指定了这个层"的池子,不再按 kind 二次筛。
|
|
309
|
+
const expPool = entries !== null
|
|
310
|
+
? entries
|
|
311
|
+
: visibleInsights({ store, globalStore, boundTaskId }).filter((it) => it.kind === 'experience')
|
|
307
312
|
// 有向量时在**全量** BM25 序上融合(见 fuseVectorHits 注释),截断到 limit 放到融合之后;
|
|
308
313
|
// 没有向量时沿用原来的 limit 语义,输出与纯词法路径逐字段一致。
|
|
309
314
|
const scored0 = matchedFloor(rankExperienceScored(expPool, qsLayers, rerank ? expPool.length : limit), qsLayers, Boolean(rerank))
|
|
@@ -320,8 +325,8 @@ export function recallItems(opts = {}) {
|
|
|
320
325
|
|
|
321
326
|
if (want.has('insight')) {
|
|
322
327
|
const pool = entries !== null
|
|
323
|
-
? entries.filter((e) => e && e.type === 'insight')
|
|
324
|
-
: visibleInsights({ store, globalStore, boundTaskId }).map(insightToEntry)
|
|
328
|
+
? entries.filter((e) => e && e.type === 'insight' && e.kind !== 'experience')
|
|
329
|
+
: visibleInsights({ store, globalStore, boundTaskId }).filter((it) => it.kind !== 'experience').map(insightToEntry)
|
|
325
330
|
const scored0 = matchedFloor(rankEntriesMergedScored(pool, qsLayers, rerank ? pool.length : limit), qsLayers, Boolean(rerank))
|
|
326
331
|
if (scored0.length) {
|
|
327
332
|
const scored = fuseVectorHits(scored0.map((r) => ({ item: r.entry, score: r.score })), qs, rerank).slice(0, limit)
|