@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
@@ -32,6 +32,8 @@ export interface Task {
32
32
  updatedAt: string
33
33
  archived?: boolean
34
34
  insights?: TaskInsight[]
35
+ /** 载荷被截断时的真实总量;正常任务没有这个键。 */
36
+ totals?: { steps: number; files: number; insights: number; completedSteps: number }
35
37
  }
36
38
 
37
39
  export interface TaskPayload {
@@ -72,16 +74,26 @@ interface TaskDataState {
72
74
  archivedCount: number
73
75
  /** 这份数据的项目根:广播按它做作用域,避免多项目标签页互相覆盖。 */
74
76
  root: string | null
77
+ /** 写入这份数据的会话;跨标签页只对同一会话同步 boundTaskId。 */
78
+ sessionId: string | null
79
+ /** 最后应用/产生的广播时间:乱序快照按它丢弃。 */
80
+ lastSyncAt: number
75
81
  lastUpdate: number
76
82
  }
77
83
 
78
- const SYNC_CHANNEL = typeof window !== 'undefined' ? new BroadcastChannel('dsh-pm-tasks-data') : null
84
+ // 不是所有宿主都有 BroadcastChannel(SSR / 老 WebView / 测试替身)。缺它只关闭跨标签页同步,
85
+ // 不能让整个 client 半边在 apply 之前就 ReferenceError。
86
+ const SYNC_CHANNEL = typeof window !== 'undefined' && typeof BroadcastChannel !== 'undefined'
87
+ ? new BroadcastChannel('dsh-pm-tasks-data')
88
+ : null
79
89
 
80
90
  let dataState: TaskDataState = {
81
91
  tasks: [],
82
92
  boundTaskId: null,
83
93
  archivedCount: 0,
84
94
  root: null,
95
+ sessionId: null,
96
+ lastSyncAt: 0,
85
97
  lastUpdate: 0,
86
98
  }
87
99
 
@@ -96,16 +108,32 @@ function setDataState(next: TaskDataState | ((prev: TaskDataState) => TaskDataSt
96
108
  boundTaskId: patch?.boundTaskId ?? null,
97
109
  archivedCount: typeof patch?.archivedCount === 'number' ? patch.archivedCount : 0,
98
110
  root: payloadRoot(patch?.root),
111
+ sessionId: typeof patch?.sessionId === 'string' && patch.sessionId ? patch.sessionId : null,
112
+ lastSyncAt: typeof patch?.lastSyncAt === 'number' ? patch.lastSyncAt : 0,
99
113
  lastUpdate: typeof patch?.lastUpdate === 'number' ? patch.lastUpdate : 0,
100
114
  }
101
115
  for (const listener of dataListeners) listener()
102
116
  }
103
117
 
104
- function broadcastDataUpdate(tasks: Task[], archivedCount: number, root: string | null): void {
118
+ function broadcastDataUpdate(
119
+ tasks: Task[],
120
+ archivedCount: number,
121
+ root: string | null,
122
+ boundTaskId: string | null,
123
+ sessionId: string | null,
124
+ sentAt: number,
125
+ ): void {
105
126
  if (!SYNC_CHANNEL) return
106
127
  SYNC_CHANNEL.postMessage({
107
128
  type: 'PROJECT_TASKS_UPDATED',
108
- payload: { tasks: Array.isArray(tasks) ? tasks : [], archivedCount, root },
129
+ payload: {
130
+ tasks: Array.isArray(tasks) ? tasks : [],
131
+ archivedCount,
132
+ root,
133
+ boundTaskId,
134
+ sessionId,
135
+ sentAt,
136
+ },
109
137
  })
110
138
  }
111
139
 
@@ -113,16 +141,23 @@ if (SYNC_CHANNEL) {
113
141
  SYNC_CHANNEL.onmessage = (event) => {
114
142
  const msg = event.data
115
143
  if (msg?.type !== 'PROJECT_TASKS_UPDATED' || !msg.payload) return
116
- const { tasks, archivedCount, root } = msg.payload
144
+ const { tasks, archivedCount, root, boundTaskId, sessionId, sentAt } = msg.payload
117
145
  // 频道名是固定的(同一浏览器同源的所有 dsh 页面共用一个),所以**必须**按项目根过滤:
118
146
  // 否则在 A 项目点一下刷新,B 项目的标签页面板就被贴上 A 的任务列表(而它还保留自己的
119
147
  // boundTaskId,看起来像"绑定丢了")。两侧都已知根且不同 → 丢弃;本页还不知道根(还没
120
148
  // 同步过)→ 也丢弃,让它自己那一次 /tasks 决定归属,不先借别人的数据。
121
149
  if (!broadcastAppliesTo(dataState.root, root)) return
150
+ // 同一浏览器的时钟可比:晚到的旧快照不能把新状态盖回去。
151
+ if (typeof sentAt === 'number' && sentAt < dataState.lastSyncAt) return
122
152
  setDataState(prev => ({
123
153
  ...prev,
124
154
  tasks: Array.isArray(tasks) ? tasks : [],
125
155
  archivedCount: typeof archivedCount === 'number' ? archivedCount : prev.archivedCount,
156
+ // 只在同一会话内同步绑定:同项目不同会话的任务列表可以共享,绑定不能互相覆盖。
157
+ ...(sessionId && prev.sessionId && sessionId === prev.sessionId
158
+ ? { boundTaskId: typeof boundTaskId === 'string' ? boundTaskId : null }
159
+ : {}),
160
+ lastSyncAt: typeof sentAt === 'number' ? sentAt : prev.lastSyncAt,
126
161
  lastUpdate: Date.now(),
127
162
  }))
128
163
  }
@@ -137,18 +172,31 @@ export const taskDataStore = {
137
172
  return dataState
138
173
  },
139
174
  actions: {
140
- setTasks(payload: { tasks: Task[]; boundTaskId: string | null; archivedCount: number; root?: string | null }): void {
175
+ setTasks(payload: {
176
+ tasks: Task[]
177
+ boundTaskId: string | null
178
+ archivedCount: number
179
+ root?: string | null
180
+ sessionId?: string | null
181
+ }): void {
141
182
  const nextTasks = payload.tasks || []
142
183
  const nextArchived = payload.archivedCount ?? 0
143
184
  const nextRoot = payloadRoot(payload.root)
185
+ // 未提供 sessionId 的调用点(命令节点)不能把已有会话清空,否则绑定同步被顺手关掉。
186
+ const nextSession = payload.sessionId === undefined
187
+ ? dataState.sessionId
188
+ : (typeof payload.sessionId === 'string' && payload.sessionId ? payload.sessionId : null)
189
+ const sentAt = Date.now()
144
190
  setDataState({
145
191
  tasks: nextTasks,
146
192
  boundTaskId: payload.boundTaskId ?? null,
147
193
  archivedCount: nextArchived,
148
194
  root: nextRoot,
149
- lastUpdate: Date.now(),
195
+ sessionId: nextSession,
196
+ lastSyncAt: sentAt,
197
+ lastUpdate: sentAt,
150
198
  })
151
- broadcastDataUpdate(nextTasks, nextArchived, nextRoot)
199
+ broadcastDataUpdate(nextTasks, nextArchived, nextRoot, payload.boundTaskId ?? null, nextSession, sentAt)
152
200
  },
153
201
  reset(): void {
154
202
  setDataState({
@@ -156,6 +204,8 @@ export const taskDataStore = {
156
204
  boundTaskId: null,
157
205
  archivedCount: 0,
158
206
  root: null,
207
+ sessionId: null,
208
+ lastSyncAt: 0,
159
209
  lastUpdate: 0,
160
210
  })
161
211
  },
@@ -3,7 +3,6 @@
3
3
  * 只依赖 react + task-data-store 类型,不碰数据/UI store。
4
4
  */
5
5
  import { useEffect, useRef, useState, useCallback } from 'react'
6
- import { TaskStep } from './task-data-store.ts'
7
6
 
8
7
  interface DragState {
9
8
  fromIndex: number
@@ -26,7 +25,6 @@ interface DragState {
26
25
  */
27
26
  export function useTaskDrag(
28
27
  taskId: string,
29
- steps: TaskStep[],
30
28
  isBound: boolean,
31
29
  onReorder: (fromIndex: number, toIndex: number) => void
32
30
  ) {
@@ -19,7 +19,22 @@
19
19
  export function broadcastAppliesTo(localRoot, incomingRoot) {
20
20
  if (typeof incomingRoot !== 'string' || incomingRoot === '') return false
21
21
  if (typeof localRoot !== 'string' || localRoot === '') return false
22
- return localRoot === incomingRoot
22
+ return rootKey(localRoot) === rootKey(incomingRoot)
23
+ }
24
+
25
+ /** Windows/macOS 的文件系统大小写不敏感;Linux 上不能把两个只差大小写的根当成一个。 */
26
+ function caseInsensitiveFs() {
27
+ const platform = typeof navigator !== 'undefined' ? String(navigator.platform || '') : ''
28
+ if (/win/i.test(platform) || /mac/i.test(platform)) return true
29
+ const ua = typeof navigator !== 'undefined' ? String(navigator.userAgent || '') : ''
30
+ return /Windows|Macintosh/i.test(ua)
31
+ }
32
+
33
+ /** 根的规范键:统一分隔符、去掉末尾分隔符;大小写不敏感平台再折叠大小写。 */
34
+ function rootKey(root) {
35
+ let key = String(root).replace(/\\/g, '/')
36
+ if (key.length > 1) key = key.replace(/\/+$/, '')
37
+ return caseInsensitiveFs() ? key.toLowerCase() : key
23
38
  }
24
39
 
25
40
  /**
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Task UI Store — 仅管本地 UI 状态(closed、minimized、position、expandedIds、theme、showHints)
2
+ * Task UI Store — 仅管本地 UI 状态(closed、minimized、position、expandedTaskIds、theme、showHints)
3
3
  * - 持久化到 localStorage(key: dsh-pm-task-panel-ui)
4
4
  * - 不跨标签页同步(每个标签页独立)
5
5
  * - 启动/刷新强制 closed: true,面板默认不显示
@@ -5,9 +5,11 @@
5
5
  import path from 'node:path'
6
6
  import { ProjectMemoryStore } from '../store.js'
7
7
  import { memoryRootFor, normalizeCitationFiles } from '../util/fs.js'
8
- import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, carryUsageFields, pruneItems, INSIGHT_KINDS } from '../insight-store.js'
8
+ import { cfgInsight, GlobalStore, normalizeInsight, defaultGlobalFile, saveInsight, recordDeleted, carryUsageFields, mergeOrPushInto, demoteToProject, demoteToTask, pruneItems, refreshDerivedTrigger, putInsightField, INSIGHT_KINDS } from '../insight-store.js'
9
9
  import { NO_PROJECT_ROOT_NOTE, projectRootFor } from '../setup/taskbridge.js'
10
10
  import { fencedJson, invocationContext } from './invocation.js'
11
+ import { isoMs } from '../util/value.js'
12
+ import { pruneKindFields } from '../util/insight-fields.js'
11
13
  import { forgetVectorRows } from '../vector-index.js'
12
14
 
13
15
  /** 容量旋钮的防御性取值:cfg 可能只带显式测试字段。 */
@@ -21,9 +23,8 @@ function capOf(value, fallback) {
21
23
  */
22
24
  function forgetVectorsForDeleted({ store, gs, home, ids }) {
23
25
  try {
24
- const dir = home === 'global'
25
- ? (gs && typeof gs.file === 'string' ? path.dirname(gs.file) : null)
26
- : (store && typeof store.dir === 'string' ? store.dir : null)
26
+ // 所有 home 的向量行都在 project store 目录(query_memory/auto-inject 都传 memoryDir)。
27
+ const dir = store && typeof store.dir === 'string' ? store.dir : null
27
28
  if (dir && ids.length) forgetVectorRows({ dir, ids })
28
29
  } catch {
29
30
  /* 缓存删除失败不影响删除承诺 */
@@ -68,6 +69,8 @@ function insSummary(ins, extra = {}) {
68
69
  symbols: (s.symbols || []).length,
69
70
  trigger: s.trigger ? { keywords: s.trigger.keywords || [], scope: s.trigger.scope || [] } : null,
70
71
  steps: Array.isArray(s.steps) ? s.steps.slice(0, 50) : null,
72
+ // 面板编辑要知道原数组是否被截断:只回传看到的 50 条会删掉后面的步骤。
73
+ stepsTotal: Array.isArray(s.steps) ? s.steps.length : 0,
71
74
  updatedAt: s.updatedAt || '',
72
75
  ...extra,
73
76
  }
@@ -81,16 +84,6 @@ function findTaskInsight(store, id) {
81
84
  return null
82
85
  }
83
86
 
84
- /**
85
- * 时间戳解析:非法/缺失一律 0,让排序键永远是可比较的数字。
86
- * @param {unknown} value - ISO 时间字符串。
87
- * @returns {number} 毫秒时间戳;不可解析时 0。
88
- */
89
- function tsOf(value) {
90
- const t = Date.parse(value == null ? '' : String(value))
91
- return Number.isFinite(t) ? t : 0
92
- }
93
-
94
87
  /**
95
88
  * 记忆列表的**全序**比较器:新 → 旧。
96
89
  *
@@ -103,11 +96,11 @@ function tsOf(value) {
103
96
  * @returns {number} 排序结果。
104
97
  */
105
98
  function compareInsightRecency(a, b) {
106
- const ua = tsOf(a.raw?.updatedAt) || tsOf(a.raw?.createdAt)
107
- const ub = tsOf(b.raw?.updatedAt) || tsOf(b.raw?.createdAt)
99
+ const ua = isoMs(a.raw?.updatedAt) || isoMs(a.raw?.createdAt)
100
+ const ub = isoMs(b.raw?.updatedAt) || isoMs(b.raw?.createdAt)
108
101
  if (ua !== ub) return ub - ua
109
- const ca = tsOf(a.raw?.createdAt)
110
- const cb = tsOf(b.raw?.createdAt)
102
+ const ca = isoMs(a.raw?.createdAt)
103
+ const cb = isoMs(b.raw?.createdAt)
111
104
  if (ca !== cb) return cb - ca
112
105
  return String(a.raw?.id ?? '').localeCompare(String(b.raw?.id ?? ''))
113
106
  }
@@ -200,12 +193,15 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
200
193
  copy.movedFrom = { scope: 'task', id, at: now }
201
194
  copy.createdAt = insight.createdAt || copy.createdAt
202
195
  copy.hitCount = insight.hitCount || 0
203
- items.push(copy)
204
- pruneItems(items, capOf(cfg?.maxProject, 100), now)
196
+ const { merged, target } = mergeOrPushInto({ targetPool: items, copy, cfg, nowIso: now })
197
+ pruneItems(items, capOf(cfg?.maxProject, 100), now, { protectedIds: new Set([target.id]) })
205
198
  store.replaceInsightItems(items)
206
199
  task.insights = (task.insights || []).filter((i) => i.id !== id)
207
200
  store.markTasksDirty()
208
- return { ok: true, text: `已提升到 project:${copy.title}` }
201
+ return {
202
+ ok: true,
203
+ text: merged ? `已提升并合并到 project 既有条目:${target.title}` : `已提升到 project:${copy.title}`,
204
+ }
209
205
  }
210
206
  return { ok: false, text: `task 级不支持动作: ${act}` }
211
207
  }
@@ -241,31 +237,28 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
241
237
  copy.movedFrom = { scope: 'project', id, at: now }
242
238
  copy.createdAt = ins.createdAt || copy.createdAt
243
239
  copy.hitCount = ins.hitCount || 0
244
- gs.items().push(copy)
245
- pruneItems(gs.items(), capOf(cfg?.maxGlobalProcedures, 200), now)
240
+ const { merged, target } = mergeOrPushInto({ targetPool: gs.items(), copy, cfg, nowIso: now })
241
+ pruneItems(gs.items(), capOf(cfg?.maxGlobalProcedures, 200), now, { protectedIds: new Set([target.id]) })
246
242
  gs.markDirty()
247
243
  items.splice(idx, 1)
248
244
  store.replaceInsightItems(items)
249
- return { ok: true, text: `已提升到 global:${copy.title}` }
245
+ return {
246
+ ok: true,
247
+ text: merged ? `已提升并合并到 global 既有条目:${target.title}` : `已提升到 global:${copy.title}`,
248
+ }
250
249
  }
251
250
  if (act === 'demote') {
252
- // project → task(需目标任务)
251
+ // project → task(需目标任务);去重/去留统一走 insight-store 的唯一实现。
253
252
  const task = store.getTask(taskId)
254
253
  if (!task) return { ok: false, text: '降级到任务需要 taskId' }
255
- const now = new Date().toISOString()
256
- const copy = carryUsageFields(
257
- normalizeInsight(ins, { scope: 'task', source: ins.source, nowIso: now }),
258
- ins,
259
- )
260
- copy.id = `${id}_d${Date.now().toString(36)}`
261
- copy.movedFrom = { scope: 'project', id, at: now }
262
- copy.createdAt = ins.createdAt || copy.createdAt
263
- if (!Array.isArray(task.insights)) task.insights = []
264
- task.insights.push(copy)
265
- store.markTasksDirty()
266
- items.splice(idx, 1)
267
- store.replaceInsightItems(items)
268
- return { ok: true, text: `已降级到任务 ${task.title}` }
254
+ const moved = demoteToTask(store, taskId, id, new Date().toISOString(), cfg)
255
+ if (!moved.ok) return { ok: false, text: moved.error }
256
+ return {
257
+ ok: true,
258
+ text: moved.merged
259
+ ? `已降级并合并到任务 ${task.title} 的既有条目:${moved.target.title}`
260
+ : `已降级到任务 ${task.title}`,
261
+ }
269
262
  }
270
263
  return { ok: false, text: `project 级不支持动作: ${act}` }
271
264
  }
@@ -290,22 +283,15 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
290
283
  return { ok: true, text: `已删除 global 条目 ${id}` }
291
284
  }
292
285
  if (act === 'demote') {
293
- // global → project
294
- const now = new Date().toISOString()
295
- const pjItems = store.insightItems()
296
- const copy = carryUsageFields(
297
- normalizeInsight(ins, { scope: 'project', source: ins.source, nowIso: now }),
298
- ins,
299
- )
300
- copy.id = `${id}_d${Date.now().toString(36)}`
301
- copy.movedFrom = { scope: 'global', id, at: now }
302
- copy.createdAt = ins.createdAt || copy.createdAt
303
- pjItems.push(copy)
304
- pruneItems(pjItems, capOf(cfg?.maxProject, 100), now)
305
- store.replaceInsightItems(pjItems)
306
- items.splice(idx, 1)
307
- gs.markDirty()
308
- return { ok: true, text: `已降级到 project:${copy.title}` }
286
+ // global → project;去重/容量/去留统一走 insight-store 的唯一实现。
287
+ const moved = demoteToProject(store, gs, id, new Date().toISOString(), cfg)
288
+ if (!moved.ok) return { ok: false, text: moved.error }
289
+ return {
290
+ ok: true,
291
+ text: moved.merged
292
+ ? `已降级并合并到 project 既有条目:${moved.target.title}`
293
+ : `已降级到 project:${moved.target.title}`,
294
+ }
309
295
  }
310
296
  return { ok: false, text: `global 级不支持动作: ${act}` }
311
297
  }
@@ -323,30 +309,20 @@ export function saveMemoryItem({ store, gs, cfg, scope, fields }) {
323
309
 
324
310
  const EDIT_FIELDS = new Set(['title', 'kind', 'body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'confidence', 'steps', 'trigger', 'tags', 'files', 'symbols'])
325
311
 
326
- // kind 各自的“内容字段”;切 kind 时清掉不再属于它的旧字段(否则旧经验文本会残留显示)
327
- const KIND_CONTENT = {
328
- lesson: ['pattern', 'fix'],
329
- decision: ['choice', 'reason'],
330
- procedure: ['steps', 'trigger'],
331
- experience: ['problem', 'solution'],
332
- }
333
- // 切 kind 时要清掉的内容字段。**不含 trigger**:任何 kind 都可以带 authored trigger,
334
- // 放进这里会在 lesson↔decision 之间切换时把自动注入能力一并删掉。
335
- const ALL_CONTENT = ['body', 'pattern', 'fix', 'problem', 'solution', 'choice', 'reason', 'steps']
336
-
337
312
  /** 编辑既有条目(title/kind/正文/trigger 等白名单字段)。任务级按 id 在任务池定位。 */
338
313
  export function editMemoryItem({ store, gs, scope, id, fields, root }) {
339
314
  if (!fields || typeof fields !== 'object') return { ok: false, text: 'edit 需要字段对象' }
340
315
  const applyTo = (item) => {
341
316
  let changed = false
317
+ let dropped = 0
342
318
  const oldKind = item.kind
343
319
  for (const key of Object.keys(fields)) {
344
320
  const v = fields[key]
345
321
  if (!EDIT_FIELDS.has(key)) continue
346
322
  if (key === 'kind') {
347
323
  if (!INSIGHT_KINDS.includes(v) || v === item.kind) continue
348
- item.kind = v
349
- changed = true
324
+ // 与自动覆盖同一条字段写入:旧 kind 进 prev,编辑可还原。
325
+ if (putInsightField(item, key, v)) changed = true
350
326
  continue
351
327
  }
352
328
  if (key === 'trigger') {
@@ -362,58 +338,58 @@ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
362
338
  if (v.when && typeof v.when === 'object') next.when = v.when
363
339
  if (v.guard && typeof v.guard === 'object') next.guard = v.guard
364
340
  if (typeof v.prevents === 'string') next.prevents = v.prevents
365
- item.trigger = next
366
- changed = true
341
+ if (putInsightField(item, 'trigger', next)) changed = true
367
342
  continue
368
343
  }
369
344
  if (key === 'steps' || key === 'tags' || key === 'files' || key === 'symbols') {
370
345
  if (!Array.isArray(v)) continue
371
346
  // 写入期约束(与 save_lesson 同一判据):files 只收项目内相对路径,项目外/逃出根的丢弃。
372
- item[key] = key === 'files' ? normalizeCitationFiles(v, root).files : v.map(String)
373
- changed = true
347
+ if (key === 'files') {
348
+ const norm = normalizeCitationFiles(v, root)
349
+ if (putInsightField(item, key, norm.files)) changed = true
350
+ dropped += norm.dropped.length
351
+ } else if (putInsightField(item, key, v.map(String))) {
352
+ changed = true
353
+ }
374
354
  continue
375
355
  }
376
356
  if (key === 'confidence') {
377
357
  const n = Number(v)
378
358
  if (!Number.isFinite(n)) continue
379
- item.confidence = Math.max(0, Math.min(1, n))
380
- changed = true
359
+ if (putInsightField(item, key, Math.max(0, Math.min(1, n)))) changed = true
381
360
  continue
382
361
  }
383
362
  const s = v === null || v === undefined ? '' : String(v)
384
363
  if (key === 'title' && !s.trim()) continue
385
- item[key] = s
386
- changed = true
364
+ if (putInsightField(item, key, s)) changed = true
387
365
  }
388
- // 切 kind → 清理不再属于新 kind 的旧内容字段
389
- if (changed && item.kind !== oldKind && KIND_CONTENT[item.kind]) {
390
- const keep = new Set(KIND_CONTENT[item.kind])
391
- const isProcedure = item.kind === 'procedure'
392
- for (const f of ALL_CONTENT) {
393
- if (keep.has(f)) continue
394
- if (isProcedure && f === 'body') continue // procedure 保留通用 body
395
- delete item[f]
396
- }
366
+ pruneKindFields(item, oldKind)
367
+ if (changed) {
368
+ item.updatedAt = new Date().toISOString()
369
+ refreshDerivedTrigger(item)
397
370
  }
398
- if (changed) item.updatedAt = new Date().toISOString()
399
- return changed
371
+ return { changed, dropped }
400
372
  }
373
+ const droppedNote = (n) => (n ? `;${n} 个 files 是项目外路径,已丢弃` : '')
401
374
  const s = scope || 'project'
375
+ if (!['task', 'project', 'global'].includes(s)) return { ok: false, text: `未知 scope: ${s}(只认 task/project/global)` }
402
376
  if (s === 'task') {
403
377
  const found = findTaskInsight(store, id)
404
378
  if (!found) return { ok: false, text: `insight ${id} 不在任务层` }
405
- if (!applyTo(found.insight)) return { ok: false, text: '没有可更新的字段' }
379
+ const applied = applyTo(found.insight)
380
+ if (!applied.changed) return { ok: false, text: '没有可更新的字段' }
406
381
  store.markTasksDirty()
407
- return { ok: true, text: '已更新任务级记忆' }
382
+ return { ok: true, text: `已更新任务级记忆${droppedNote(applied.dropped)}` }
408
383
  }
409
384
  const items = s === 'global' ? (gs ? gs.items() : null) : store.insightItems()
410
385
  if (!items) return { ok: false, text: '存储不可用' }
411
386
  const item = items.find((i) => i.id === id)
412
387
  if (!item) return { ok: false, text: `insight ${id} 不在 ${s} 层` }
413
- if (!applyTo(item)) return { ok: false, text: '没有可更新的字段' }
388
+ const applied = applyTo(item)
389
+ if (!applied.changed) return { ok: false, text: '没有可更新的字段' }
414
390
  if (s === 'global') gs.markDirty()
415
391
  else store.replaceInsightItems(items)
416
- return { ok: true, text: '已更新记忆条目' }
392
+ return { ok: true, text: `已更新记忆条目${droppedNote(applied.dropped)}` }
417
393
  }
418
394
 
419
395
  /**
@@ -443,7 +419,10 @@ export function insightCommandDefinition(config, ctx) {
443
419
  if (!raw[0]) return { kind: 'error', text: '[insight] 用法见面板' }
444
420
  const verb = raw[0]
445
421
  if (verb === 'list') {
446
- const scope = raw[1] === 'task' || raw[1] === 'global' || raw[1] === 'project' ? raw[1] : 'project'
422
+ if (raw[1] !== undefined && !['task', 'global', 'project'].includes(raw[1])) {
423
+ return { kind: 'error', text: `[insight] 未知 scope: ${raw[1]}(只认 task/project/global)` }
424
+ }
425
+ const scope = raw[1] || 'project'
447
426
  // 分页参数可选:省略即维持"返回全部"的旧行为(老客户端 bundle 仍按此调用)。
448
427
  // 显式给 limit 时封顶 INSIGHT_PAGE_MAX,避免一次请求把整个池子拉成超大载荷。
449
428
  let offset = 0
@@ -480,12 +459,24 @@ export function insightCommandDefinition(config, ctx) {
480
459
  if (!fields || typeof fields !== 'object' || (!fields.title && !fields.pattern && !fields.topic)) {
481
460
  return { kind: 'error', text: '[insight] save JSON 需要 title/pattern/topic' }
482
461
  }
462
+ // 面板来的 files 也要走同一套写入期路径约束:项目外/绝对路径丢弃,不写进条目。
463
+ let droppedFiles = 0
464
+ if (Array.isArray(fields.files)) {
465
+ const norm = normalizeCitationFiles(fields.files, root)
466
+ droppedFiles = norm.dropped.length
467
+ fields = { ...fields, files: norm.files }
468
+ }
483
469
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
484
470
  const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
485
471
  const res = saveMemoryItem({ store, gs, cfg: cfgInsight(config), scope, fields })
486
472
  store.commit(() => 0)
487
473
  gs.commit()
488
- return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
474
+ if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
475
+ return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
476
+ }
477
+ return res.ok
478
+ ? { kind: 'success', text: res.text + (droppedFiles ? `;${droppedFiles} 个 files 是项目外路径,已丢弃` : '') }
479
+ : { kind: 'error', text: res.text }
489
480
  }
490
481
  if (verb === 'edit') {
491
482
  // /insight edit <scope> <id> <json>
@@ -505,19 +496,25 @@ export function insightCommandDefinition(config, ctx) {
505
496
  const res = editMemoryItem({ store, gs, scope, id, fields, root })
506
497
  store.commit(() => 0)
507
498
  gs.commit()
499
+ if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
500
+ return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
501
+ }
508
502
  return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
509
503
  }
510
504
  const scope = raw[1]
511
505
  const id = raw[2]
512
506
  const taskId = raw[3]
513
507
  if (!['confirm', 'promote', 'demote', 'archive', 'restore', 'delete'].includes(verb) || !id) {
514
- return { kind: 'error', text: '[insight] 用法: /insight <动作|save|edit> …' }
508
+ return { kind: 'error', text: '[insight] 用法: /tasks insight <动作|save|edit> …' }
515
509
  }
516
510
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
517
511
  const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
518
512
  const res = actInsight({ store, gs, action: verb, scope, id, taskId, cfg: cfgInsight(config) })
519
513
  store.commit(() => 0) // 项目侧(tasks/insights)落盘
520
514
  gs.commit() // global 侧若有变更落盘
515
+ if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
516
+ return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
517
+ }
521
518
  return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
522
519
  } catch (err) {
523
520
  return { kind: 'error', text: `[insight] ${err?.message || err}` }
@@ -38,6 +38,7 @@ function withTaskSnapshot(config, cwd, sid, store, note) {
38
38
  const boundId = sid ? store.getBoundTaskId(sid) : null
39
39
  const root = projectRootFor(cwd, config)
40
40
  const human = `项目 ${root}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
41
+ + (store.lastSaveOk === false ? '\n⚠ tasks.json 未落盘(权限/磁盘/锁);内存已变更,退出前会重试。' : '')
41
42
  const payload = buildTaskPayload(active, boundId, archived, root)
42
43
  return { kind: 'success', text: fencedJson(human, payload) }
43
44
  }
@@ -110,8 +111,9 @@ export function taskCommandDefinition(config, ctx) {
110
111
  } else if (verb === 'step-move') {
111
112
  const from = Number(rest[0])
112
113
  const to = Number(rest[1])
113
- if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || from >= task.steps.length) {
114
- return { kind: 'error', text: '[task] step-move 需要合法的 from/to' }
114
+ if (!Number.isInteger(from) || !Number.isInteger(to)
115
+ || from < 0 || from >= task.steps.length || to < 0 || to > task.steps.length) {
116
+ return { kind: 'error', text: '[task] step-move 需要合法的 from/to(0 ≤ to ≤ 步骤数)' }
115
117
  }
116
118
  const [moved] = task.steps.splice(from, 1)
117
119
  const target = to > from ? to - 1 : to
@@ -194,7 +196,7 @@ export function taskCommandDefinition(config, ctx) {
194
196
  store.markTasksDirty()
195
197
  store.save()
196
198
  if (shouldAdoptToHost(config)) {
197
- adoptStepsToSession(session, task)
199
+ adoptStepsToSession(session, task, { force: true })
198
200
  }
199
201
  const note = `已更新「${task.title}」步骤(${norm.length} 条)`
200
202
  return withTaskSnapshot(config, cwd, sid, store, note)
@@ -216,9 +218,9 @@ export function taskCommandDefinition(config, ctx) {
216
218
  if (prevBound && prevBound !== task.id) {
217
219
  fireReflect(config, { llm: ctx?.llm }, root, prevBound, 'switch-away', resolveRoute(session ? { agent: { session } } : undefined, config))
218
220
  }
219
- // 反向接管:切换成功后把任务步骤推成宿主 todo/write(dsh 清单跟随)
221
+ // 反向接管:切换成功后把任务步骤推成宿主 todo/write(dsh 清单跟随);空步骤也要推空。
220
222
  if (shouldAdoptToHost(config)) {
221
- adoptStepsToSession(session, task)
223
+ adoptStepsToSession(session, task, { force: true })
222
224
  }
223
225
  const note = `已切换绑定: ${describeTask(task)}${sid ? '' : '(拿不到会话 id,未持久绑定)'}`
224
226
  return withTaskSnapshot(config, cwd, sid, store, note)
@@ -7,18 +7,42 @@ 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
+ // 快照会原样写进会话历史(command/done),没有上限时一个异常任务就能把单条消息撑到几十 MB。
11
+ // 截断只发生在**展示载荷**里,不碰 store;超出部分由 totals 告知调用方。
12
+ const SNAPSHOT_LIMITS = { steps: 50, files: 50, insights: 20 }
13
+
14
+ function cappable(list, max) {
15
+ const arr = Array.isArray(list) ? list : []
16
+ return { slice: arr.slice(0, max), total: arr.length }
17
+ }
18
+
10
19
  export function buildTaskPayload(tasks, boundId, archived, root = null) {
11
20
  return JSON.stringify({
12
- tasks: tasks.map((t) => ({
13
- id: t.id,
14
- title: t.title,
15
- steps: (t.steps || []).map((s) => ({ content: stepContent(s), status: stepStatus(s) })),
16
- files: (t.files || []).map((f) => ({ path: f, line: undefined })),
17
- lastActiveAt: t.lastActiveAt,
18
- updatedAt: t.updatedAt,
19
- archived: t.archived || false,
20
- insights: (t.insights || []).filter((i) => !i.archived).map((i) => ({ id: i.id, kind: i.kind || 'lesson', title: i.title || '', draft: i.draft === true })),
21
- })),
21
+ tasks: tasks.map((t) => {
22
+ const steps = cappable(t.steps, SNAPSHOT_LIMITS.steps)
23
+ const files = cappable(t.files, SNAPSHOT_LIMITS.files)
24
+ const insights = cappable((t.insights || []).filter((i) => !i.archived), SNAPSHOT_LIMITS.insights)
25
+ const truncated = steps.total > steps.slice.length || files.total > files.slice.length || insights.total > insights.slice.length
26
+ return {
27
+ id: t.id,
28
+ title: t.title,
29
+ steps: steps.slice.map((s) => ({ content: stepContent(s), status: stepStatus(s) })),
30
+ files: files.slice.map((f) => ({ path: f, line: undefined })),
31
+ lastActiveAt: t.lastActiveAt,
32
+ updatedAt: t.updatedAt,
33
+ archived: t.archived || false,
34
+ insights: insights.slice.map((i) => ({ id: i.id, kind: i.kind || 'lesson', title: i.title || '', draft: i.draft === true })),
35
+ ...(truncated ? {
36
+ totals: {
37
+ steps: steps.total,
38
+ files: files.total,
39
+ insights: insights.total,
40
+ // 截断后 UI 不能再用前 50 步判断“全部完成”。
41
+ completedSteps: (Array.isArray(t.steps) ? t.steps : []).filter((x) => stepStatus(x) === 'completed').length,
42
+ },
43
+ } : {}),
44
+ }
45
+ }),
22
46
  boundId: boundId || null,
23
47
  archived,
24
48
  // 项目根:客户端用它把跨标签页广播限定在同一个项目里(不同项目共用一个浏览器时,
package/src/doc-index.js CHANGED
@@ -67,7 +67,9 @@ export function extractKeywords(title, text, { max = MAX_KEYWORDS } = {}) {
67
67
  * 只对 doc 条目判断,code 条目(符号表)不需要 terms。
68
68
  */
69
69
  export function docEntriesNeedBackfill(entries) {
70
- if (!Array.isArray(entries) || entries.length === 0) return true
70
+ // 零条目不是“旧条目缺 terms”:空文档本来就没有 chunk;返回 true 会让 mtime 快路径永远失效。
71
+ if (!Array.isArray(entries)) return true
72
+ if (entries.length === 0) return false
71
73
  return entries.some((e) => e && e.type === 'doc' &&
72
74
  (typeof e.terms !== 'string' || e.termsVersion !== TOKENIZER_VERSION))
73
75
  }