@yolk_vat-y/dsh-project-memory 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,8 @@ import { trackDirty, untrackDirty } from './util/flush.js'
13
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'
16
+ import { isRecord, isoMs } from './util/value.js'
17
+ import { mergeById } from './util/merge-by-id.js'
17
18
  import { UNTITLED_TITLE, pruneKindFields, titleOf } from './util/insight-fields.js'
18
19
 
19
20
  export const INSIGHT_KINDS = ['lesson', 'decision', 'procedure', 'experience']
@@ -432,14 +433,18 @@ export function reinforceOnly(existing, base, nowIso) {
432
433
  return existing
433
434
  }
434
435
 
435
- function allTaskInsights(store) {
436
+ function allTaskInsights(store, taskVisible = null) {
436
437
  const out = []
437
- for (const t of store.getTasks() || []) for (const ins of t.insights || []) out.push(ins)
438
+ for (const t of store.getTasks() || []) {
439
+ if (taskVisible && !taskVisible(t)) continue
440
+ for (const ins of t.insights || []) out.push(ins)
441
+ }
438
442
  return out
439
443
  }
440
444
 
441
- function taskContaining(store, insightId) {
445
+ function taskContaining(store, insightId, taskVisible = null) {
442
446
  for (const t of store.getTasks() || []) {
447
+ if (taskVisible && !taskVisible(t)) continue
443
448
  if ((t.insights || []).some((i) => i.id === insightId)) return t
444
449
  }
445
450
  return null
@@ -666,26 +671,14 @@ export class GlobalStore {
666
671
  }
667
672
  try {
668
673
  const rawDisk = readJsonFile(this.file, null)
669
- const disk = isRecord(rawDisk) && Array.isArray(rawDisk.items) ? rawDisk : null
670
- if (disk) {
671
- const byId = new Map()
672
- for (const it of disk.items) if (it?.id) byId.set(it.id, it)
673
- for (const it of this.doc.items) {
674
- if (!it?.id) continue
675
- if (this._deletedIds.has(it.id)) {
676
- byId.delete(it.id)
677
- continue
678
- }
679
- const prev = byId.get(it.id)
680
- if (!prev) {
681
- // 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
682
- if (this._createdIds.has(it.id)) byId.set(it.id, it)
683
- continue
684
- }
685
- if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
686
- }
687
- for (const id of this._deletedIds) byId.delete(id)
688
- this.doc.items = [...byId.values()]
674
+ const merged = mergeById({
675
+ diskItems: isRecord(rawDisk) && Array.isArray(rawDisk.items) ? rawDisk.items : null,
676
+ localItems: this.doc.items,
677
+ deletedIds: this._deletedIds,
678
+ createdIds: this._createdIds,
679
+ })
680
+ if (merged) {
681
+ this.doc.items = merged
689
682
  } else {
690
683
  // 文件缺失/不可读/损坏(readJsonFile 已把损坏件备份)时,不能把"空 doc"当成
691
684
  // "对端把所有条目都删了":那会把整库旧条目静默清掉。保留内存里的完整副本重写。
@@ -718,7 +711,7 @@ export class GlobalStore {
718
711
  * 模型不该为了改一条记忆先搞清它在哪一层;scope 用条目自己声明的。
719
712
  * @returns {{scope: string, item: object, taskId?: string}|null}
720
713
  */
721
- export function findInsightAnywhere({ store, globalStore } = {}, id) {
714
+ export function findInsightAnywhere({ store, globalStore, taskVisible = null } = {}, id) {
722
715
  if (!id) return null
723
716
  if (globalStore && typeof globalStore.items === 'function') {
724
717
  const it = globalStore.items().find((i) => i && i.id === id)
@@ -730,6 +723,8 @@ export function findInsightAnywhere({ store, globalStore } = {}, id) {
730
723
  }
731
724
  const tasks = store && typeof store.getTasks === 'function' ? store.getTasks() || [] : []
732
725
  for (const t of tasks) {
726
+ // 任务级条目按任务可见性过滤:别队的私有记忆不能被一个 id 串到(改/删同一条路径)。
727
+ if (taskVisible && !taskVisible(t)) continue
733
728
  const it = (t.insights || []).find((i) => i && i.id === id)
734
729
  if (it) return { scope: it.scope || 'task', item: it, taskId: t.id }
735
730
  }
@@ -820,9 +815,10 @@ export function recordDeleted({ store, globalStore } = {}, entries = []) {
820
815
  * @param {object} o
821
816
  * @param {string} o.idOrQuery - 精确 id,或用于匹配的关键词
822
817
  * @param {number} [o.maxMatches] - 关键词命中上限;超过则**一条都不删**,只回报候选
818
+ * @param {(task: object) => boolean} [o.taskVisible] - 任务级条目的可见性过滤(团队隔离);缺省不过滤
823
819
  * @returns {{ok: boolean, removed?: object[], matches?: object[], tooMany?: boolean, keptIn?: string[]}}
824
820
  */
825
- export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 } = {}) {
821
+ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10, taskVisible = null } = {}) {
826
822
  const query = String(idOrQuery ?? '').trim()
827
823
  if (!query) return { ok: false, removed: [], matches: [] }
828
824
  const at = (home, item, taskId) => ({
@@ -835,6 +831,8 @@ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 }
835
831
  for (const it of (store && typeof store.insightItems === 'function' ? store.insightItems() : []) || []) pools.project.push(at('project', it))
836
832
  for (const it of (globalStore && typeof globalStore.items === 'function' ? globalStore.items() : []) || []) pools.global.push(at('global', it))
837
833
  for (const t of (store && typeof store.getTasks === 'function' ? store.getTasks() : []) || []) {
834
+ // 别队的任务级条目不在删除候选里:按 id / 关键词都不能删到本会话看不见的任务。
835
+ if (taskVisible && !taskVisible(t)) continue
838
836
  for (const it of t.insights || []) pools.task.push(at('task', it, t.id))
839
837
  }
840
838
 
@@ -851,17 +849,14 @@ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 }
851
849
 
852
850
  // 2) 关键词:查询侧覆盖率 ≥ 0.5(与旧经验层同判据)
853
851
  const matches = []
854
- const textOf = (home, id) => {
855
- if (home === 'project') return memoryText((store.insightItems() || []).find((x) => x.id === id))
856
- if (home === 'global') return memoryText((globalStore.items() || []).find((x) => x.id === id))
857
- for (const t of store.getTasks() || []) {
858
- const it = (t.insights || []).find((x) => x.id === id)
859
- if (it) return memoryText(it)
860
- }
861
- return ''
852
+ const textOf = (x) => {
853
+ if (x.home === 'project') return memoryText((store.insightItems() || []).find((it) => it.id === x.id))
854
+ if (x.home === 'global') return memoryText((globalStore.items() || []).find((it) => it.id === x.id))
855
+ const task = store.getTask(x.taskId)
856
+ return memoryText((task?.insights || []).find((it) => it.id === x.id))
862
857
  }
863
858
  for (const list of Object.values(pools)) {
864
- for (const x of list) if (queryCoverage(query, textOf(x.home, x.id)) >= 0.5) matches.push(x)
859
+ for (const x of list) if (queryCoverage(query, textOf(x)) >= 0.5) matches.push(x)
865
860
  }
866
861
  if (matches.length > maxMatches) return { ok: false, tooMany: true, matches, removed: [] }
867
862
  const keptIn = removeEntries({ store, globalStore }, matches)
@@ -916,9 +911,10 @@ function removeEntries({ store, globalStore }, entries) {
916
911
  * global 走 globalStore。`raw.id` 给定时走**就地更新**(忽略 scope 路由:条目留在原 home,
917
912
  * 只覆盖显式给的字段,旧值进 `prev`)。`cosine` 给定时启用向量带:≥ autoMergeCos 且领先第二名
918
913
  * ≥ autoMergeMargin → 自动覆盖;≥ hintCos → 新建但回报近邻 id;都不给就是纯词法行为。
914
+ * `taskVisible(task)` 给定时,按 id 更新与跨任务去重只考虑可见任务(团队隔离);缺省不过滤。
919
915
  * 返回 { ok, action, id, replaced, near, hint }。
920
916
  */
921
- export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null }) {
917
+ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, source = 'agent', nowIso, cosine = null, taskVisible = null }) {
922
918
  if (!isRecord(raw)) return { ok: false, error: '内容必须是对象(不能是 null/数组/字符串)' }
923
919
  const cfg2 = cfg || cfgInsight({})
924
920
  const now = nowIso || new Date().toISOString()
@@ -927,7 +923,7 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
927
923
  return { ok: false, error: `内容疑似包含密钥/token/私钥形态数据(字段: ${secretField}),已拒绝写入` }
928
924
  }
929
925
  if (raw && raw.id) {
930
- const found = findInsightAnywhere({ store, globalStore }, raw.id)
926
+ const found = findInsightAnywhere({ store, globalStore, taskVisible }, raw.id)
931
927
  if (!found) return { ok: false, error: `找不到要更新的条目: ${raw.id}(可能已被删除/提升;用 query_memory 重新确认 id)` }
932
928
  const wasDraft = found.item.draft === true
933
929
  const replaced = applyUpdate(found.item, raw, now)
@@ -962,7 +958,7 @@ export function saveInsight({ store, globalStore, raw, scope, taskId, cfg, sourc
962
958
  // 归档任务 = 已停止续做:写进去的条目在 recall(visibleInsights)里永远不可见,
963
959
  // 必须让调用方先 select_task 解归档,而不是报“Saved”后石沉大海。
964
960
  if (task.archived) return { ok: false, error: `任务已归档: ${taskId}(先 select_task 解归档再写入)` }
965
- return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine)
961
+ return saveTaskInsight(store, globalStore, task, raw, cfg2, now, source, cosine, taskVisible)
966
962
  }
967
963
  return saveProjectInsight(store, globalStore, raw, cfg2, now, source, cosine)
968
964
  }
@@ -1027,7 +1023,7 @@ function buildHint(res, pruned, promoted) {
1027
1023
 
1028
1024
  // ---- scope = task ----
1029
1025
 
1030
- function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine) {
1026
+ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine, taskVisible = null) {
1031
1027
  // 反思产出是**待确认草稿**:只落在当前任务,绝不参与 project/global/跨任务的自动合并或
1032
1028
  // 自动提升,否则一条 LLM 生成的 draft 可以覆盖作者手写的 project 级知识。
1033
1029
  const draftOnly = raw.draft === true || source === 'reflect'
@@ -1072,14 +1068,15 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
1072
1068
  }
1073
1069
  }
1074
1070
  // 3) 跨任务池去重(同一坑只留一份,sourceTaskIds 累积)。非草稿写入不得把正文并进 draft,
1075
- // 否则新知识永远停在待审状态。
1076
- const pool = allTaskInsights(store).filter((it) => it.draft !== true)
1071
+ // 否则新知识永远停在待审状态。池子只收调用者可见的任务:跨队去重会让别队的私有条目
1072
+ // 被这条写入改写(并在 hint 里回显它的 id),团队隔离在这里也要成立。
1073
+ const pool = allTaskInsights(store, taskVisible).filter((it) => it.draft !== true)
1077
1074
  const poolNear = vectorNear(vectorText(base), pool, cosine)
1078
1075
  const poolTarget = autoMergeTarget(poolNear, cfg)
1079
1076
  if (poolTarget) {
1080
1077
  const { replaced } = mergeInto(poolTarget.item, base, cfg, now)
1081
1078
  store.markTasksDirty()
1082
- const holder = taskContaining(store, poolTarget.item.id)
1079
+ const holder = taskContaining(store, poolTarget.item.id, taskVisible)
1083
1080
  if (holder) {
1084
1081
  const promoted = promoteAllTasksToProject(store, globalStore, cfg, now)
1085
1082
  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} 条` : ''}` }
@@ -1088,7 +1085,7 @@ function saveTaskInsight(store, globalStore, task, raw, cfg, now, source, cosine
1088
1085
  const hit = findBestOverlapMatch(text, pool)
1089
1086
  if (hit && hit.score >= cfg.dedupOverlap) {
1090
1087
  const { replaced } = mergeInto(hit.item, base, cfg, now)
1091
- const holder = taskContaining(store, hit.item.id)
1088
+ const holder = taskContaining(store, hit.item.id, taskVisible)
1092
1089
  if (holder) {
1093
1090
  store.markTasksDirty()
1094
1091
  const holderId = holder.id
@@ -2,7 +2,7 @@
2
2
  * 宿主团队任务(`task-<n>`)→ 本地记忆任务键的唯一映射。
3
3
  *
4
4
  * 为什么需要这一层:任务级记忆(`save_lesson` 的 `scope: 'task'`)挂在 `tasks.json` 某条任务
5
- * 记录的 `insights[]` 上,只有**会话绑定到该任务**时,`save_lesson` / `recall` / 注入才看得见它;
5
+ * 记录的 `insights[]` 上,只有**会话绑定到该任务、或本次调用显式传 `task_id`** 时才看得见它;
6
6
  * 而绑定原本只认本地 `tsk_…` 任务。团队模式下 lead 与队友是两个会话,它们唯一的公共任务身份
7
7
  * 是宿主的团队任务板(`TeamTaskId` 形如 `task-<n>`)。不做映射,lead 写在任务上的经验队友就
8
8
  * 看不到,只能 promote 到 project —— 一个任务的经验被抬成全项目知识,作用域丢失。
@@ -12,7 +12,8 @@
12
12
  * 记录是**记忆挂载点**:镜像宿主的 status / owner / writeScopes(只做展示与提示),
13
13
  * 但不吸收某个成员的步骤/自维护时刻(那是单个 agent 的清单,见 taskbridge 的 todo/write 分支);
14
14
  * 冲突告警由宿主的视图现算,不落盘(快照里没有它,存下来只会过期)。
15
- * 它也不进 taskbridge 的自动建档路径(子代理仍不建档,绑定只能由显式 `select_task` 建立)。
15
+ * 它也不进 taskbridge 的自动建档路径(子代理仍不建档;绑定只能由显式 `select_task` 建立,
16
+ * 而锚点另有"任务级 `save_lesson` 懒建"这一个入口)。
16
17
  */
17
18
  import { hash8 } from '../util/hash.js'
18
19
 
@@ -110,7 +111,7 @@ function teamFieldsOf(view) {
110
111
  /**
111
112
  * 把工具参数里的任务引用归一成本地记忆任务 id:本地 id 原样返回;宿主团队 id(`task-<n>`)
112
113
  * 如果已经有锚点,返回 `team:task-<n>`;没有锚点则原样返回,由调用方按"找不到"给出可执行的错误。
113
- * 只做映射,不创建锚点 —— 创建需要宿主视图,入口仍是 `select_task`。
114
+ * 只做映射,不创建锚点 —— 创建需要宿主视图,入口是 `select_task` 或任务级 `save_lesson`。
114
115
  * @param {object} store - 项目 store。
115
116
  * @param {unknown} taskId - 工具参数里的任务 id。
116
117
  * @param {string|null} teamId - 调用者所属团队树(`teamIdOf`);团队 id 缺省时不做映射。
@@ -124,6 +125,61 @@ export function memoryTaskIdFor(store, taskId, teamId) {
124
125
  return store.getTask(anchor) ? anchor : taskId
125
126
  }
126
127
 
128
+ /**
129
+ * 这条本地记录是不是**别的团队**的锚点。
130
+ *
131
+ * 团队锚点自带 `teamId`(团队树根会话 id)。显式传原始锚点 id(`team:<root>:task-<n>`,
132
+ * 也就是 `select_task` 回给模型的那个"记忆任务 id")时,必须和调用者所在团队一致——
133
+ * 否则同一项目里两个团队的私有任务记忆会被一个猜到的 id 串读。本地任务(无 `teamId`)恒可见。
134
+ * @param {object} record - 本地任务记录(可能不是团队锚点)。
135
+ * @param {string|null} teamId - 调用者所属团队树;拿不到时团队锚点按不可见处理。
136
+ * @returns {boolean} true = 可以访问。
137
+ */
138
+ export function teamAnchorVisible(record, teamId) {
139
+ if (!record || !record.teamId) return true
140
+ return teamId != null && record.teamId === teamId
141
+ }
142
+
143
+ /**
144
+ * 任务记录对调用者是否可用:本地任务恒可见;团队锚点只对所属团队树可见。
145
+ * 拿不到团队树时团队锚点按不可见处理(fail-closed)——访问判定宁可报"找不到",
146
+ * 也不能让一个猜到的 id / 标题串到别的团队的私有记忆。
147
+ * @param {object} record - 本地任务记录。
148
+ * @param {object} exec - 工具执行上下文或命令调用(需要 `agent`)。
149
+ * @returns {boolean}
150
+ */
151
+ export function taskVisibleTo(record, exec) {
152
+ return teamAnchorVisible(record, teamIdOf(exec))
153
+ }
154
+
155
+ /**
156
+ * 生成"这条任务对该会话是否可见"的判定函数:团队树只解析一次,适合在任务池 / 任务列表
157
+ * 的循环里反复判定(每次 `taskVisibleTo` 都会重新探测 subagents 服务)。
158
+ * @param {object} exec - 工具执行上下文或命令调用(需要 `agent`)。
159
+ * @returns {(record: object) => boolean}
160
+ */
161
+ export function taskVisibility(exec) {
162
+ const teamId = teamIdOf(exec)
163
+ return (record) => teamAnchorVisible(record, teamId)
164
+ }
165
+
166
+ /**
167
+ * 已落盘团队锚点的宿主复核:只有宿主**明确**说"没有这个任务"才算失效;拿不到宿主
168
+ * (`unavailable` / `no-caller` / RPC 失败)是离线降级,不能据此把已有记忆判死。
169
+ * 用于显式原始锚点、会话绑定这两条不经过宿主视图解析的路径。
170
+ * @param {object} exec - 工具执行上下文。
171
+ * @param {object} record - 本地任务记录(可带 `teamTaskId`)。
172
+ * @returns {{ok: true, degraded?: string} | {ok: false, reason: 'not-found'|'error', error?: string}}
173
+ */
174
+ export function recheckTeamAnchor(exec, record) {
175
+ if (!record || !record.teamTaskId) return { ok: true }
176
+ const resolved = resolveTeamTask(exec, record.teamTaskId)
177
+ if (resolved.ok) return { ok: true }
178
+ if (resolved.reason === 'not-found') return { ok: false, reason: 'not-found' }
179
+ if (resolved.reason === 'error') return { ok: false, reason: 'error', error: resolved.error }
180
+ return { ok: true, degraded: resolved.reason }
181
+ }
182
+
127
183
  /**
128
184
  * 团队任务对应的本地记忆任务记录:已有就复用,没有就按宿主视图懒建一条。
129
185
  *
package/src/store.js CHANGED
@@ -7,6 +7,7 @@ import { debugPersistence } from './util/persist.js'
7
7
  import { trackDirty, untrackDirty } from './util/flush.js'
8
8
  import { backfillDerivedTriggers } from './readiness.js'
9
9
  import { isRecord, isoMs, newerIso } from './util/value.js'
10
+ import { mergeById } from './util/merge-by-id.js'
10
11
 
11
12
  const FORMAT_FILE = 'format.json'
12
13
  const INDEX_FILE = 'index.json'
@@ -19,6 +20,12 @@ const INSIGHTS_FILE = 'insights.json'
19
20
  const SHARDS_DIR = 'shards'
20
21
  /** ≤0.5.10 的 TS 增强结果缓存目录;0.5.11 起废弃并自愈清理。 */
21
22
  const LEGACY_TYPE_CACHE_DIR = 'type-cache'
23
+ /**
24
+ * 空团队锚点的回收期。团队锚点镜像宿主任务,但"空壳"(没有任何任务级记忆)只是写入被
25
+ * 去重/提升后留下的残迹:宿主的删除事件不一定能到达每个进程(lead 离线、团队插件卸载),
26
+ * 超过这个时间、没有绑定、也没有记忆,就回收;有记忆的锚点一律保留(那是知识,不是镜像垃圾)。
27
+ */
28
+ const STALE_TEAM_ANCHOR_MS = 30 * 24 * 60 * 60 * 1000
22
29
 
23
30
  const storeCache = new Map()
24
31
  /**
@@ -300,24 +307,17 @@ function mergeTaskFileState(a, b) {
300
307
  * @returns {object[]}
301
308
  */
302
309
  function mergeTaskInsights(local, disk, base) {
303
- const merged = new Map()
304
- for (const ins of Array.isArray(disk?.insights) ? disk.insights : []) {
305
- if (ins?.id) merged.set(ins.id, ins)
306
- }
307
- const localById = new Map()
308
- for (const ins of Array.isArray(local?.insights) ? local.insights : []) {
309
- if (ins?.id) localById.set(ins.id, ins)
310
- }
311
- for (const id of base) if (!localById.has(id)) merged.delete(id)
312
- for (const [id, ins] of localById) {
313
- const prev = merged.get(id)
314
- if (!prev) {
315
- if (!base.has(id)) merged.set(id, ins)
316
- continue
317
- }
318
- if (newerIso(ins.updatedAt, prev.updatedAt) >= 0) merged.set(id, ins)
319
- }
320
- return [...merged.values()]
310
+ const localItems = Array.isArray(local?.insights) ? local.insights : []
311
+ // 三方判断折成两份 id 集合交给 mergeById:基线有、本地没有 = 本地删了(墓碑);
312
+ // 本地有、基线没有 = 本次新建(磁盘缺失时允许补写);两边都有时按 updatedAt 取新。
313
+ const localIds = new Set(localItems.map((it) => it?.id).filter(Boolean))
314
+ const baseIds = base || new Set()
315
+ return mergeById({
316
+ diskItems: Array.isArray(disk?.insights) ? disk.insights : [],
317
+ localItems,
318
+ deletedIds: new Set([...baseIds].filter((id) => !localIds.has(id))),
319
+ createdIds: new Set([...localIds].filter((id) => !baseIds.has(id))),
320
+ }) || []
321
321
  }
322
322
 
323
323
  /**
@@ -491,6 +491,8 @@ export class ProjectMemoryStore {
491
491
  */
492
492
  this._createdInsightIds = new Set()
493
493
  this._createdTaskIds = new Set()
494
+ /** 待回收的过期空团队锚点:只在写盘合并后确认"另一进程也没写过"才移除(见 _pruneStaleTeamAnchors)。 */
495
+ this._staleAnchorIds = new Set()
494
496
  /** 上一次 save 是否真的落到盘上(锁竞争/权限失败时为 false)。 */
495
497
  this.lastSaveOk = true
496
498
  /** `shards/` 的 `.tmp` 清扫节流:NTFS 上 readdir(数千分片) 不便宜,不能每次 save 都扫。 */
@@ -1640,25 +1642,14 @@ export class ProjectMemoryStore {
1640
1642
  for (const id of this._baseInsightIds) if (!current.has(id)) this._deletedInsightIds.add(id)
1641
1643
  for (const id of current) this._deletedInsightIds.delete(id)
1642
1644
  const disk = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
1643
- if (isRecord(disk) && Array.isArray(disk.items)) {
1644
- const byId = new Map()
1645
- for (const it of disk.items) if (isRecord(it) && it.id) byId.set(it.id, it)
1646
- for (const it of this.insights.items) {
1647
- if (!isRecord(it) || !it.id) continue
1648
- if (this._deletedInsightIds.has(it.id)) {
1649
- byId.delete(it.id)
1650
- continue
1651
- }
1652
- const prev = byId.get(it.id)
1653
- if (!prev) {
1654
- // 磁盘没有:本进程新建的才补写;否则是**对方删了**,丢掉内存里的旧副本。
1655
- if (this._createdInsightIds.has(it.id)) byId.set(it.id, it)
1656
- continue
1657
- }
1658
- if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
1659
- }
1660
- for (const id of this._deletedInsightIds) byId.delete(id)
1661
- this.insights = { ...this.insights, items: [...byId.values()] }
1645
+ const merged = mergeById({
1646
+ diskItems: isRecord(disk) && Array.isArray(disk.items) ? disk.items : null,
1647
+ localItems: this.insights.items,
1648
+ deletedIds: this._deletedInsightIds,
1649
+ createdIds: this._createdInsightIds,
1650
+ })
1651
+ if (merged) {
1652
+ this.insights = { ...this.insights, items: merged }
1662
1653
  this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
1663
1654
  this._auxVersion++
1664
1655
  }
@@ -1674,6 +1665,19 @@ export class ProjectMemoryStore {
1674
1665
  continue
1675
1666
  }
1676
1667
  const prev = byId.get(t.id)
1668
+ if (this._staleAnchorIds.has(t.id)) {
1669
+ this._staleAnchorIds.delete(t.id)
1670
+ // 按**合并后**的条目决定:另一进程可能刚给这条锚点写了记忆,不能跟着空壳一起删。
1671
+ const mergedInsights = prev
1672
+ ? mergeTaskInsights(t, prev, this._baseTaskInsightIds.get(t.id) || new Set())
1673
+ : (Array.isArray(t.insights) ? t.insights : [])
1674
+ if (mergedInsights.length === 0) {
1675
+ byId.delete(t.id)
1676
+ this._deletedTaskIds.add(t.id)
1677
+ this._createdTaskIds.delete(t.id)
1678
+ continue
1679
+ }
1680
+ }
1677
1681
  if (!prev) {
1678
1682
  // 同 insights:磁盘缺失 = 对方删了,只有本进程新建的任务才补写。
1679
1683
  if (this._createdTaskIds.has(t.id)) byId.set(t.id, t)
@@ -1702,6 +1706,8 @@ export class ProjectMemoryStore {
1702
1706
  }
1703
1707
  // `removeTask` 已把它从内存数组移除,上面循环看不到;不在这里剔除会在同一次 save 里被写回。
1704
1708
  for (const id of this._deletedTaskIds) byId.delete(id)
1709
+ // 不在本地列表里的候选(已被删除/迁移)不再跟踪;下一轮 prune 会重新登记。
1710
+ this._staleAnchorIds.clear()
1705
1711
  this.tasks = [...byId.values()]
1706
1712
  this._auxVersion++
1707
1713
  }
@@ -1997,19 +2003,51 @@ export class ProjectMemoryStore {
1997
2003
  const fileCount = Object.keys(this.files).length
1998
2004
  const maxTasks = Math.min(100, Math.max(5, Math.floor(fileCount / 20)))
1999
2005
  const bound = new Set(Object.values(this.binding || {}))
2000
- const nonArchived = this.tasks.filter((t) => !t.archived && !bound.has(t.id))
2001
- if (nonArchived.length <= maxTasks) return 0
2006
+ // 团队锚点是宿主任务的镜像,生命周期由宿主(team/task 快照)管:本地容量 GC 不该把它归档,
2007
+ // 否则"按 id 直读、从不绑定"的锚点会在任务一多时静默失效,把绑定要求从后门放回来。
2008
+ // 空壳锚点另有过期回收(_pruneStaleTeamAnchors),不靠容量兜底。
2009
+ const nonArchived = this.tasks.filter((t) => !t.archived && !bound.has(t.id) && !t.teamTaskId)
2002
2010
  const ts = (t) => new Date(t.lastActiveAt || t.updatedAt || t.createdAt || 0).getTime()
2003
- const sorted = [...nonArchived].sort((a, b) => ts(a) - ts(b))
2004
- const toArchive = sorted.slice(0, nonArchived.length - maxTasks)
2011
+ const toArchive = nonArchived.length > maxTasks
2012
+ ? [...nonArchived].sort((a, b) => ts(a) - ts(b)).slice(0, nonArchived.length - maxTasks)
2013
+ : []
2005
2014
  for (const task of toArchive) {
2006
2015
  task.archived = true
2007
2016
  this._dirtyTasks = true
2008
2017
  }
2009
2018
  if (toArchive.length) this._auxVersion++
2019
+ this._pruneStaleTeamAnchors(bound)
2010
2020
  return toArchive.length
2011
2021
  }
2012
2022
 
2023
+ /**
2024
+ * 登记过期空团队锚点,等写盘合并时再回收。团队锚点镜像宿主任务,但没有任何任务级记忆的
2025
+ * 锚点只是写入被去重/提升后留下的残迹;宿主的删除事件不一定能到达每个进程(lead 离线、
2026
+ * 团队插件卸载、团队结束),没有本地回收就会永久留在 tasks.json 和面板里。
2027
+ *
2028
+ * 这里**只登记不删**:本地内存里的空不等于磁盘上也没人写过——另一进程可能刚给这条锚点
2029
+ * 存了记忆。真正移除在 `_mergeAuxFromDisk` 里按合并后的条目决定,避免把别人的写入一起删掉。
2030
+ * 有记忆、刚活动过、仍有会话绑定的锚点都不登记。
2031
+ * @param {Set<string>} bound - 仍有会话绑定的任务 id。
2032
+ * @returns {number} 本轮新登记的条数
2033
+ */
2034
+ _pruneStaleTeamAnchors(bound) {
2035
+ const now = Date.now()
2036
+ const stale = (t) => now - new Date(t.lastActiveAt || t.updatedAt || t.createdAt || 0).getTime() > STALE_TEAM_ANCHOR_MS
2037
+ let added = 0
2038
+ for (const t of this.tasks) {
2039
+ if (!t.teamTaskId || bound.has(t.id) || !stale(t)) continue
2040
+ // 形状异常(insights 不是数组)按"有内容"处理:宁可少回收,也不能把看不懂的数据删掉。
2041
+ if (!Array.isArray(t.insights) || t.insights.length) continue
2042
+ if (this._staleAnchorIds.has(t.id)) continue
2043
+ this._staleAnchorIds.add(t.id)
2044
+ added++
2045
+ }
2046
+ // 没有别的脏数据时 save() 会早退,合并逻辑就跑不到:标记一次脏,让这次 commit 真正落盘并回收。
2047
+ if (added) this._dirtyTasks = true
2048
+ return added
2049
+ }
2050
+
2013
2051
  /**
2014
2052
  * @param {(store: ProjectMemoryStore) => any} fn 变更函数
2015
2053
  * @param {{save?: boolean}} [options] save=false 时只标脏,由调用方在回合结束统一 flush
@@ -2,6 +2,7 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
5
+ import { taskVisibility } from '../setup/team-task.js'
5
6
  import { forgetVectorRows } from '../vector-index.js'
6
7
 
7
8
  /** 回报用的一行:`ins_xxx《标题》(project)`。标题已在 removeMemory 里截断。 */
@@ -46,7 +47,14 @@ export function forgetTool(config) {
46
47
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
47
48
  let res
48
49
  store.commit((s) => {
49
- res = removeMemory({ store: s, globalStore, idOrQuery: args.id_or_query, maxMatches: cfg.maxForgetMatches })
50
+ res = removeMemory({
51
+ store: s,
52
+ globalStore,
53
+ idOrQuery: args.id_or_query,
54
+ maxMatches: cfg.maxForgetMatches,
55
+ // 按 id / 关键词都不能删到本会话看不见的团队任务记忆(别队的私有条目)。
56
+ taskVisible: taskVisibility(exec),
57
+ })
50
58
  return res
51
59
  })
52
60
  globalStore.commit() // global 侧若被删过才落盘