@yolk_vat-y/dsh-project-memory 0.6.11 → 0.7.0

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.
Files changed (67) hide show
  1. package/CHANGELOG.md +104 -120
  2. package/README.md +14 -105
  3. package/README.zh-CN.md +14 -105
  4. package/client/client.js +228 -95
  5. package/client/client.js.map +1 -1
  6. package/package.json +2 -2
  7. package/scripts/file-peak.mjs +1 -1
  8. package/scripts/tool-schema-size.mjs +1 -1
  9. package/skills/project-memory/SKILL.md +1 -1
  10. package/skills/project-memory/scripts/pm-digest.mjs +20 -6
  11. package/src/audit.js +10 -2
  12. package/src/auto-inject.js +124 -38
  13. package/src/client/MemoryView.tsx +119 -40
  14. package/src/client/TaskCommandNode.tsx +6 -4
  15. package/src/client/TaskComponents.tsx +13 -16
  16. package/src/client/TaskPanel.tsx +41 -15
  17. package/src/client/client.ts +4 -7
  18. package/src/client/paging.js +1 -14
  19. package/src/client/settings-card.tsx +9 -0
  20. package/src/client/task-data-store.ts +57 -7
  21. package/src/client/task-hooks.ts +0 -2
  22. package/src/client/task-scope.js +16 -1
  23. package/src/client/task-ui-store.ts +1 -1
  24. package/src/commands/insight-actions.js +91 -94
  25. package/src/commands/task-actions.js +7 -5
  26. package/src/commands/tasks.js +34 -10
  27. package/src/doc-index.js +3 -1
  28. package/src/enhancer.js +0 -12
  29. package/src/index-failures.js +1 -1
  30. package/src/index-pipeline.js +11 -2
  31. package/src/index.js +60 -14
  32. package/src/inject-visible.js +282 -0
  33. package/src/insight-store.js +133 -68
  34. package/src/lazy.js +29 -23
  35. package/src/llm-route.js +1 -1
  36. package/src/llm.js +1 -8
  37. package/src/ops.js +18 -5
  38. package/src/parsers/pdfjs-parser.js +3 -33
  39. package/src/project-memory-service.js +195 -0
  40. package/src/project-profile.js +0 -4
  41. package/src/setup/taskbridge.js +38 -6
  42. package/src/store.js +639 -147
  43. package/src/symbols.js +2 -4
  44. package/src/tools/context.js +14 -0
  45. package/src/tools/forget.js +7 -17
  46. package/src/tools/index-doc.js +62 -21
  47. package/src/tools/index-repo.js +17 -15
  48. package/src/tools/lesson-tools.js +10 -13
  49. package/src/tools/output.js +33 -0
  50. package/src/tools/query-memory.js +7 -12
  51. package/src/tools/remember.js +8 -18
  52. package/src/tools/stats.js +4 -9
  53. package/src/tools/task-tools.js +23 -22
  54. package/src/tools/watch-repo.js +16 -15
  55. package/src/util/flush.js +1 -1
  56. package/src/util/fs.js +135 -20
  57. package/src/util/insight-fields.js +22 -0
  58. package/src/util/message-source.js +20 -0
  59. package/src/util/relative-time.js +24 -0
  60. package/src/util/search.js +0 -1
  61. package/src/util/task-view.js +8 -15
  62. package/src/util/value.js +16 -0
  63. package/src/vector-index.js +2 -2
  64. package/src/watch.js +25 -8
  65. package/client/client.d.ts +0 -27
  66. package/client/client.d.ts.map +0 -1
  67. package/client/style.css +0 -395
@@ -10,9 +10,11 @@ import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from '
10
10
  import { acquireDirLock, storeKey, writeJsonAtomic } from './util/fs.js'
11
11
  import { debugPersistence } from './util/persist.js'
12
12
  import { trackDirty, untrackDirty } from './util/flush.js'
13
- import { backfillDerivedTriggers } from './readiness.js'
13
+ import { backfillDerivedTriggers, deriveTrigger } from './readiness.js'
14
14
  import { vectorText } from './vector-index.js'
15
15
  import { tokenize } from './util/search.js'
16
+ import { isRecord, isoMs, newerIso } from './util/value.js'
17
+ import { pruneKindFields } from './util/insight-fields.js'
16
18
 
17
19
  export const INSIGHT_KINDS = ['lesson', 'decision', 'procedure', 'experience']
18
20
  export const INSIGHT_SCOPES = ['task', 'project', 'global']
@@ -29,31 +31,20 @@ export const SECRET_PATTERNS = [
29
31
  ]
30
32
 
31
33
  /** 检测疑似密钥/token/私钥形态内容;命中返回第一个命中字段名,否则 null。 */
32
- export function containsSecretFields(ins, fields = ['title', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps']) {
34
+ export function containsSecretFields(ins, fields = ['title', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps', 'trigger']) {
33
35
  for (const f of fields) {
34
36
  const v = ins && ins[f]
35
37
  if (!v) continue
36
- const text = Array.isArray(v) ? v.join('\n') : String(v)
38
+ const text = Array.isArray(v) ? v.join('\n') : typeof v === 'object' ? JSON.stringify(v) : String(v)
37
39
  for (const re of SECRET_PATTERNS) if (re.test(text)) return f
38
40
  }
39
41
  return null
40
42
  }
41
43
 
42
- function isRecord(value) {
43
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
44
- }
45
-
46
44
  function num(v, d) {
47
45
  return typeof v === 'number' && Number.isFinite(v) ? v : d
48
46
  }
49
47
 
50
- /** 两个 ISO 时间戳的先后;缺失/非法一律 0。 */
51
- function newerIso(a, b) {
52
- const ta = Date.parse(a || '') || 0
53
- const tb = Date.parse(b || '') || 0
54
- return ta - tb
55
- }
56
-
57
48
  /** 合并配置(config.insight 之上补默认)。 */
58
49
  export function cfgInsight(config) {
59
50
  const c = (config && config.insight) || {}
@@ -98,6 +89,7 @@ const ARRAY_FIELDS = ['steps', 'files', 'symbols', 'tags', 'sourceTaskIds']
98
89
 
99
90
  /** 由工具/测试传入的 raw 构造规范 insight(scope/source/timestamps 由调用方定)。 */
100
91
  export function normalizeInsight(raw, extra = {}) {
92
+ raw = isRecord(raw) ? raw : {}
101
93
  const kind = INSIGHT_KINDS.includes(raw.kind) ? raw.kind : 'lesson'
102
94
  const now = extra.nowIso || new Date().toISOString()
103
95
  const ins = {
@@ -172,6 +164,8 @@ export function carryUsageFields(copy, src) {
172
164
  if (src.lastHitAt) copy.lastHitAt = src.lastHitAt
173
165
  if (src.createdAt) copy.createdAt = src.createdAt
174
166
  if (src.triggerDerived) copy.triggerDerived = src.triggerDerived
167
+ if (src.archived) copy.archived = true
168
+ if (src.promoteHold) copy.promoteHold = true
175
169
  // `prev` 是被覆盖挤掉的那一版,必须跟着条目走:promote/demote 走白名单,漏了它就丢了"还能还原"。
176
170
  if (src.prev && typeof src.prev === 'object') copy.prev = src.prev
177
171
  return copy
@@ -194,9 +188,49 @@ function putField(item, key, next, replaced) {
194
188
  replaced.push(key)
195
189
  }
196
190
 
191
+ /** 面板编辑用的单字段写入:与自动覆盖共用 `prev` 单槽,避免“编辑后旧值不可还原”。 */
192
+ export function putInsightField(item, key, next) {
193
+ const replaced = []
194
+ putField(item, key, next, replaced)
195
+ return replaced.length > 0
196
+ }
197
+
198
+ /** 局部 trigger 更新与面板编辑同语义:只改传入成员,when/guard/prevents 等 authored 面保留。 */
199
+ function mergeAuthoredTrigger(existing, incoming) {
200
+ if (!incoming || typeof incoming !== 'object') return existing
201
+ const next = { ...(existing || {}) }
202
+ for (const f of ['keywords', 'scope', 'actions', 'paths', 'symbols']) {
203
+ if (Array.isArray(incoming[f])) next[f] = incoming[f].map(String)
204
+ }
205
+ if (incoming.when && typeof incoming.when === 'object') next.when = incoming.when
206
+ if (incoming.guard && typeof incoming.guard === 'object') next.guard = incoming.guard
207
+ if (typeof incoming.prevents === 'string') next.prevents = incoming.prevents
208
+ return next
209
+ }
210
+
197
211
  /** 自动合并会改写的正文字段(title 也在内:0.90 以上的两条标题本就近乎同一句)。 */
198
212
  const MERGE_FIELDS = ['title', 'pattern', 'fix', 'choice', 'reason', 'problem', 'solution', 'body']
199
213
 
214
+ /** `deriveTrigger` 读取且 store 可改写的正文字段;元数据变化不触发重算。 */
215
+ const DERIVED_SOURCE_FIELDS = [...MERGE_FIELDS, 'steps']
216
+
217
+ /** 序列化快照:区分“同值写入”与真正的正文变更。 */
218
+ function derivedSourceSnapshot(item) {
219
+ return JSON.stringify(DERIVED_SOURCE_FIELDS.map((f) => item[f]))
220
+ }
221
+
222
+ /** 重算派生词(只写 triggerDerived);空结果删除,避免用过期词召回。 */
223
+ export function refreshDerivedTrigger(item) {
224
+ const derived = deriveTrigger(item)
225
+ if (!derived.keywords.length && !derived.actions.length && !derived.paths.length) {
226
+ // 旧值一律清掉:空派生继续留着就是审计 #17 的过期召回。
227
+ delete item.triggerDerived
228
+ return false
229
+ }
230
+ item.triggerDerived = derived
231
+ return true
232
+ }
233
+
200
234
  /**
201
235
  * 把 base 合并进既有条目:**正文取新值**(旧值进 `prev`),成员/文件/符号并集,置信取高,记命中。
202
236
  * 提升路径只传成员/文件/符号/置信,不传正文字段,语义未变。
@@ -204,6 +238,7 @@ const MERGE_FIELDS = ['title', 'pattern', 'fix', 'choice', 'reason', 'problem',
204
238
  */
205
239
  export function mergeInto(existing, base, cfg, nowIso) {
206
240
  const now = nowIso || new Date().toISOString()
241
+ const before = derivedSourceSnapshot(existing)
207
242
  existing.sourceTaskIds = unionStrings(existing.sourceTaskIds, base.sourceTaskIds)
208
243
  existing.files = unionStrings(existing.files, base.files)
209
244
  existing.symbols = unionStrings(existing.symbols, base.symbols)
@@ -215,7 +250,9 @@ export function mergeInto(existing, base, cfg, nowIso) {
215
250
  putField(existing, f, String(b), replaced)
216
251
  }
217
252
  if (Array.isArray(base.steps) && base.steps.length) putField(existing, 'steps', base.steps.map(String), replaced)
218
- if (base.trigger && typeof base.trigger === 'object') putField(existing, 'trigger', base.trigger, replaced)
253
+ // 正文变了就重算派生词(作者手写的 trigger 不动);只并成员/文件/置信时快照不变,跳过。
254
+ if (derivedSourceSnapshot(existing) !== before) refreshDerivedTrigger(existing)
255
+ if (base.trigger && typeof base.trigger === 'object') putField(existing, 'trigger', mergeAuthoredTrigger(existing.trigger, base.trigger), replaced)
219
256
  existing.confidence = Math.max(num(existing.confidence, 0.5), num(base.confidence, 0.5))
220
257
  existing.hitCount = (existing.hitCount || 0) + 1
221
258
  existing.lastHitAt = now
@@ -228,20 +265,11 @@ export function mergeInto(existing, base, cfg, nowIso) {
228
265
  const UPDATE_FIELDS = ['title', 'kind', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps', 'trigger', 'files', 'symbols', 'tags', 'confidence']
229
266
  const UPDATE_ARRAYS = ['steps', 'files', 'symbols', 'tags']
230
267
 
231
- // 切 kind 时要保留的专属字段;其余内容字段清掉(与 commands/insight-actions 的 editMemoryItem 同语义)。
232
- // 两条写入路径必须一致:同一次“改 kind”,面板会清、save_lesson 不清就是两套数据形状。
233
- const KIND_CONTENT = {
234
- lesson: ['pattern', 'fix'],
235
- decision: ['choice', 'reason'],
236
- procedure: ['steps', 'trigger'],
237
- experience: ['problem', 'solution'],
238
- }
239
- const ALL_CONTENT = ['body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps']
240
-
241
268
  /** 显式就地更新(`save_lesson` 带 id):只动调用方给的字段,其余原样,旧值进 `prev`。 */
242
269
  export function applyUpdate(item, raw, nowIso) {
243
270
  const now = nowIso || new Date().toISOString()
244
271
  const replaced = []
272
+ const before = derivedSourceSnapshot(item)
245
273
  const oldKind = item.kind
246
274
  for (const f of UPDATE_FIELDS) {
247
275
  const v = raw[f]
@@ -261,22 +289,16 @@ export function applyUpdate(item, raw, nowIso) {
261
289
  continue
262
290
  }
263
291
  if (f === 'trigger') {
264
- if (typeof v === 'object') putField(item, 'trigger', v, replaced)
292
+ if (typeof v === 'object') putField(item, 'trigger', mergeAuthoredTrigger(item.trigger, v), replaced)
265
293
  continue
266
294
  }
267
295
  putField(item, f, String(v), replaced)
268
296
  }
269
297
  // 改 kind 时清掉旧 kind 的专属字段(procedure 保留通用 body):否则 lesson→decision 后
270
298
  // `fix` 会盖在 `choice` 前面进入正文/摘要(insightBodyText 的优先级是 fix > choice > …)。
271
- if (item.kind !== oldKind && KIND_CONTENT[item.kind]) {
272
- const keep = new Set(KIND_CONTENT[item.kind])
273
- const isProcedure = item.kind === 'procedure'
274
- for (const f of ALL_CONTENT) {
275
- if (keep.has(f)) continue
276
- if (isProcedure && f === 'body') continue
277
- delete item[f]
278
- }
279
- }
299
+ pruneKindFields(item, oldKind)
300
+ // 正文(含 steps、切 kind 时被清掉的旧字段)真的变了才重算派生词;改 confidence 等元数据不碰。
301
+ if (derivedSourceSnapshot(item) !== before) refreshDerivedTrigger(item)
280
302
  item.updatedAt = now
281
303
  if (item.archived) item.archived = false
282
304
  // 显式编辑一条草稿 = 作者确认:reflection 产出的 draft 可被 save_lesson 带 id 直接改正文并转正。
@@ -363,17 +385,27 @@ function autoMergeTarget(near, cfg) {
363
385
  * 只记非归档条目。返回实际加一的条数,调用方据此决定是否落盘。
364
386
  * @returns {number} 被加一的条目数
365
387
  */
366
- export function recordHit({ store, globalStore, ids, nowIso } = {}) {
388
+ export function recordHit({ store, globalStore, ids, nowIso, delta = 1, restore = null } = {}) {
367
389
  const want = new Set((ids || []).filter(Boolean))
368
390
  if (!want.size) return 0
369
391
  const now = nowIso || new Date().toISOString()
392
+ const step = Number(delta) || 0
393
+ if (!step) return 0
370
394
  let n = 0
371
395
  const touch = (items) => {
372
396
  let c = 0
373
397
  for (const it of items || []) {
374
398
  if (!it || it.archived || !want.has(it.id)) continue
375
- it.hitCount = num(it.hitCount, 0) + 1
376
- it.lastHitAt = now
399
+ const next = Math.max(0, num(it.hitCount, 0) + step)
400
+ if (next === num(it.hitCount, 0)) continue
401
+ it.hitCount = next
402
+ if (step > 0) it.lastHitAt = now
403
+ else if (restore && restore.has(it.id)) {
404
+ // 回滚到注入前的活跃度:不能把“模型从没看到过”的这次曝光留成 lastHitAt=now。
405
+ const prev = restore.get(it.id)
406
+ if (prev) it.lastHitAt = prev
407
+ else delete it.lastHitAt
408
+ }
377
409
  c++
378
410
  }
379
411
  n += c
@@ -423,13 +455,8 @@ function removeFromTask(store, insightId) {
423
455
 
424
456
  const DAY_MS = 86400000
425
457
 
426
- function tsOf(ins, field) {
427
- const v = ins[field]
428
- return v ? Date.parse(v) || 0 : 0
429
- }
430
-
431
458
  function activityOf(ins) {
432
- return tsOf(ins, 'lastHitAt') || tsOf(ins, 'updatedAt') || tsOf(ins, 'createdAt') || 0
459
+ return isoMs(ins.lastHitAt) || isoMs(ins.updatedAt) || isoMs(ins.createdAt)
433
460
  }
434
461
 
435
462
  export function applyDecay(items, cfg, nowIso) {
@@ -455,19 +482,19 @@ export function applyDecay(items, cfg, nowIso) {
455
482
  * 注意:没有归档可删时,本轮归档的条目会在同一次调用的后续循环里被删掉——
456
483
  * `archived` 计数是"先归档、随即被删",不是"留下了软删副本"。
457
484
  */
458
- export function pruneItems(items, max, nowIso) {
485
+ export function pruneItems(items, max, nowIso, { protectedIds = new Set() } = {}) {
459
486
  const now = nowIso || new Date().toISOString()
460
487
  let removed = 0
461
488
  let archivedNow = 0
462
489
  while (items.length > max) {
463
- const arch = items.filter((i) => i.archived).sort((a, b) => activityOf(a) - activityOf(b))
490
+ const arch = items.filter((i) => i && i.archived && !protectedIds.has(i.id)).sort((a, b) => activityOf(a) - activityOf(b))
464
491
  if (arch.length) {
465
492
  const victim = arch[0]
466
493
  const idx = items.indexOf(victim)
467
494
  if (idx !== -1) items.splice(idx, 1)
468
495
  removed++
469
496
  } else {
470
- const sorted = [...items].sort((a, b) => activityOf(a) - activityOf(b) || num(a.confidence, 0) - num(b.confidence, 0))
497
+ const sorted = items.filter((i) => i && !protectedIds.has(i.id)).sort((a, b) => activityOf(a) - activityOf(b) || num(a.confidence, 0) - num(b.confidence, 0))
471
498
  const victim = sorted[0]
472
499
  if (!victim) break
473
500
  victim.archived = true
@@ -871,6 +898,7 @@ function removeEntries({ store, globalStore }, entries) {
871
898
  * 返回 { ok, action, id, replaced, near, hint }。
872
899
  */
873
900
  export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null }) {
901
+ if (!isRecord(raw)) return { ok: false, error: '内容必须是对象(不能是 null/数组/字符串)' }
874
902
  const cfg2 = cfg || cfgInsight({})
875
903
  const now = nowIso || new Date().toISOString()
876
904
  const secretField = containsSecretFields(raw)
@@ -902,7 +930,7 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
902
930
  if (s === 'global') {
903
931
  if (!globalStore) return { ok: false, error: 'global 存储未初始化' }
904
932
  const res = upsertIntoPool(globalStore.items(), raw, cfg2, now, { source, scope: 'global', cosine })
905
- if (res.action === 'created') pruneItems(globalStore.items(), cfg2.maxGlobalProcedures, now)
933
+ if (res.action === 'created') pruneItems(globalStore.items(), cfg2.maxGlobalProcedures, now, { protectedIds: new Set([res.id]) })
906
934
  globalStore.markDirty()
907
935
  return { ok: true, ...res, scope: 'global', hint: res.hint || buildHint(res) }
908
936
  }
@@ -910,6 +938,9 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
910
938
  if (!store || !taskId) return { ok: false, error: 'task 级写入需要 taskId' }
911
939
  const task = store.getTask(taskId)
912
940
  if (!task) return { ok: false, error: `任务不存在: ${taskId}` }
941
+ // 归档任务 = 已停止续做:写进去的条目在 recall(visibleInsights)里永远不可见,
942
+ // 必须让调用方先 select_task 解归档,而不是报“Saved”后石沉大海。
943
+ if (task.archived) return { ok: false, error: `任务已归档: ${taskId}(先 select_task 解归档再写入)` }
913
944
  return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine)
914
945
  }
915
946
  return saveProjectInsight(store, globalStore, raw, cfg2, now, source, cosine)
@@ -938,6 +969,7 @@ function upsertIntoPool(items, raw, cfg, nowIso, extra = {}) {
938
969
  return { action: 'reinforced', id: hit.item.id }
939
970
  }
940
971
  const ins = normalizeInsight(base, { scope: extra.scope || 'project', source: extra.source, nowIso })
972
+ refreshDerivedTrigger(ins)
941
973
  items.push(ins)
942
974
  const hint = hintOf(near, cfg)
943
975
  return hint ? { action: 'created', id: ins.id, near: hint } : { action: 'created', id: ins.id }
@@ -950,7 +982,7 @@ function saveProjectInsight(store, globalStore, raw, cfg, now, source, cosine) {
950
982
  const res = upsertIntoPool(items, raw, cfg, now, { source, scope: 'project', cosine })
951
983
  store.replaceInsightItems(items) // 一律标脏(created/merged/auto-merged/reinforced 都改了数组)
952
984
  applyDecay(items, cfg, now)
953
- const pruned = pruneItems(items, cfg.maxProject, now)
985
+ const pruned = pruneItems(items, cfg.maxProject, now, { protectedIds: new Set([res.id]) })
954
986
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
955
987
  return { ok: true, ...res, scope: 'project', hint: buildHint(res, pruned, promoted) }
956
988
  }
@@ -989,7 +1021,7 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
989
1021
  const { replaced } = mergeInto(pjTarget.item, base, cfg, now)
990
1022
  store.replaceInsightItems(pjItems)
991
1023
  applyDecay(pjItems, cfg, now)
992
- pruneItems(pjItems, cfg.maxProject, now)
1024
+ pruneItems(pjItems, cfg.maxProject, now, { protectedIds: new Set([pjTarget.item.id]) })
993
1025
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
994
1026
  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' : ''}` }
995
1027
  }
@@ -998,7 +1030,7 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
998
1030
  const { replaced } = mergeInto(pjHit.item, base, cfg, now)
999
1031
  store.replaceInsightItems(pjItems)
1000
1032
  applyDecay(pjItems, cfg, now)
1001
- pruneItems(pjItems, cfg.maxProject, now)
1033
+ pruneItems(pjItems, cfg.maxProject, now, { protectedIds: new Set([pjHit.item.id]) })
1002
1034
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
1003
1035
  return { ok: true, action: 'linked-project', id: pjHit.item.id, scope: 'project', replaced, hint: `该知识已在 project 级,累计第 ${(pjHit.item.sourceTaskIds || []).length} 个任务命中${promoted ? ';已自动提升 global' : ''}` }
1004
1036
  }
@@ -1080,22 +1112,25 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
1080
1112
  export function promoteAllTasksToProject(store, globalStore, cfg, now) {
1081
1113
  const tasks = store.getTasks() || []
1082
1114
  let promoted = 0
1115
+ const promotedIds = new Set()
1083
1116
  for (const task of tasks) {
1084
1117
  const list = task.insights || []
1085
1118
  for (const ins of [...list]) {
1086
1119
  if (ins.scope && ins.scope !== 'task') continue
1087
1120
  // 草稿必须先被确认;自动提升绕过审核就等于把 reflection 的猜测变成项目资产。
1088
- if (ins.draft === true) continue
1121
+ if (ins.draft === true || ins.archived || ins.promoteHold) continue
1089
1122
  const members = new Set(ins.sourceTaskIds || [])
1090
1123
  if (members.size < 2) continue
1091
1124
  if (num(ins.confidence, 0) < cfg.promoteConfidence) continue
1092
- // 与 project 已有资产去重:重复 → 并成员,删 task 副本
1125
+ // 与 project 已有资产去重:同 id 先合并(历史脏数据),再按相似度;正文随移动带走。
1093
1126
  const pjItems = store.insightItems()
1094
- const pjHit = findBestOverlapMatch(insightMatchText(ins), pjItems)
1127
+ const sameId = pjItems.find((it) => it && it.id === ins.id)
1128
+ const pjHit = sameId ? { item: sameId, score: 1 } : findBestOverlapMatch(insightMatchText(ins), pjItems)
1095
1129
  if (pjHit && pjHit.score >= cfg.dedupOverlap) {
1096
- mergeInto(pjHit.item, { sourceTaskIds: ins.sourceTaskIds, files: ins.files, symbols: ins.symbols, tags: ins.tags, confidence: ins.confidence }, cfg, now)
1130
+ mergeInto(pjHit.item, ins, cfg, now)
1097
1131
  store.replaceInsightItems(pjItems)
1098
1132
  removeFromTask(store, ins.id)
1133
+ promotedIds.add(pjHit.item.id)
1099
1134
  promoted++
1100
1135
  continue
1101
1136
  }
@@ -1105,18 +1140,20 @@ export function promoteAllTasksToProject(store, globalStore, cfg, now) {
1105
1140
  )
1106
1141
  moved.id = ins.id
1107
1142
  moved.draft = false
1143
+ moved.lastHitAt = now
1108
1144
  moved.confidence = num(ins.confidence, cfg.promoteConfidence)
1109
1145
  moved.movedFrom = { scope: 'task', id: ins.id, at: now }
1110
1146
  pjItems.push(moved)
1111
1147
  store.replaceInsightItems(pjItems)
1112
1148
  removeFromTask(store, ins.id)
1149
+ promotedIds.add(moved.id)
1113
1150
  promoted++
1114
1151
  }
1115
1152
  }
1116
1153
  if (promoted) {
1117
1154
  const items = store.insightItems()
1118
1155
  applyDecay(items, cfg, now)
1119
- pruneItems(items, cfg.maxProject, now)
1156
+ pruneItems(items, cfg.maxProject, now, { protectedIds: promotedIds.size === 1 ? promotedIds : new Set() })
1120
1157
  promoteProjectToGlobal(store, globalStore, cfg, now)
1121
1158
  }
1122
1159
  return promoted
@@ -1127,15 +1164,17 @@ export function promoteProjectToGlobal(store, globalStore, cfg, now) {
1127
1164
  if (!globalStore) return 0
1128
1165
  const items = store.insightItems()
1129
1166
  let moved = 0
1167
+ const movedIds = new Set()
1130
1168
  for (const ins of [...items]) {
1131
1169
  if (ins.scope && ins.scope !== 'project') continue
1132
- if (ins.draft === true) continue
1170
+ if (ins.draft === true || ins.archived || ins.promoteHold) continue
1133
1171
  const members = new Set(ins.sourceTaskIds || [])
1134
1172
  if (members.size < cfg.globalPromoteTasks) continue
1135
1173
  const glItems = globalStore.items()
1136
- const glHit = findBestOverlapMatch(insightMatchText(ins), glItems)
1174
+ const sameId = glItems.find((it) => it && it.id === ins.id)
1175
+ const glHit = sameId ? { item: sameId, score: 1 } : findBestOverlapMatch(insightMatchText(ins), glItems)
1137
1176
  if (glHit && glHit.score >= cfg.dedupOverlap) {
1138
- mergeInto(glHit.item, { sourceTaskIds: ins.sourceTaskIds, files: ins.files, symbols: ins.symbols, tags: ins.tags, confidence: ins.confidence }, cfg, now)
1177
+ mergeInto(glHit.item, ins, cfg, now)
1139
1178
  } else {
1140
1179
  const movedIns = carryUsageFields(
1141
1180
  normalizeInsight(ins, { scope: 'global', source: ins.source, nowIso: now }),
@@ -1143,23 +1182,47 @@ export function promoteProjectToGlobal(store, globalStore, cfg, now) {
1143
1182
  )
1144
1183
  movedIns.id = ins.id
1145
1184
  movedIns.draft = false
1185
+ movedIns.lastHitAt = now
1146
1186
  movedIns.confidence = num(ins.confidence, cfg.promoteConfidence)
1147
1187
  movedIns.movedFrom = { scope: 'project', id: ins.id, at: now }
1148
1188
  glItems.push(movedIns)
1149
1189
  }
1150
1190
  items.splice(items.indexOf(ins), 1)
1191
+ movedIds.add(ins.id)
1151
1192
  moved++
1152
1193
  }
1153
1194
  if (moved) {
1154
1195
  store.replaceInsightItems(items)
1155
1196
  // 提升只增不减 global:不在这里收口,maxGlobalProcedures 就形同虚设。
1156
- pruneItems(globalStore.items(), cfg.maxGlobalProcedures, now)
1197
+ pruneItems(globalStore.items(), cfg.maxGlobalProcedures, now, { protectedIds: movedIds.size === 1 ? movedIds : new Set() })
1157
1198
  globalStore.markDirty()
1158
1199
  }
1159
1200
  return moved
1160
1201
  }
1161
1202
 
1162
- // ---- 降级(反向,PR3 UI 使用;现在提供最小实现) ----
1203
+ // ---- 降级(反向,PR3 UI 使用) ----
1204
+
1205
+ /**
1206
+ * 落点去重:同 id 或近重复(≥ dedupOverlap)合并,否则 push;来源删除/容量收口由调用方做。
1207
+ * 提升/降级与面板的四个目标池共用这一份,避免 store 与命令层各有一套去重规则。
1208
+ */
1209
+ export function mergeOrPushInto({ targetPool, copy, cfg, nowIso }) {
1210
+ // 同 id 必须比 id 而不是相似度:'ins_dup' 已在目标池时再移动同 id,指纹类字段可能因后来编辑
1211
+ // 而分叉,靠相似度会漏判——同 id 是确定事实,直接合并。
1212
+ const sameId = targetPool.find((it) => it && it.id === copy.id)
1213
+ if (sameId) {
1214
+ mergeInto(sameId, copy, cfg, nowIso)
1215
+ return { merged: true, target: sameId }
1216
+ }
1217
+ const hit = findBestOverlapMatch(insightMatchText(copy), targetPool)
1218
+ const threshold = cfg?.dedupOverlap ?? 0.7
1219
+ if (hit && hit.score >= threshold) {
1220
+ mergeInto(hit.item, copy, cfg, nowIso)
1221
+ return { merged: true, target: hit.item }
1222
+ }
1223
+ targetPool.push(copy)
1224
+ return { merged: false, target: copy }
1225
+ }
1163
1226
 
1164
1227
  export function demoteToProject(store, globalStore, id, nowIso, cfg = cfgInsight({})) {
1165
1228
  if (!globalStore) return { ok: false, error: 'global 存储未初始化' }
@@ -1171,16 +1234,17 @@ export function demoteToProject(store, globalStore, id, nowIso, cfg = cfgInsight
1171
1234
  const copy = carryUsageFields(normalizeInsight(ins, { scope: 'project', nowIso: now }), ins)
1172
1235
  copy.id = `${ins.id}_d${Date.now().toString(36)}`
1173
1236
  copy.movedFrom = { scope: 'global', id: ins.id, at: now }
1174
- items.push(copy)
1175
- // 降级只增不减 project:同样要收口 maxProject。
1176
- pruneItems(items, cfg.maxProject, now)
1237
+ copy.promoteHold = true
1238
+ const { merged, target } = mergeOrPushInto({ targetPool: items, copy, cfg, nowIso: now })
1239
+ // 降级只增不减 project:同样要收口 maxProject;被移动的条目必须豁免。
1240
+ pruneItems(items, cfg.maxProject, now, { protectedIds: new Set([target.id]) })
1177
1241
  store.replaceInsightItems(items)
1178
1242
  globalStore.items().splice(idx, 1)
1179
1243
  globalStore.markDirty()
1180
- return { ok: true, action: 'demoted', id: copy.id, hint: '已降级回 project' }
1244
+ return { ok: true, action: 'demoted', id: target.id, merged, target, hint: '已降级回 project' }
1181
1245
  }
1182
1246
 
1183
- export function demoteToTask(store, taskId, id, nowIso) {
1247
+ export function demoteToTask(store, taskId, id, nowIso, cfg = cfgInsight({})) {
1184
1248
  const now = nowIso || new Date().toISOString()
1185
1249
  const task = store.getTask(taskId)
1186
1250
  if (!task) return { ok: false, error: `任务不存在: ${taskId}` }
@@ -1192,11 +1256,12 @@ export function demoteToTask(store, taskId, id, nowIso) {
1192
1256
  const copy = carryUsageFields(normalizeInsight(ins, { scope: 'task', nowIso: now }), ins)
1193
1257
  copy.id = `${ins.id}_d${Date.now().toString(36)}`
1194
1258
  copy.movedFrom = { scope: 'project', id: ins.id, at: now }
1195
- task.insights.push(copy)
1259
+ copy.promoteHold = true
1260
+ const { merged, target } = mergeOrPushInto({ targetPool: task.insights, copy, cfg, nowIso: now })
1196
1261
  items.splice(idx, 1)
1197
1262
  store.replaceInsightItems(items)
1198
1263
  store.markTasksDirty()
1199
- return { ok: true, action: 'demoted', id: copy.id, hint: '已降级到任务级' }
1264
+ return { ok: true, action: 'demoted', id: target.id, merged, target, hint: '已降级到任务级' }
1200
1265
  }
1201
1266
 
1202
1267
  /** 便捷:直接对归一化后文本算重叠(测试用)。 */
package/src/lazy.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  findProjectRootWithSource,
8
8
  isGitIgnored,
9
9
  isGitIgnoredBatch,
10
+ isDefaultIgnoredRel,
10
11
  isHiddenPath,
11
12
  memoryRootFor,
12
13
  relativePath,
@@ -50,12 +51,6 @@ function rootCacheFor(config) {
50
51
  return cache
51
52
  }
52
53
 
53
- /** 清空根缓存(测试 / 诊断;不传 config 表示全清)。 */
54
- export function clearRootCache(config) {
55
- if (config) rootCaches.delete(config)
56
- else rootCaches.clear()
57
- }
58
-
59
54
  function cachedProjectRoot(config, filePath, watchManager, sessionRoot) {
60
55
  const cache = rootCacheFor(config)
61
56
  const dir = path.dirname(filePath)
@@ -87,43 +82,54 @@ export async function indexObservedBatch(config, items, watchManager = null) {
87
82
  const candidates = []
88
83
 
89
84
  for (const item of items) {
90
- const { filePath, sessionRoot } = item
85
+ const { filePath: rawPath, sessionRoot } = item
86
+ const key = rawPath
91
87
  try {
88
+ if (typeof rawPath !== 'string' || !rawPath) {
89
+ results.set(key, false)
90
+ continue
91
+ }
92
+ // FsTarget.displayPath 可能是工作区相对路径;按会话 cwd 解析,不能落到宿主进程 cwd。
93
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(rawPath) || (/^[a-z][a-z0-9+.-]*:/i.test(rawPath) && !/^[a-z]:[\\/]/i.test(rawPath))) {
94
+ results.set(key, false)
95
+ continue
96
+ }
97
+ const filePath = path.isAbsolute(rawPath) ? rawPath : path.resolve(sessionRoot || process.cwd(), rawPath)
92
98
  const kind = fileKind(path.extname(filePath).toLowerCase())
93
99
  if (!kind) {
94
- results.set(filePath, false)
100
+ results.set(key, false)
95
101
  continue
96
102
  }
97
103
  // roots.exclude 是子树级否定:被排除的文件连根都不推导,直接不落任何记忆。
98
104
  if (excludedEntryForPath(filePath, config)) {
99
- results.set(filePath, false)
105
+ results.set(key, false)
100
106
  continue
101
107
  }
102
108
  const root = cachedProjectRoot(config, filePath, watchManager, sessionRoot)
103
109
  if (!root || rootRejection(root, config)) {
104
- results.set(filePath, false)
110
+ results.set(key, false)
105
111
  continue
106
112
  }
107
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
108
- const rel = storeKey(relativePath(root, filePath))
109
- // 隐藏路径与扫描口径一致:`.env` / `.github/**` 这类默认是配置/状态/密钥,不因模型
110
- // 偶然读了一次就进语料;要索引就显式 `index_doc`。
111
- if (isHiddenPath(rel)) {
112
- results.set(filePath, false)
113
+ const relRaw = relativePath(root, filePath)
114
+ // 与 index_repo/watch 同口径;判在 store 读盘与 stat 之前,省掉无谓 IO。
115
+ if (isHiddenPath(relRaw) || isDefaultIgnoredRel(relRaw)) {
116
+ results.set(key, false)
113
117
  continue
114
118
  }
119
+ const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
120
+ const rel = storeKey(relRaw)
115
121
  const record = store.fileRecord(rel)
116
122
  const st = statSync(filePath)
117
123
  // 快路径:mtime + size 都没动 → 连 git 都不用问。这是"重复读同一个文件"的主路径。
118
124
  // doc 不走这条捷径:旧 store 的 terms 回填条件要看 entries,交给 planFileIndex 判。
119
125
  if (kind === 'code' && record && typeof record.mtimeMs === 'number' && record.mtimeMs === st.mtimeMs && record.size === st.size) {
120
- results.set(filePath, false)
126
+ results.set(key, false)
121
127
  continue
122
128
  }
123
- candidates.push({ store, root, rel, filePath, kind, record, size: st.size, mtimeMs: st.mtimeMs, gitRel: relativePath(root, filePath) })
124
- results.set(filePath, false)
129
+ candidates.push({ store, root, rel, filePath, key, kind, record, size: st.size, mtimeMs: st.mtimeMs, gitRel: relRaw })
130
+ results.set(key, false)
125
131
  } catch {
126
- results.set(filePath, false)
132
+ results.set(key, false)
127
133
  }
128
134
  }
129
135
 
@@ -183,17 +189,17 @@ export async function indexObservedBatch(config, items, watchManager = null) {
183
189
  if (plan.key === OVERSIZE) {
184
190
  // 与 index_repo 同一语义:文件涨过阈值后,旧条目必须摘掉,而不是只跳过本轮。
185
191
  updates.push({ rel: cand.rel, drop: true })
186
- results.set(cand.filePath, false)
192
+ results.set(cand.key, false)
187
193
  continue
188
194
  }
189
195
  updates.push(toFileUpdate(cand.rel, plan, cand.record))
190
196
  if (plan.key !== DROP && plan.type === 'code') codeToEnhance.push([cand.rel, cand.filePath])
191
- results.set(cand.filePath, plan.key !== DROP)
197
+ results.set(cand.key, plan.key !== DROP)
192
198
  } catch (err) {
193
199
  // 单文件读盘 / 解析失败不影响同批其它文件;但要登记,否则"读了却没索引成"
194
200
  // 在界面上完全不可见(过去这里连日志都没有)。
195
201
  recordIndexFailure(cand.root, cand.rel, err.message)
196
- results.set(cand.filePath, false)
202
+ results.set(cand.key, false)
197
203
  }
198
204
  }
199
205
 
package/src/llm-route.js CHANGED
@@ -66,7 +66,7 @@ export function resolveRoute(exec, config) {
66
66
 
67
67
  /**
68
68
  * 记录一次降级(允许降级,不允许静默)。同一 code 只打印一次,避免逐 chunk 刷屏;
69
- * 计数与最近原因保留下来,供 memory_stats / 测试读取。
69
+ * 计数与最近原因保留下来,供 pm_stats / 测试读取。
70
70
  */
71
71
  export function noteDegraded(code, reason) {
72
72
  const at = new Date().toISOString()
package/src/llm.js CHANGED
@@ -2,19 +2,12 @@
2
2
  // chatText 是唯一的宿主调用出口:provider/model 必填,缺失时显式抛错,由调用方决定回退并记 degraded。
3
3
  import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
4
4
  import { noteDegraded } from './llm-route.js'
5
+ import { textOf } from './util/text.js'
5
6
 
6
7
  function systemMessage(text) {
7
8
  return { role: 'system', content: [{ type: 'text', text }] }
8
9
  }
9
10
 
10
- function textOf(message) {
11
- const blocks = message.content || []
12
- return blocks
13
- .filter((b) => b.type === 'text' && typeof b.text === 'string')
14
- .map((b) => b.text)
15
- .join('\n')
16
- }
17
-
18
11
  export async function chatText(llm, system, user, { timeoutMs = 120000, route } = {}) {
19
12
  // provider/model 是宿主 GenerateOptions 的必填项,缺失时 LlmRuntime 抛 NO_ADAPTER。
20
13
  // 这里显式失败(由调用方决定回退并记 degraded),不让异常悄悄消失。