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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
5
5
  "author": "00080000 <3388065969@qq.com>",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  "url": "https://github.com/00080000/dsh-project-memory.git"
20
20
  },
21
21
  "scripts": {
22
- "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
22
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
23
23
  "eval:injection": "node test/injection-scenarios.test.mjs",
24
24
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
25
25
  "selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
@@ -33,6 +33,7 @@ export function TaskCommandNode({ node }: { node?: any }) {
33
33
  tasks: parsedTasks.tasks,
34
34
  boundTaskId: parsedTasks.boundId,
35
35
  archivedCount: parsedTasks.archived,
36
+ root: parsedTasks.root,
36
37
  })
37
38
  if (isList) taskUIStore.actions.open()
38
39
  }, [text])
@@ -14,7 +14,7 @@ import {
14
14
  } from './icons.ts'
15
15
  import { createTranslate, zh, en } from './locales.ts'
16
16
  import { missingServices, service } from './services.ts'
17
- import { useTaskData, useTaskDataActions, taskDataStore, parseTaskPayloadText, type TaskStep } from './task-data-store.ts'
17
+ import { useTaskData, useTaskDataActions, parseTaskPayloadText, type TaskStep } from './task-data-store.ts'
18
18
  import { useTaskUI, useTaskUIActions, PANEL_VIEWS } from './task-ui-store.ts'
19
19
  import { MiniBar, TaskCard } from './TaskComponents.tsx'
20
20
  import { MemoryView, type InsightScope } from './MemoryView.tsx'
@@ -102,7 +102,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
102
102
  const applyPayload = (text?: string): boolean => {
103
103
  const parsed = parseTaskPayloadText(text)
104
104
  if (!parsed) return false
105
- dataActions.setTasks({ tasks: parsed.tasks, boundTaskId: parsed.boundId, archivedCount: parsed.archived })
105
+ dataActions.setTasks({ tasks: parsed.tasks, boundTaskId: parsed.boundId, archivedCount: parsed.archived, root: parsed.root })
106
106
  setSyncedAt(Date.now())
107
107
  setSyncError(null)
108
108
  return true
@@ -133,16 +133,22 @@ function TaskPanelView({ ctx }: { ctx: any }) {
133
133
  return applyPayload(result?.text)
134
134
  }
135
135
 
136
+ /**
137
+ * 只取数据,**不**顺手 switch。
138
+ *
139
+ * 旧实现在这里补一次 `/tasks switch <boundId>`(条件是"新 boundId 与内存里的不同"),
140
+ * 意图是刷新后让宿主 todo 跟随绑定任务。但那是多余的:宿主的 todo 清单是
141
+ * `sessionProjections` 里的 `todos` 单元(由 `todo/write` 事件折叠而来),重启/换标签页
142
+ * 都会从会话日志重建,不需要谁再推一次;而 switch 会 `session.append('todo/write')`,
143
+ * 于是"打开面板/切一次会话"就写一次会话历史(还顺手刷新任务的 lastActiveAt)。
144
+ * 真正的绑定动作都有明确入口:`select_task`、`/tasks switch`、面板卡片的切换按钮,
145
+ * 它们各自会推宿主清单(adoptStepsToSession),不需要巡检式补写。
146
+ */
136
147
  const refresh = async (): Promise<void> => {
137
148
  if (syncing) return
138
149
  setSyncing(true)
139
150
  try {
140
- const prevBoundId = data.boundTaskId
141
151
  await runLine('/tasks')
142
- const newBoundId = taskDataStore.getSnapshot().boundTaskId
143
- if (newBoundId && newBoundId !== prevBoundId) {
144
- await runLine(`/tasks switch ${newBoundId}`)
145
- }
146
152
  } finally {
147
153
  setSyncing(false)
148
154
  }
@@ -4,6 +4,7 @@
4
4
  * - 无 UI 状态,无 localStorage,纯内存 + BroadcastChannel 同步
5
5
  */
6
6
  import { useSyncExternalStore } from 'react'
7
+ import { broadcastAppliesTo, payloadRoot } from './task-scope.js'
7
8
 
8
9
  export interface TaskStep {
9
10
  content: string
@@ -37,6 +38,8 @@ export interface TaskPayload {
37
38
  tasks: Task[]
38
39
  boundId: string | null
39
40
  archived: number
41
+ /** 项目根。旧宿主没有这个键(null):跨标签页同步在未知根时退回"只按会话"处理。 */
42
+ root?: string | null
40
43
  }
41
44
 
42
45
  export function parseTaskPayloadText(text?: string | null): TaskPayload | null {
@@ -52,7 +55,12 @@ export function parseTaskPayloadText(text?: string | null): TaskPayload | null {
52
55
  try {
53
56
  const data = JSON.parse(jsonBlock)
54
57
  if (!Array.isArray(data.tasks)) return null
55
- return { tasks: data.tasks, boundId: data.boundId ?? null, archived: data.archived ?? 0 }
58
+ return {
59
+ tasks: data.tasks,
60
+ boundId: data.boundId ?? null,
61
+ archived: data.archived ?? 0,
62
+ root: payloadRoot(data.root),
63
+ }
56
64
  } catch {
57
65
  return null
58
66
  }
@@ -62,6 +70,8 @@ interface TaskDataState {
62
70
  tasks: Task[]
63
71
  boundTaskId: string | null
64
72
  archivedCount: number
73
+ /** 这份数据的项目根:广播按它做作用域,避免多项目标签页互相覆盖。 */
74
+ root: string | null
65
75
  lastUpdate: number
66
76
  }
67
77
 
@@ -71,6 +81,7 @@ let dataState: TaskDataState = {
71
81
  tasks: [],
72
82
  boundTaskId: null,
73
83
  archivedCount: 0,
84
+ root: null,
74
85
  lastUpdate: 0,
75
86
  }
76
87
 
@@ -84,31 +95,36 @@ function setDataState(next: TaskDataState | ((prev: TaskDataState) => TaskDataSt
84
95
  tasks: Array.isArray(patch?.tasks) ? patch.tasks : [],
85
96
  boundTaskId: patch?.boundTaskId ?? null,
86
97
  archivedCount: typeof patch?.archivedCount === 'number' ? patch.archivedCount : 0,
98
+ root: payloadRoot(patch?.root),
87
99
  lastUpdate: typeof patch?.lastUpdate === 'number' ? patch.lastUpdate : 0,
88
100
  }
89
101
  for (const listener of dataListeners) listener()
90
102
  }
91
103
 
92
- function broadcastDataUpdate(tasks: Task[], archivedCount: number): void {
104
+ function broadcastDataUpdate(tasks: Task[], archivedCount: number, root: string | null): void {
93
105
  if (!SYNC_CHANNEL) return
94
106
  SYNC_CHANNEL.postMessage({
95
107
  type: 'PROJECT_TASKS_UPDATED',
96
- payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount },
108
+ payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount, root },
97
109
  })
98
110
  }
99
111
 
100
112
  if (SYNC_CHANNEL) {
101
113
  SYNC_CHANNEL.onmessage = (event) => {
102
114
  const msg = event.data
103
- if (msg?.type === 'PROJECT_TASKS_UPDATED' && msg.payload) {
104
- const { tasks, archivedCount } = msg.payload
105
- setDataState(prev => ({
106
- ...prev,
107
- tasks: Array.isArray(tasks) ? tasks : [],
108
- archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
109
- lastUpdate: Date.now(),
110
- }))
111
- }
115
+ if (msg?.type !== 'PROJECT_TASKS_UPDATED' || !msg.payload) return
116
+ const { tasks, archivedCount, root } = msg.payload
117
+ // 频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个),所以**必须**按项目根过滤:
118
+ // 否则在 A 项目点一下刷新,B 项目的标签页面板就被贴上 A 的任务列表(而它还保留自己的
119
+ // boundTaskId,看起来像"绑定丢了")。两侧都已知根且不同 → 丢弃;本页还不知道根(还没
120
+ // 同步过)→ 也丢弃,让它自己那一次 /tasks 决定归属,不先借别人的数据。
121
+ if (!broadcastAppliesTo(dataState.root, root)) return
122
+ setDataState(prev => ({
123
+ ...prev,
124
+ tasks: Array.isArray(tasks) ? tasks : [],
125
+ archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
126
+ lastUpdate: Date.now(),
127
+ }))
112
128
  }
113
129
  }
114
130
 
@@ -121,22 +137,25 @@ export const taskDataStore = {
121
137
  return dataState
122
138
  },
123
139
  actions: {
124
- setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number }): void {
140
+ setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number; root?: string | null }): void {
125
141
  const nextTasks = payload.tasks || []
126
142
  const nextArchived = payload.archivedCount ?? 0
143
+ const nextRoot = payloadRoot(payload.root)
127
144
  setDataState({
128
145
  tasks: nextTasks,
129
146
  boundTaskId: payload.boundTaskId ?? null,
130
147
  archivedCount: nextArchived,
148
+ root: nextRoot,
131
149
  lastUpdate: Date.now(),
132
150
  })
133
- broadcastDataUpdate(nextTasks, nextArchived)
151
+ broadcastDataUpdate(nextTasks, nextArchived, nextRoot)
134
152
  },
135
153
  reset(): void {
136
154
  setDataState({
137
155
  tasks: [],
138
156
  boundTaskId: null,
139
157
  archivedCount: 0,
158
+ root: null,
140
159
  lastUpdate: 0,
141
160
  })
142
161
  },
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 跨标签页任务广播的**项目作用域**判定(纯函数,无 React / 无 BroadcastChannel 依赖)。
3
+ *
4
+ * 为什么需要它:同步频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个
5
+ * `dsh-pm-tasks-data`),而消息体只带任务数组。没有作用域判定时,在 A 项目点一下刷新,
6
+ * B 项目的标签页面板就会被贴上 A 的任务列表——它自己保留着 B 的 `boundTaskId`,
7
+ * 于是表现为"绑定莫名丢了"。频道名不能按项目拆:项目根是数据到达后才知道的,
8
+ * 而 `new BroadcastChannel` 在模块加载期就要定名。
9
+ *
10
+ * 判据刻意**严格**:消息里没有根、或本页还没确定根,都不接受。
11
+ * - 无根:老宿主/老 bundle 的载荷,宁可不同步也不猜;
12
+ * - 本页未知根:它自己那一次 `/tasks` 会决定归属,不先借别人的数据(避免短暂显示错项目)。
13
+ * 两侧都已知且相等时才接受——这正是"同一项目的两个标签页"。
14
+ *
15
+ * @param {string|null|undefined} localRoot - 本页当前数据的项目根(未同步过为 null)
16
+ * @param {unknown} incomingRoot - 广播消息里的项目根
17
+ * @returns {boolean} true = 这条广播属于同一个项目,可以套用
18
+ */
19
+ export function broadcastAppliesTo(localRoot, incomingRoot) {
20
+ if (typeof incomingRoot !== 'string' || incomingRoot === '') return false
21
+ if (typeof localRoot !== 'string' || localRoot === '') return false
22
+ return localRoot === incomingRoot
23
+ }
24
+
25
+ /**
26
+ * 从 `/tasks` 载荷里取项目根(旧宿主没有该键)。
27
+ * @param {unknown} value - `payload.root`
28
+ * @returns {string|null} 非空字符串才算根
29
+ */
30
+ export function payloadRoot(value) {
31
+ return typeof value === 'string' && value !== '' ? value : null
32
+ }
@@ -4,7 +4,7 @@
4
4
  // (命令 handler:store.commit + gs.commit)统一负责,便于单测。
5
5
  import { ProjectMemoryStore } from '../store.js'
6
6
  import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
7
- import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, INSIGHT_KINDS } from '../insight-store.js'
7
+ import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, INSIGHT_KINDS } from '../insight-store.js'
8
8
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
10
10
 
@@ -150,6 +150,8 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
150
150
  return { ok: true, text: `已审核:${insight.title}` }
151
151
  }
152
152
  if (act === 'delete') {
153
+ // 面板删除与 forget 同一套留痕:真删,但最近 5 条可在同目录 deleted.json 里找回来。
154
+ recordDeleted({ store, globalStore: gs }, [{ ...insight, home: 'task', taskId: task.id }])
153
155
  task.insights = (task.insights || []).filter((i) => i.id !== id)
154
156
  store.markTasksDirty()
155
157
  return { ok: true, text: `已删除任务级条目 ${id}` }
@@ -191,6 +193,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
191
193
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
192
194
  }
193
195
  if (act === 'delete') {
196
+ recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'project' }])
194
197
  items.splice(idx, 1)
195
198
  store.replaceInsightItems(items)
196
199
  return { ok: true, text: `已删除 project 条目 ${id}` }
@@ -243,6 +246,7 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
243
246
  return { ok: true, text: `已${act === 'archive' ? '归档' : '恢复'}` }
244
247
  }
245
248
  if (act === 'delete') {
249
+ recordDeleted({ store, globalStore: gs }, [{ ...ins, home: 'global' }])
246
250
  items.splice(idx, 1)
247
251
  gs.markDirty()
248
252
  return { ok: true, text: `已删除 global 条目 ${id}` }
@@ -36,8 +36,9 @@ function withTaskSnapshot(config, cwd, sid, store, note) {
36
36
  const active = tasks.filter((t) => !t.archived)
37
37
  const archived = tasks.length - active.length
38
38
  const boundId = sid ? store.getBoundTaskId(sid) : null
39
- const human = `项目 ${projectRootFor(cwd)}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
40
- const payload = buildTaskPayload(active, boundId, archived)
39
+ const root = projectRootFor(cwd)
40
+ const human = `项目 ${root}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
41
+ const payload = buildTaskPayload(active, boundId, archived, root)
41
42
  return { kind: 'success', text: fencedJson(human, payload) }
42
43
  }
43
44
 
@@ -7,7 +7,7 @@ import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
7
7
  import { fencedJson, invocationContext } from './invocation.js'
8
8
  import { stepContent, stepProgress, stepStatus, timeAgo } from '../util/task-view.js'
9
9
 
10
- export function buildTaskPayload(tasks, boundId, archived) {
10
+ export function buildTaskPayload(tasks, boundId, archived, root = null) {
11
11
  return JSON.stringify({
12
12
  tasks: tasks.map((t) => ({
13
13
  id: t.id,
@@ -21,6 +21,9 @@ export function buildTaskPayload(tasks, boundId, archived) {
21
21
  })),
22
22
  boundId: boundId || null,
23
23
  archived,
24
+ // 项目根:客户端用它把跨标签页广播限定在同一个项目里(不同项目共用一个浏览器时,
25
+ // 没有这个键就会把 A 项目的任务贴到 B 项目的面板上)。
26
+ root: root || null,
24
27
  })
25
28
  }
26
29
 
@@ -56,7 +59,7 @@ export function renderTaskSnapshot(config, cwd, sid) {
56
59
  }
57
60
  lines.push('', '续接/改名/归档:直接告诉模型(list_tasks / select_task / archive_task)。')
58
61
  const humanText = lines.join('\n')
59
- const payload = buildTaskPayload(active, boundId, archived)
62
+ const payload = buildTaskPayload(active, boundId, archived, root)
60
63
  return { kind: 'success', text: fencedJson(humanText, payload) }
61
64
  }
62
65
 
@@ -558,6 +558,67 @@ function queryCoverage(query, text) {
558
558
  return hit / q.length
559
559
  }
560
560
 
561
+ /**
562
+ * 最近删除的保留条数。
563
+ *
564
+ * 删除仍然是**真删**(工具描述里的 "no undo" 不变):这里只是把刚被删掉的条目按层
565
+ * 追加进同目录的 {@link DELETED_FILE},滚动保留最近 5 条,供人/模型事后自己找回来。
566
+ *
567
+ * 为什么是 5:够覆盖"刚删错一条/一批"的窗口,又不足以在盘上长期留一份正文副本;
568
+ * 为什么按层分文件:project/task 条目落在项目 store 目录、global 落在 global 文件目录,
569
+ * 与各自真相源同源,删库/搬家时不会对不上。
570
+ */
571
+ export const DELETED_KEEP = 5
572
+
573
+ /** 删除留痕文件名(与 store 同目录)。 */
574
+ export const DELETED_FILE = 'deleted.json'
575
+
576
+ /** 某层 store 目录下的留痕文件绝对路径。 */
577
+ export function deletedFilePath(dir) {
578
+ return dir ? path.join(dir, DELETED_FILE) : null
579
+ }
580
+
581
+ /**
582
+ * 把即将被删的条目写进各自层的留痕文件(滚动保留最近 {@link DELETED_KEEP} 条)。
583
+ *
584
+ * 契约:**永不抛、永不挡删除**。留痕是旁路,写失败只丢留痕,不允许因此让删除失败或半途而废。
585
+ * @param {{store?: object, globalStore?: object}} stores - 两个 store;按条目的 `home` 选目录
586
+ * @param {Array<object>} entries - 完整条目副本,须带 `home`(`global` 走 global 目录,其余走 store 目录)与可选 `taskId`
587
+ * @returns {string[]} 实际写入的留痕文件路径(去重)
588
+ */
589
+ export function recordDeleted({ store, globalStore } = {}, entries = []) {
590
+ const now = new Date().toISOString()
591
+ const byDir = new Map()
592
+ for (const e of entries) {
593
+ if (!e || !e.id) continue
594
+ const dir = e.home === 'global'
595
+ ? (globalStore && globalStore.file ? path.dirname(globalStore.file) : null)
596
+ : (store ? store.dir : null)
597
+ if (!dir) continue
598
+ const batch = byDir.get(dir) || []
599
+ batch.push({ ...e, deletedAt: now })
600
+ byDir.set(dir, batch)
601
+ }
602
+ const written = []
603
+ for (const [dir, batch] of byDir) {
604
+ const file = deletedFilePath(dir)
605
+ let prev = []
606
+ try {
607
+ const doc = JSON.parse(readFileSync(file, 'utf8'))
608
+ if (doc && Array.isArray(doc.items)) prev = doc.items
609
+ } catch {
610
+ // 首次删除(文件不存在)或留痕文件损坏:从空开始,不因旁路数据带崩删除。
611
+ }
612
+ try {
613
+ writeJsonAtomic(file, { version: 1, updatedAt: now, items: [...batch, ...prev].slice(0, DELETED_KEEP) })
614
+ written.push(file)
615
+ } catch {
616
+ // 写不进去(只读盘 / 权限)就放弃留痕:删除本身照常进行。
617
+ }
618
+ }
619
+ return [...new Set(written)]
620
+ }
621
+
561
622
  /**
562
623
  * 全层删除:task 内嵌 / project / global。一套判据、一次调用。
563
624
  *
@@ -566,7 +627,7 @@ function queryCoverage(query, text) {
566
627
  * @param {object} o
567
628
  * @param {string} o.idOrQuery - 精确 id,或用于匹配的关键词
568
629
  * @param {number} [o.maxMatches] - 关键词命中上限;超过则**一条都不删**,只回报候选
569
- * @returns {{ok: boolean, removed?: object[], matches?: object[], tooMany?: boolean}}
630
+ * @returns {{ok: boolean, removed?: object[], matches?: object[], tooMany?: boolean, keptIn?: string[]}}
570
631
  */
571
632
  export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 } = {}) {
572
633
  const query = String(idOrQuery ?? '').trim()
@@ -591,8 +652,8 @@ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 }
591
652
  if (hit) byId.push({ ...hit, home })
592
653
  }
593
654
  if (byId.length) {
594
- removeEntries({ store, globalStore }, byId)
595
- return { ok: true, removed: byId }
655
+ const keptIn = removeEntries({ store, globalStore }, byId)
656
+ return { ok: true, removed: byId, keptIn }
596
657
  }
597
658
 
598
659
  // 2) 关键词:查询侧覆盖率 ≥ 0.5(与旧经验层同判据)
@@ -610,12 +671,30 @@ export function removeMemory({ store, globalStore, idOrQuery, maxMatches = 10 }
610
671
  for (const x of list) if (queryCoverage(query, textOf(x.home, x.id)) >= 0.5) matches.push(x)
611
672
  }
612
673
  if (matches.length > maxMatches) return { ok: false, tooMany: true, matches, removed: [] }
613
- removeEntries({ store, globalStore }, matches)
614
- return { ok: true, removed: matches }
674
+ const keptIn = removeEntries({ store, globalStore }, matches)
675
+ return { ok: true, removed: matches, keptIn }
615
676
  }
616
677
 
617
- /** 按 home 把条目从各自真相源里移除。 */
678
+ /** 按 home 把条目从各自真相源里移除;删除前先把**完整条目**写进留痕文件。 */
618
679
  function removeEntries({ store, globalStore }, entries) {
680
+ // 传进来的 entries 是 at() 的摘要(只有 id/home/title),留痕要的是正文,
681
+ // 所以这里按 id 回真相源取完整对象——顺序在 splice 之前,取不到就跳过留痕(不挡删除)。
682
+ const full = []
683
+ for (const e of entries) {
684
+ if (e.home === 'project') {
685
+ const it = (store.insightItems() || []).find((x) => x.id === e.id)
686
+ if (it) full.push({ ...it, home: 'project' })
687
+ } else if (e.home === 'global') {
688
+ const it = (globalStore.items() || []).find((x) => x.id === e.id)
689
+ if (it) full.push({ ...it, home: 'global' })
690
+ } else if (e.home === 'task') {
691
+ const task = store.getTask(e.taskId)
692
+ const it = (task?.insights || []).find((x) => x.id === e.id)
693
+ if (it) full.push({ ...it, home: 'task', taskId: e.taskId })
694
+ }
695
+ }
696
+ const keptIn = recordDeleted({ store, globalStore }, full)
697
+
619
698
  const projectIds = new Set()
620
699
  const globalIds = new Set()
621
700
  const taskIds = new Map()
@@ -636,6 +715,7 @@ function removeEntries({ store, globalStore }, entries) {
636
715
  task.insights = (task.insights || []).filter((i) => !ids.includes(i.id))
637
716
  store.markTasksDirty()
638
717
  }
718
+ return keptIn
639
719
  }
640
720
 
641
721
  /**
package/src/ops.js CHANGED
@@ -90,8 +90,19 @@ const SHELL_OP_RULES = [
90
90
  [/\b(curl|wget|web_fetch)\b/, 'fetch-web'],
91
91
  ]
92
92
 
93
- /** 会改动文件系统的 shell 动作前缀:只有这些命令的路径才算"写目标"。 */
94
- const SHELL_WRITE_RE = /\b(rm|rmdir|unlink|shred|mv|cp|touch|tee|truncate|mkdir)\b|>>?\s*\S|\bsed\s+-i\b/
93
+ /**
94
+ * 会改动文件系统的 shell 动作:只有这些命令的路径才算"写目标"。
95
+ *
96
+ * 重定向这一支要排除"丢弃输出",否则 `2>/dev/null`、`2>&1`、`>/dev/null` 这些
97
+ * **纯读命令的惯用写法**会被当成写盘:实测 `ls .agents 2>/dev/null | head` 抽出
98
+ * targets=['.agents']、`cat package.json 2>&1` 抽出 ['package.json'] —— 写目标正是
99
+ * `when.writes` 的匹配面,于是"读/列目录"会误触发一条 `writes:['package.json']` 的教训。
100
+ *
101
+ * 规则:`>` / `>>` / `2>` 后面的目标若是 `&`(合并 fd)或 `/dev/null`(丢弃),不算写;
102
+ * `> file`、`2> file`、`1>> file` 仍算写。
103
+ */
104
+ const SHELL_WRITE_RE =
105
+ /\b(rm|rmdir|unlink|shred|mv|cp|touch|tee|truncate|mkdir)\b|(?:^|[^>])[0-9]?>>?\s*(?!&|\/dev\/null(?:\b|$))\S|\bsed\s+-i\b/
95
106
 
96
107
  const WSL_HINT_RE = /\/mnt\/[a-z]\//i
97
108
 
package/src/store.js CHANGED
@@ -979,11 +979,23 @@ export class ProjectMemoryStore {
979
979
  }
980
980
  }
981
981
 
982
- /** 每项目任务数上限随项目体积自适应;超限按 lastActiveAt 归档最旧(只统计非归档)。 */
982
+ /**
983
+ * 每项目任务数上限随项目体积自适应;超限按 lastActiveAt 归档最旧(只统计非归档)。
984
+ *
985
+ * **仍被会话绑定的任务不参与裁剪**(这条是修 bug,不是放宽上限):
986
+ * 绑定 = "这个任务还没结束,某个会话随时会回来接着干"。旧实现按 `lastActiveAt` 一刀切,
987
+ * 一个长期挂着的绑定任务会被更新的任务挤到最旧、被静默归档;会话回来写 todo 时,
988
+ * `taskbridge` 把"归档"按"停止同步"处理(那是归档的文档语义),于是**另建一条新任务**——
989
+ * 同一个会话的历史被静默拆成两条记录,原条目变成归档孤儿。
990
+ * 代价是活跃列表可能比上限多出"绑定任务数"条;这是刻意取舍:上限只是启发式,
991
+ * 而"别把用户正在做的任务从脚底下抽走"是正确性。想真正停掉一个任务,先解绑或显式归档。
992
+ * @returns {number} 本轮归档的条数
993
+ */
983
994
  pruneTasks() {
984
995
  const fileCount = Object.keys(this.files).length
985
996
  const maxTasks = Math.min(100, Math.max(5, Math.floor(fileCount / 20)))
986
- const nonArchived = this.tasks.filter((t) => !t.archived)
997
+ const bound = new Set(Object.values(this.binding || {}))
998
+ const nonArchived = this.tasks.filter((t) => !t.archived && !bound.has(t.id))
987
999
  if (nonArchived.length <= maxTasks) return 0
988
1000
  const ts = (t) => new Date(t.lastActiveAt || t.updatedAt || t.createdAt || 0).getTime()
989
1001
  const sorted = [...nonArchived].sort((a, b) => ts(a) - ts(b))
@@ -1,13 +1,29 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
3
  import { ProjectMemoryStore } from '../store.js'
4
- import { cfgInsight, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
4
+ import { cfgInsight, DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
5
5
 
6
6
  /** 回报用的一行:`ins_xxx《标题》(project)`。标题已在 removeMemory 里截断。 */
7
7
  function line(e) {
8
8
  return `${e.id}《${e.title}》(${e.home})`
9
9
  }
10
10
 
11
+ /**
12
+ * 删除留痕的回报后缀:把留痕文件的**真实路径**直接写进结果。
13
+ *
14
+ * 为什么不只写在工具描述里、而是每次删除都回报:描述是静态文本,说不清项目目录在哪
15
+ * (`memoryDir` 可配、项目根随会话变);而模型要"自己去找"就必须先知道路径。这条不影响
16
+ * 任何判据,只是把地址递到手里。
17
+ * @param {{keptIn?: string[]}} res - removeMemory 的返回
18
+ * @returns {string} 直接拼在删除回报后面的文本(无留痕时为空串)
19
+ */
20
+ function keptHint(res) {
21
+ const files = Array.isArray(res?.keptIn) ? res.keptIn : []
22
+ if (!files.length) return ''
23
+ return `\nLast ${DELETED_KEEP} deleted entries kept for manual recovery (read them to restore, then save again):\n`
24
+ + files.map((f) => `- ${f}`).join('\n')
25
+ }
26
+
11
27
  export function forgetTool(config) {
12
28
  return defineTool({
13
29
  name: 'forget',
@@ -15,7 +31,9 @@ export function forgetTool(config) {
15
31
  'Delete memories by id or by matching keywords — lessons / decisions / procedures and experience notes, ' +
16
32
  'at task / project / global scope alike (one call, no need to know which layer it lives in). Real deletion, no undo. ' +
17
33
  'An exact id deletes that one entry; keywords match on how much of the query the entry covers. ' +
18
- 'A keyword that matches more than the configured cap deletes nothing and lists the candidates instead.',
34
+ 'A keyword that matches more than the configured cap deletes nothing and lists the candidates instead. ' +
35
+ `The ${DELETED_KEEP} most recently deleted entries are kept in that layer's deleted.json next to its store ` +
36
+ '(the path is returned after every deletion) — read it to recover an accidental deletion and save it again.',
19
37
  parameters: {
20
38
  id_or_query: {
21
39
  type: 'string',
@@ -50,7 +68,9 @@ export function forgetTool(config) {
50
68
  return `Matched ${res.matches.length} memories (cap ${cfg.maxForgetMatches}), removed none — narrow the query or delete by id:\n` + head.map((l) => `- ${l}`).join('\n') + more
51
69
  }
52
70
  if (!res || !res.ok || !res.removed.length) return 'No matching memory found.'
53
- return `Removed ${res.removed.length} memory entries:\n` + res.removed.map((e) => `- ${line(e)}`).join('\n')
71
+ return `Removed ${res.removed.length} memory entries:\n`
72
+ + res.removed.map((e) => `- ${line(e)}`).join('\n')
73
+ + keptHint(res)
54
74
  },
55
75
  })
56
76
  }
@@ -1,6 +1,6 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import path from 'node:path'
3
- import { memoryDirName, memoryRootFor, nestedStoreRoots, resolveSafeIndexRoot } from '../util/fs.js'
3
+ import { assertIndexRoot, memoryDirName, memoryRootFor, nestedStoreRoots, resolveSafeIndexRoot } from '../util/fs.js'
4
4
  import { ProjectMemoryStore, storeOverview } from '../store.js'
5
5
  import { expandQuery } from '../llm.js'
6
6
  import { resolveRoute } from '../llm-route.js'
@@ -66,6 +66,11 @@ export function queryMemoryTool(ctx, config) {
66
66
  },
67
67
  async execute(args, exec) {
68
68
  const root = resolveSafeIndexRoot(exec, args.root, config)
69
+ // 读路径也要验根存在。这条不是洁癖:可选的向量层(leanvec)在空 store 上会建
70
+ // `<root>/.dsh-project-memory/vectors.json`,于是传错一个 root(拼写错误/旧路径)就能
71
+ // 在任意可写位置造出目录和空 store,而回报是"No memory matches"——看起来像"这个项目
72
+ // 没有记忆",用户不会意识到自己查错了地方。与 index_repo/watch_repo 同一道护栏。
73
+ assertIndexRoot(root, args.root || root)
69
74
  // 空查询不是"全部":recallItems 会过滤空串,rankEntriesStreaming 随即返回
70
75
  // entries.slice(0, limit)(任意条目、分数 0),task 分支的 includes('') 更是命中所有任务。
71
76
  if (!String(args.query ?? '').trim()) {
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
2
+ import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
3
  import { ProjectMemoryStore, storeOverview } from '../store.js'
4
4
  import { truncate } from '../util/text.js'
5
5
 
@@ -23,6 +23,10 @@ export function statsTool(config) {
23
23
  },
24
24
  async execute(args, exec) {
25
25
  const root = resolveSafeIndexRoot(exec, args.root, config)
26
+ // 读路径也要验根存在:可选的向量层(leanvec)在索引空 store 时会落盘 vectors 缓存,
27
+ // 于是"传错一个 root"就能在任意可写位置造出 `<root>/.dsh-project-memory` —— 而回报
28
+ // 只是"空 store",看起来像"这个项目没有记忆"。与 index_repo/watch_repo 同一道护栏。
29
+ assertIndexRoot(root, args.root || root)
26
30
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
27
31
  const overview = storeOverview(store)
28
32
  const files = Object.entries(store.files).sort((a, b) => String(b[1].indexedAt || '').localeCompare(String(a[1].indexedAt || '')))