@yolk_vat-y/dsh-project-memory 0.6.12 → 0.7.1

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 (66) hide show
  1. package/CHANGELOG.md +68 -20
  2. package/README.md +14 -105
  3. package/README.zh-CN.md +14 -105
  4. package/client/client.js +311 -163
  5. package/client/client.js.map +1 -1
  6. package/package.json +8 -8
  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 +121 -51
  14. package/src/client/TaskCommandNode.tsx +6 -4
  15. package/src/client/TaskComponents.tsx +14 -26
  16. package/src/client/TaskPanel.tsx +44 -23
  17. package/src/client/client.ts +4 -7
  18. package/src/client/i18n.ts +29 -0
  19. package/src/client/kind-label.js +38 -0
  20. package/src/client/paging.js +1 -14
  21. package/src/client/settings-card.tsx +9 -0
  22. package/src/client/slash.ts +4 -15
  23. package/src/client/task-data-store.ts +57 -7
  24. package/src/client/task-hooks.ts +0 -2
  25. package/src/client/task-scope.js +16 -1
  26. package/src/client/task-ui-store.ts +1 -1
  27. package/src/commands/insight-actions.js +85 -60
  28. package/src/commands/task-actions.js +7 -5
  29. package/src/commands/tasks.js +34 -10
  30. package/src/doc-index.js +3 -1
  31. package/src/enhancer.js +0 -12
  32. package/src/index-failures.js +1 -1
  33. package/src/index-pipeline.js +11 -2
  34. package/src/index.js +60 -14
  35. package/src/inject-visible.js +282 -0
  36. package/src/insight-store.js +129 -32
  37. package/src/lazy.js +29 -23
  38. package/src/llm-route.js +1 -1
  39. package/src/ops.js +18 -5
  40. package/src/parsers/pdfjs-parser.js +3 -33
  41. package/src/project-memory-service.js +195 -0
  42. package/src/project-profile.js +0 -4
  43. package/src/setup/taskbridge.js +38 -6
  44. package/src/store.js +638 -135
  45. package/src/symbols.js +2 -4
  46. package/src/tools/forget.js +3 -6
  47. package/src/tools/index-doc.js +61 -18
  48. package/src/tools/index-repo.js +16 -12
  49. package/src/tools/lesson-tools.js +5 -5
  50. package/src/tools/output.js +28 -0
  51. package/src/tools/query-memory.js +6 -9
  52. package/src/tools/remember.js +3 -6
  53. package/src/tools/stats.js +3 -6
  54. package/src/tools/task-tools.js +15 -8
  55. package/src/tools/watch-repo.js +15 -12
  56. package/src/util/flush.js +1 -1
  57. package/src/util/fs.js +135 -20
  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/vector-index.js +2 -2
  63. package/src/watch.js +25 -8
  64. package/client/client.d.ts +0 -27
  65. package/client/client.d.ts.map +0 -1
  66. package/client/style.css +0 -395
@@ -10,7 +10,7 @@ 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
16
  import { isRecord, isoMs, newerIso } from './util/value.js'
@@ -31,11 +31,11 @@ export const SECRET_PATTERNS = [
31
31
  ]
32
32
 
33
33
  /** 检测疑似密钥/token/私钥形态内容;命中返回第一个命中字段名,否则 null。 */
34
- 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']) {
35
35
  for (const f of fields) {
36
36
  const v = ins && ins[f]
37
37
  if (!v) continue
38
- 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)
39
39
  for (const re of SECRET_PATTERNS) if (re.test(text)) return f
40
40
  }
41
41
  return null
@@ -89,6 +89,7 @@ const ARRAY_FIELDS = ['steps', 'files', 'symbols', 'tags', 'sourceTaskIds']
89
89
 
90
90
  /** 由工具/测试传入的 raw 构造规范 insight(scope/source/timestamps 由调用方定)。 */
91
91
  export function normalizeInsight(raw, extra = {}) {
92
+ raw = isRecord(raw) ? raw : {}
92
93
  const kind = INSIGHT_KINDS.includes(raw.kind) ? raw.kind : 'lesson'
93
94
  const now = extra.nowIso || new Date().toISOString()
94
95
  const ins = {
@@ -163,6 +164,8 @@ export function carryUsageFields(copy, src) {
163
164
  if (src.lastHitAt) copy.lastHitAt = src.lastHitAt
164
165
  if (src.createdAt) copy.createdAt = src.createdAt
165
166
  if (src.triggerDerived) copy.triggerDerived = src.triggerDerived
167
+ if (src.archived) copy.archived = true
168
+ if (src.promoteHold) copy.promoteHold = true
166
169
  // `prev` 是被覆盖挤掉的那一版,必须跟着条目走:promote/demote 走白名单,漏了它就丢了"还能还原"。
167
170
  if (src.prev && typeof src.prev === 'object') copy.prev = src.prev
168
171
  return copy
@@ -185,9 +188,49 @@ function putField(item, key, next, replaced) {
185
188
  replaced.push(key)
186
189
  }
187
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
+
188
211
  /** 自动合并会改写的正文字段(title 也在内:0.90 以上的两条标题本就近乎同一句)。 */
189
212
  const MERGE_FIELDS = ['title', 'pattern', 'fix', 'choice', 'reason', 'problem', 'solution', 'body']
190
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
+
191
234
  /**
192
235
  * 把 base 合并进既有条目:**正文取新值**(旧值进 `prev`),成员/文件/符号并集,置信取高,记命中。
193
236
  * 提升路径只传成员/文件/符号/置信,不传正文字段,语义未变。
@@ -195,6 +238,7 @@ const MERGE_FIELDS = ['title', 'pattern', 'fix', 'choice', 'reason', 'problem',
195
238
  */
196
239
  export function mergeInto(existing, base, cfg, nowIso) {
197
240
  const now = nowIso || new Date().toISOString()
241
+ const before = derivedSourceSnapshot(existing)
198
242
  existing.sourceTaskIds = unionStrings(existing.sourceTaskIds, base.sourceTaskIds)
199
243
  existing.files = unionStrings(existing.files, base.files)
200
244
  existing.symbols = unionStrings(existing.symbols, base.symbols)
@@ -206,7 +250,9 @@ export function mergeInto(existing, base, cfg, nowIso) {
206
250
  putField(existing, f, String(b), replaced)
207
251
  }
208
252
  if (Array.isArray(base.steps) && base.steps.length) putField(existing, 'steps', base.steps.map(String), replaced)
209
- 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)
210
256
  existing.confidence = Math.max(num(existing.confidence, 0.5), num(base.confidence, 0.5))
211
257
  existing.hitCount = (existing.hitCount || 0) + 1
212
258
  existing.lastHitAt = now
@@ -223,6 +269,7 @@ const UPDATE_ARRAYS = ['steps', 'files', 'symbols', 'tags']
223
269
  export function applyUpdate(item, raw, nowIso) {
224
270
  const now = nowIso || new Date().toISOString()
225
271
  const replaced = []
272
+ const before = derivedSourceSnapshot(item)
226
273
  const oldKind = item.kind
227
274
  for (const f of UPDATE_FIELDS) {
228
275
  const v = raw[f]
@@ -242,7 +289,7 @@ export function applyUpdate(item, raw, nowIso) {
242
289
  continue
243
290
  }
244
291
  if (f === 'trigger') {
245
- if (typeof v === 'object') putField(item, 'trigger', v, replaced)
292
+ if (typeof v === 'object') putField(item, 'trigger', mergeAuthoredTrigger(item.trigger, v), replaced)
246
293
  continue
247
294
  }
248
295
  putField(item, f, String(v), replaced)
@@ -250,6 +297,8 @@ export function applyUpdate(item, raw, nowIso) {
250
297
  // 改 kind 时清掉旧 kind 的专属字段(procedure 保留通用 body):否则 lesson→decision 后
251
298
  // `fix` 会盖在 `choice` 前面进入正文/摘要(insightBodyText 的优先级是 fix > choice > …)。
252
299
  pruneKindFields(item, oldKind)
300
+ // 正文(含 steps、切 kind 时被清掉的旧字段)真的变了才重算派生词;改 confidence 等元数据不碰。
301
+ if (derivedSourceSnapshot(item) !== before) refreshDerivedTrigger(item)
253
302
  item.updatedAt = now
254
303
  if (item.archived) item.archived = false
255
304
  // 显式编辑一条草稿 = 作者确认:reflection 产出的 draft 可被 save_lesson 带 id 直接改正文并转正。
@@ -336,17 +385,27 @@ function autoMergeTarget(near, cfg) {
336
385
  * 只记非归档条目。返回实际加一的条数,调用方据此决定是否落盘。
337
386
  * @returns {number} 被加一的条目数
338
387
  */
339
- export function recordHit({ store, globalStore, ids, nowIso } = {}) {
388
+ export function recordHit({ store, globalStore, ids, nowIso, delta = 1, restore = null } = {}) {
340
389
  const want = new Set((ids || []).filter(Boolean))
341
390
  if (!want.size) return 0
342
391
  const now = nowIso || new Date().toISOString()
392
+ const step = Number(delta) || 0
393
+ if (!step) return 0
343
394
  let n = 0
344
395
  const touch = (items) => {
345
396
  let c = 0
346
397
  for (const it of items || []) {
347
398
  if (!it || it.archived || !want.has(it.id)) continue
348
- it.hitCount = num(it.hitCount, 0) + 1
349
- 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
+ }
350
409
  c++
351
410
  }
352
411
  n += c
@@ -423,19 +482,19 @@ export function applyDecay(items, cfg, nowIso) {
423
482
  * 注意:没有归档可删时,本轮归档的条目会在同一次调用的后续循环里被删掉——
424
483
  * `archived` 计数是"先归档、随即被删",不是"留下了软删副本"。
425
484
  */
426
- export function pruneItems(items, max, nowIso) {
485
+ export function pruneItems(items, max, nowIso, { protectedIds = new Set() } = {}) {
427
486
  const now = nowIso || new Date().toISOString()
428
487
  let removed = 0
429
488
  let archivedNow = 0
430
489
  while (items.length > max) {
431
- 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))
432
491
  if (arch.length) {
433
492
  const victim = arch[0]
434
493
  const idx = items.indexOf(victim)
435
494
  if (idx !== -1) items.splice(idx, 1)
436
495
  removed++
437
496
  } else {
438
- 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))
439
498
  const victim = sorted[0]
440
499
  if (!victim) break
441
500
  victim.archived = true
@@ -839,6 +898,7 @@ function removeEntries({ store, globalStore }, entries) {
839
898
  * 返回 { ok, action, id, replaced, near, hint }。
840
899
  */
841
900
  export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null }) {
901
+ if (!isRecord(raw)) return { ok: false, error: '内容必须是对象(不能是 null/数组/字符串)' }
842
902
  const cfg2 = cfg || cfgInsight({})
843
903
  const now = nowIso || new Date().toISOString()
844
904
  const secretField = containsSecretFields(raw)
@@ -870,7 +930,7 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
870
930
  if (s === 'global') {
871
931
  if (!globalStore) return { ok: false, error: 'global 存储未初始化' }
872
932
  const res = upsertIntoPool(globalStore.items(), raw, cfg2, now, { source, scope: 'global', cosine })
873
- 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]) })
874
934
  globalStore.markDirty()
875
935
  return { ok: true, ...res, scope: 'global', hint: res.hint || buildHint(res) }
876
936
  }
@@ -878,6 +938,9 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
878
938
  if (!store || !taskId) return { ok: false, error: 'task 级写入需要 taskId' }
879
939
  const task = store.getTask(taskId)
880
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 解归档再写入)` }
881
944
  return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine)
882
945
  }
883
946
  return saveProjectInsight(store, globalStore, raw, cfg2, now, source, cosine)
@@ -906,6 +969,7 @@ function upsertIntoPool(items, raw, cfg, nowIso, extra = {}) {
906
969
  return { action: 'reinforced', id: hit.item.id }
907
970
  }
908
971
  const ins = normalizeInsight(base, { scope: extra.scope || 'project', source: extra.source, nowIso })
972
+ refreshDerivedTrigger(ins)
909
973
  items.push(ins)
910
974
  const hint = hintOf(near, cfg)
911
975
  return hint ? { action: 'created', id: ins.id, near: hint } : { action: 'created', id: ins.id }
@@ -918,7 +982,7 @@ function saveProjectInsight(store, globalStore, raw, cfg, now, source, cosine) {
918
982
  const res = upsertIntoPool(items, raw, cfg, now, { source, scope: 'project', cosine })
919
983
  store.replaceInsightItems(items) // 一律标脏(created/merged/auto-merged/reinforced 都改了数组)
920
984
  applyDecay(items, cfg, now)
921
- const pruned = pruneItems(items, cfg.maxProject, now)
985
+ const pruned = pruneItems(items, cfg.maxProject, now, { protectedIds: new Set([res.id]) })
922
986
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
923
987
  return { ok: true, ...res, scope: 'project', hint: buildHint(res, pruned, promoted) }
924
988
  }
@@ -957,7 +1021,7 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
957
1021
  const { replaced } = mergeInto(pjTarget.item, base, cfg, now)
958
1022
  store.replaceInsightItems(pjItems)
959
1023
  applyDecay(pjItems, cfg, now)
960
- pruneItems(pjItems, cfg.maxProject, now)
1024
+ pruneItems(pjItems, cfg.maxProject, now, { protectedIds: new Set([pjTarget.item.id]) })
961
1025
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
962
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' : ''}` }
963
1027
  }
@@ -966,7 +1030,7 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
966
1030
  const { replaced } = mergeInto(pjHit.item, base, cfg, now)
967
1031
  store.replaceInsightItems(pjItems)
968
1032
  applyDecay(pjItems, cfg, now)
969
- pruneItems(pjItems, cfg.maxProject, now)
1033
+ pruneItems(pjItems, cfg.maxProject, now, { protectedIds: new Set([pjHit.item.id]) })
970
1034
  const promoted = promoteProjectToGlobal(store, globalStore, cfg, now)
971
1035
  return { ok: true, action: 'linked-project', id: pjHit.item.id, scope: 'project', replaced, hint: `该知识已在 project 级,累计第 ${(pjHit.item.sourceTaskIds || []).length} 个任务命中${promoted ? ';已自动提升 global' : ''}` }
972
1036
  }
@@ -1048,22 +1112,25 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
1048
1112
  export function promoteAllTasksToProject(store, globalStore, cfg, now) {
1049
1113
  const tasks = store.getTasks() || []
1050
1114
  let promoted = 0
1115
+ const promotedIds = new Set()
1051
1116
  for (const task of tasks) {
1052
1117
  const list = task.insights || []
1053
1118
  for (const ins of [...list]) {
1054
1119
  if (ins.scope && ins.scope !== 'task') continue
1055
1120
  // 草稿必须先被确认;自动提升绕过审核就等于把 reflection 的猜测变成项目资产。
1056
- if (ins.draft === true) continue
1121
+ if (ins.draft === true || ins.archived || ins.promoteHold) continue
1057
1122
  const members = new Set(ins.sourceTaskIds || [])
1058
1123
  if (members.size < 2) continue
1059
1124
  if (num(ins.confidence, 0) < cfg.promoteConfidence) continue
1060
- // 与 project 已有资产去重:重复 → 并成员,删 task 副本
1125
+ // 与 project 已有资产去重:同 id 先合并(历史脏数据),再按相似度;正文随移动带走。
1061
1126
  const pjItems = store.insightItems()
1062
- 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)
1063
1129
  if (pjHit && pjHit.score >= cfg.dedupOverlap) {
1064
- 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)
1065
1131
  store.replaceInsightItems(pjItems)
1066
1132
  removeFromTask(store, ins.id)
1133
+ promotedIds.add(pjHit.item.id)
1067
1134
  promoted++
1068
1135
  continue
1069
1136
  }
@@ -1073,18 +1140,20 @@ export function promoteAllTasksToProject(store, globalStore, cfg, now) {
1073
1140
  )
1074
1141
  moved.id = ins.id
1075
1142
  moved.draft = false
1143
+ moved.lastHitAt = now
1076
1144
  moved.confidence = num(ins.confidence, cfg.promoteConfidence)
1077
1145
  moved.movedFrom = { scope: 'task', id: ins.id, at: now }
1078
1146
  pjItems.push(moved)
1079
1147
  store.replaceInsightItems(pjItems)
1080
1148
  removeFromTask(store, ins.id)
1149
+ promotedIds.add(moved.id)
1081
1150
  promoted++
1082
1151
  }
1083
1152
  }
1084
1153
  if (promoted) {
1085
1154
  const items = store.insightItems()
1086
1155
  applyDecay(items, cfg, now)
1087
- pruneItems(items, cfg.maxProject, now)
1156
+ pruneItems(items, cfg.maxProject, now, { protectedIds: promotedIds.size === 1 ? promotedIds : new Set() })
1088
1157
  promoteProjectToGlobal(store, globalStore, cfg, now)
1089
1158
  }
1090
1159
  return promoted
@@ -1095,15 +1164,17 @@ export function promoteProjectToGlobal(store, globalStore, cfg, now) {
1095
1164
  if (!globalStore) return 0
1096
1165
  const items = store.insightItems()
1097
1166
  let moved = 0
1167
+ const movedIds = new Set()
1098
1168
  for (const ins of [...items]) {
1099
1169
  if (ins.scope && ins.scope !== 'project') continue
1100
- if (ins.draft === true) continue
1170
+ if (ins.draft === true || ins.archived || ins.promoteHold) continue
1101
1171
  const members = new Set(ins.sourceTaskIds || [])
1102
1172
  if (members.size < cfg.globalPromoteTasks) continue
1103
1173
  const glItems = globalStore.items()
1104
- 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)
1105
1176
  if (glHit && glHit.score >= cfg.dedupOverlap) {
1106
- 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)
1107
1178
  } else {
1108
1179
  const movedIns = carryUsageFields(
1109
1180
  normalizeInsight(ins, { scope: 'global', source: ins.source, nowIso: now }),
@@ -1111,23 +1182,47 @@ export function promoteProjectToGlobal(store, globalStore, cfg, now) {
1111
1182
  )
1112
1183
  movedIns.id = ins.id
1113
1184
  movedIns.draft = false
1185
+ movedIns.lastHitAt = now
1114
1186
  movedIns.confidence = num(ins.confidence, cfg.promoteConfidence)
1115
1187
  movedIns.movedFrom = { scope: 'project', id: ins.id, at: now }
1116
1188
  glItems.push(movedIns)
1117
1189
  }
1118
1190
  items.splice(items.indexOf(ins), 1)
1191
+ movedIds.add(ins.id)
1119
1192
  moved++
1120
1193
  }
1121
1194
  if (moved) {
1122
1195
  store.replaceInsightItems(items)
1123
1196
  // 提升只增不减 global:不在这里收口,maxGlobalProcedures 就形同虚设。
1124
- pruneItems(globalStore.items(), cfg.maxGlobalProcedures, now)
1197
+ pruneItems(globalStore.items(), cfg.maxGlobalProcedures, now, { protectedIds: movedIds.size === 1 ? movedIds : new Set() })
1125
1198
  globalStore.markDirty()
1126
1199
  }
1127
1200
  return moved
1128
1201
  }
1129
1202
 
1130
- // ---- 降级(反向,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
+ }
1131
1226
 
1132
1227
  export function demoteToProject(store, globalStore, id, nowIso, cfg = cfgInsight({})) {
1133
1228
  if (!globalStore) return { ok: false, error: 'global 存储未初始化' }
@@ -1139,16 +1234,17 @@ export function demoteToProject(store, globalStore, id, nowIso, cfg = cfgInsight
1139
1234
  const copy = carryUsageFields(normalizeInsight(ins, { scope: 'project', nowIso: now }), ins)
1140
1235
  copy.id = `${ins.id}_d${Date.now().toString(36)}`
1141
1236
  copy.movedFrom = { scope: 'global', id: ins.id, at: now }
1142
- items.push(copy)
1143
- // 降级只增不减 project:同样要收口 maxProject。
1144
- 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]) })
1145
1241
  store.replaceInsightItems(items)
1146
1242
  globalStore.items().splice(idx, 1)
1147
1243
  globalStore.markDirty()
1148
- return { ok: true, action: 'demoted', id: copy.id, hint: '已降级回 project' }
1244
+ return { ok: true, action: 'demoted', id: target.id, merged, target, hint: '已降级回 project' }
1149
1245
  }
1150
1246
 
1151
- export function demoteToTask(store, taskId, id, nowIso) {
1247
+ export function demoteToTask(store, taskId, id, nowIso, cfg = cfgInsight({})) {
1152
1248
  const now = nowIso || new Date().toISOString()
1153
1249
  const task = store.getTask(taskId)
1154
1250
  if (!task) return { ok: false, error: `任务不存在: ${taskId}` }
@@ -1160,11 +1256,12 @@ export function demoteToTask(store, taskId, id, nowIso) {
1160
1256
  const copy = carryUsageFields(normalizeInsight(ins, { scope: 'task', nowIso: now }), ins)
1161
1257
  copy.id = `${ins.id}_d${Date.now().toString(36)}`
1162
1258
  copy.movedFrom = { scope: 'project', id: ins.id, at: now }
1163
- task.insights.push(copy)
1259
+ copy.promoteHold = true
1260
+ const { merged, target } = mergeOrPushInto({ targetPool: task.insights, copy, cfg, nowIso: now })
1164
1261
  items.splice(idx, 1)
1165
1262
  store.replaceInsightItems(items)
1166
1263
  store.markTasksDirty()
1167
- return { ok: true, action: 'demoted', id: copy.id, hint: '已降级到任务级' }
1264
+ return { ok: true, action: 'demoted', id: target.id, merged, target, hint: '已降级到任务级' }
1168
1265
  }
1169
1266
 
1170
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/ops.js CHANGED
@@ -72,6 +72,11 @@ const QUERY_TOOLS = new Set(['query_memory', 'recall'])
72
72
  * 参数、路径、引号里的词都只是**提及**(`find … bench …` 的目录名、`grep -rn "migrate" docs`)。
73
73
  * 命令头才是"这个 shell 到底在做什么"的唯一可靠位置。
74
74
  */
75
+ /** git 子命令里会改工作区/索引的写族:op 映射与 targets 抽取必须同一口径。 */
76
+ const GIT_WRITE_SUBCOMMANDS = new Set([
77
+ 'rm', 'checkout', 'restore', 'reset', 'apply', 'merge', 'rebase', 'cherry-pick', 'stash', 'mv', 'clean',
78
+ ])
79
+
75
80
  const WRITE_HEADS = new Set(['rm', 'rmdir', 'unlink', 'shred', 'mv', 'cp', 'touch', 'tee', 'truncate', 'mkdir'])
76
81
  /**
77
82
  * Windows / PowerShell 的写盘命令。与 POSIX 同名命令并列而不是另开分支:`isWriteSegment()` 与
@@ -280,8 +285,8 @@ function opsOfHead(head, rest) {
280
285
  if (gsub === 'commit' || gsub === 'add') return ['git-commit']
281
286
  if (gsub === 'push') return ['git-push']
282
287
  if (gsub === 'tag') return ['release']
283
- if (gsub === 'rm') return ['file-delete']
284
- if (gsub === 'checkout' || gsub === 'restore' || gsub === 'reset') return ['file-write']
288
+ if (gsub === 'rm' || gsub === 'clean') return ['file-delete']
289
+ if (GIT_WRITE_SUBCOMMANDS.has(gsub)) return ['file-write']
285
290
  return []
286
291
  }
287
292
  case 'rm': case 'rmdir': case 'unlink': case 'shred':
@@ -347,7 +352,9 @@ function isWriteSegment(head, rest, redirects) {
347
352
  if (redirects.length) return true
348
353
  if (WRITE_HEADS.has(head) || WINDOWS_WRITE_HEADS.has(head)) return true
349
354
  if (head === 'sed' && rest.includes('-i')) return true
350
- if (head === 'git' && String(rest[0] || '').toLowerCase() === 'rm') return true
355
+ // `git -C repo checkout -- src/a.ts` / `git -c core.x=y rm …`:子命令在全局 flag 之后,
356
+ // 不能只看 rest[0](否则 ops 判对了,targets 仍为空,when.writes 守卫静默失效)。
357
+ if (head === 'git' && GIT_WRITE_SUBCOMMANDS.has(firstSubcommand(rest))) return true
351
358
  return false
352
359
  }
353
360
 
@@ -407,21 +414,27 @@ function classifyCommand(command, depth) {
407
414
  const targets = []
408
415
  for (const segment of unquotedSegments(stripHeredocBodies(raw))) {
409
416
  const { head, rest } = commandHead(tokenizeWords(segment))
417
+ // 每段单独收 op:写段是否补 file-write 只看本段是否为删除(`rm a && touch b` 不能吞 touch)。
418
+ const segmentOps = []
410
419
  if (SHELLS.has(head) && depth < 2) {
411
420
  // POSIX 的 `-c` / `-lc` / `-ec`;PowerShell 的 `-Command`;cmd 的 `/c`。
412
421
  const ci = rest.findIndex((a) => /^-[A-Za-z]{0,4}c$/.test(a) || /^-command$/i.test(a) || /^\/c$/i.test(a))
413
422
  if (ci >= 0 && rest[ci + 1]) {
414
423
  const inner = classifyCommand(rest.slice(ci + 1).join(' '), depth + 1)
415
- for (const op of inner.ops) if (op !== 'shell-run') pushUnique(ops, op)
424
+ for (const op of inner.ops) if (op !== 'shell-run') pushUnique(segmentOps, op)
416
425
  for (const t of inner.targets) pushUnique(targets, t)
417
426
  }
418
427
  } else {
419
- for (const op of opsOfHead(head, rest)) pushUnique(ops, op)
428
+ for (const op of opsOfHead(head, rest)) pushUnique(segmentOps, op)
420
429
  }
421
430
  const redirects = redirectTargets(segment)
422
431
  if (isWriteSegment(head, rest, redirects)) {
423
432
  for (const t of extractPathTokens(segment)) pushUnique(targets, t)
433
+ // 写段补 file-write:之前这些命令只剩 shell-run,`when.ops:['file-write']` 永不命中。
434
+ // 删除段保持 file-delete,不升级成写。
435
+ if (!segmentOps.includes('file-delete')) pushUnique(segmentOps, 'file-write')
424
436
  }
437
+ for (const op of segmentOps) pushUnique(ops, op)
425
438
  }
426
439
  if (!ops.length) ops.push('shell-run')
427
440
  // 主机面:`/mnt/c/…` 是 WSL 的路径签名;`pwsh.exe` / `powershell.exe` / `cmd.exe` 是**原生