@yolk_vat-y/dsh-project-memory 0.6.12 → 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 (63) hide show
  1. package/CHANGELOG.md +58 -20
  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 +85 -60
  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 +129 -32
  34. package/src/lazy.js +29 -23
  35. package/src/llm-route.js +1 -1
  36. package/src/ops.js +18 -5
  37. package/src/parsers/pdfjs-parser.js +3 -33
  38. package/src/project-memory-service.js +195 -0
  39. package/src/project-profile.js +0 -4
  40. package/src/setup/taskbridge.js +38 -6
  41. package/src/store.js +638 -135
  42. package/src/symbols.js +2 -4
  43. package/src/tools/forget.js +3 -6
  44. package/src/tools/index-doc.js +61 -18
  45. package/src/tools/index-repo.js +16 -12
  46. package/src/tools/lesson-tools.js +5 -5
  47. package/src/tools/output.js +28 -0
  48. package/src/tools/query-memory.js +6 -9
  49. package/src/tools/remember.js +3 -6
  50. package/src/tools/stats.js +3 -6
  51. package/src/tools/task-tools.js +15 -8
  52. package/src/tools/watch-repo.js +15 -12
  53. package/src/util/flush.js +1 -1
  54. package/src/util/fs.js +135 -20
  55. package/src/util/message-source.js +20 -0
  56. package/src/util/relative-time.js +24 -0
  57. package/src/util/search.js +0 -1
  58. package/src/util/task-view.js +8 -15
  59. package/src/vector-index.js +2 -2
  60. package/src/watch.js +25 -8
  61. package/client/client.d.ts +0 -27
  62. package/client/client.d.ts.map +0 -1
  63. 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,7 +5,7 @@
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
11
  import { isoMs } from '../util/value.js'
@@ -23,9 +23,8 @@ function capOf(value, fallback) {
23
23
  */
24
24
  function forgetVectorsForDeleted({ store, gs, home, ids }) {
25
25
  try {
26
- const dir = home === 'global'
27
- ? (gs && typeof gs.file === 'string' ? path.dirname(gs.file) : null)
28
- : (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
29
28
  if (dir && ids.length) forgetVectorRows({ dir, ids })
30
29
  } catch {
31
30
  /* 缓存删除失败不影响删除承诺 */
@@ -70,6 +69,8 @@ function insSummary(ins, extra = {}) {
70
69
  symbols: (s.symbols || []).length,
71
70
  trigger: s.trigger ? { keywords: s.trigger.keywords || [], scope: s.trigger.scope || [] } : null,
72
71
  steps: Array.isArray(s.steps) ? s.steps.slice(0, 50) : null,
72
+ // 面板编辑要知道原数组是否被截断:只回传看到的 50 条会删掉后面的步骤。
73
+ stepsTotal: Array.isArray(s.steps) ? s.steps.length : 0,
73
74
  updatedAt: s.updatedAt || '',
74
75
  ...extra,
75
76
  }
@@ -192,12 +193,15 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
192
193
  copy.movedFrom = { scope: 'task', id, at: now }
193
194
  copy.createdAt = insight.createdAt || copy.createdAt
194
195
  copy.hitCount = insight.hitCount || 0
195
- items.push(copy)
196
- 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]) })
197
198
  store.replaceInsightItems(items)
198
199
  task.insights = (task.insights || []).filter((i) => i.id !== id)
199
200
  store.markTasksDirty()
200
- return { ok: true, text: `已提升到 project:${copy.title}` }
201
+ return {
202
+ ok: true,
203
+ text: merged ? `已提升并合并到 project 既有条目:${target.title}` : `已提升到 project:${copy.title}`,
204
+ }
201
205
  }
202
206
  return { ok: false, text: `task 级不支持动作: ${act}` }
203
207
  }
@@ -233,31 +237,28 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
233
237
  copy.movedFrom = { scope: 'project', id, at: now }
234
238
  copy.createdAt = ins.createdAt || copy.createdAt
235
239
  copy.hitCount = ins.hitCount || 0
236
- gs.items().push(copy)
237
- 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]) })
238
242
  gs.markDirty()
239
243
  items.splice(idx, 1)
240
244
  store.replaceInsightItems(items)
241
- return { ok: true, text: `已提升到 global:${copy.title}` }
245
+ return {
246
+ ok: true,
247
+ text: merged ? `已提升并合并到 global 既有条目:${target.title}` : `已提升到 global:${copy.title}`,
248
+ }
242
249
  }
243
250
  if (act === 'demote') {
244
- // project → task(需目标任务)
251
+ // project → task(需目标任务);去重/去留统一走 insight-store 的唯一实现。
245
252
  const task = store.getTask(taskId)
246
253
  if (!task) return { ok: false, text: '降级到任务需要 taskId' }
247
- const now = new Date().toISOString()
248
- const copy = carryUsageFields(
249
- normalizeInsight(ins, { scope: 'task', source: ins.source, nowIso: now }),
250
- ins,
251
- )
252
- copy.id = `${id}_d${Date.now().toString(36)}`
253
- copy.movedFrom = { scope: 'project', id, at: now }
254
- copy.createdAt = ins.createdAt || copy.createdAt
255
- if (!Array.isArray(task.insights)) task.insights = []
256
- task.insights.push(copy)
257
- store.markTasksDirty()
258
- items.splice(idx, 1)
259
- store.replaceInsightItems(items)
260
- 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
+ }
261
262
  }
262
263
  return { ok: false, text: `project 级不支持动作: ${act}` }
263
264
  }
@@ -282,22 +283,15 @@ export function actInsight({ store, gs, action, scope, id, taskId, cfg }) {
282
283
  return { ok: true, text: `已删除 global 条目 ${id}` }
283
284
  }
284
285
  if (act === 'demote') {
285
- // global → project
286
- const now = new Date().toISOString()
287
- const pjItems = store.insightItems()
288
- const copy = carryUsageFields(
289
- normalizeInsight(ins, { scope: 'project', source: ins.source, nowIso: now }),
290
- ins,
291
- )
292
- copy.id = `${id}_d${Date.now().toString(36)}`
293
- copy.movedFrom = { scope: 'global', id, at: now }
294
- copy.createdAt = ins.createdAt || copy.createdAt
295
- pjItems.push(copy)
296
- pruneItems(pjItems, capOf(cfg?.maxProject, 100), now)
297
- store.replaceInsightItems(pjItems)
298
- items.splice(idx, 1)
299
- gs.markDirty()
300
- 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
+ }
301
295
  }
302
296
  return { ok: false, text: `global 级不支持动作: ${act}` }
303
297
  }
@@ -320,14 +314,15 @@ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
320
314
  if (!fields || typeof fields !== 'object') return { ok: false, text: 'edit 需要字段对象' }
321
315
  const applyTo = (item) => {
322
316
  let changed = false
317
+ let dropped = 0
323
318
  const oldKind = item.kind
324
319
  for (const key of Object.keys(fields)) {
325
320
  const v = fields[key]
326
321
  if (!EDIT_FIELDS.has(key)) continue
327
322
  if (key === 'kind') {
328
323
  if (!INSIGHT_KINDS.includes(v) || v === item.kind) continue
329
- item.kind = v
330
- changed = true
324
+ // 与自动覆盖同一条字段写入:旧 kind 进 prev,编辑可还原。
325
+ if (putInsightField(item, key, v)) changed = true
331
326
  continue
332
327
  }
333
328
  if (key === 'trigger') {
@@ -343,49 +338,58 @@ export function editMemoryItem({ store, gs, scope, id, fields, root }) {
343
338
  if (v.when && typeof v.when === 'object') next.when = v.when
344
339
  if (v.guard && typeof v.guard === 'object') next.guard = v.guard
345
340
  if (typeof v.prevents === 'string') next.prevents = v.prevents
346
- item.trigger = next
347
- changed = true
341
+ if (putInsightField(item, 'trigger', next)) changed = true
348
342
  continue
349
343
  }
350
344
  if (key === 'steps' || key === 'tags' || key === 'files' || key === 'symbols') {
351
345
  if (!Array.isArray(v)) continue
352
346
  // 写入期约束(与 save_lesson 同一判据):files 只收项目内相对路径,项目外/逃出根的丢弃。
353
- item[key] = key === 'files' ? normalizeCitationFiles(v, root).files : v.map(String)
354
- 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
+ }
355
354
  continue
356
355
  }
357
356
  if (key === 'confidence') {
358
357
  const n = Number(v)
359
358
  if (!Number.isFinite(n)) continue
360
- item.confidence = Math.max(0, Math.min(1, n))
361
- changed = true
359
+ if (putInsightField(item, key, Math.max(0, Math.min(1, n)))) changed = true
362
360
  continue
363
361
  }
364
362
  const s = v === null || v === undefined ? '' : String(v)
365
363
  if (key === 'title' && !s.trim()) continue
366
- item[key] = s
367
- changed = true
364
+ if (putInsightField(item, key, s)) changed = true
368
365
  }
369
366
  pruneKindFields(item, oldKind)
370
- if (changed) item.updatedAt = new Date().toISOString()
371
- return changed
367
+ if (changed) {
368
+ item.updatedAt = new Date().toISOString()
369
+ refreshDerivedTrigger(item)
370
+ }
371
+ return { changed, dropped }
372
372
  }
373
+ const droppedNote = (n) => (n ? `;${n} 个 files 是项目外路径,已丢弃` : '')
373
374
  const s = scope || 'project'
375
+ if (!['task', 'project', 'global'].includes(s)) return { ok: false, text: `未知 scope: ${s}(只认 task/project/global)` }
374
376
  if (s === 'task') {
375
377
  const found = findTaskInsight(store, id)
376
378
  if (!found) return { ok: false, text: `insight ${id} 不在任务层` }
377
- if (!applyTo(found.insight)) return { ok: false, text: '没有可更新的字段' }
379
+ const applied = applyTo(found.insight)
380
+ if (!applied.changed) return { ok: false, text: '没有可更新的字段' }
378
381
  store.markTasksDirty()
379
- return { ok: true, text: '已更新任务级记忆' }
382
+ return { ok: true, text: `已更新任务级记忆${droppedNote(applied.dropped)}` }
380
383
  }
381
384
  const items = s === 'global' ? (gs ? gs.items() : null) : store.insightItems()
382
385
  if (!items) return { ok: false, text: '存储不可用' }
383
386
  const item = items.find((i) => i.id === id)
384
387
  if (!item) return { ok: false, text: `insight ${id} 不在 ${s} 层` }
385
- if (!applyTo(item)) return { ok: false, text: '没有可更新的字段' }
388
+ const applied = applyTo(item)
389
+ if (!applied.changed) return { ok: false, text: '没有可更新的字段' }
386
390
  if (s === 'global') gs.markDirty()
387
391
  else store.replaceInsightItems(items)
388
- return { ok: true, text: '已更新记忆条目' }
392
+ return { ok: true, text: `已更新记忆条目${droppedNote(applied.dropped)}` }
389
393
  }
390
394
 
391
395
  /**
@@ -415,7 +419,10 @@ export function insightCommandDefinition(config, ctx) {
415
419
  if (!raw[0]) return { kind: 'error', text: '[insight] 用法见面板' }
416
420
  const verb = raw[0]
417
421
  if (verb === 'list') {
418
- 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'
419
426
  // 分页参数可选:省略即维持"返回全部"的旧行为(老客户端 bundle 仍按此调用)。
420
427
  // 显式给 limit 时封顶 INSIGHT_PAGE_MAX,避免一次请求把整个池子拉成超大载荷。
421
428
  let offset = 0
@@ -452,12 +459,24 @@ export function insightCommandDefinition(config, ctx) {
452
459
  if (!fields || typeof fields !== 'object' || (!fields.title && !fields.pattern && !fields.topic)) {
453
460
  return { kind: 'error', text: '[insight] save JSON 需要 title/pattern/topic' }
454
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
+ }
455
469
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
456
470
  const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
457
471
  const res = saveMemoryItem({ store, gs, cfg: cfgInsight(config), scope, fields })
458
472
  store.commit(() => 0)
459
473
  gs.commit()
460
- 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 }
461
480
  }
462
481
  if (verb === 'edit') {
463
482
  // /insight edit <scope> <id> <json>
@@ -477,19 +496,25 @@ export function insightCommandDefinition(config, ctx) {
477
496
  const res = editMemoryItem({ store, gs, scope, id, fields, root })
478
497
  store.commit(() => 0)
479
498
  gs.commit()
499
+ if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
500
+ return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
501
+ }
480
502
  return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
481
503
  }
482
504
  const scope = raw[1]
483
505
  const id = raw[2]
484
506
  const taskId = raw[3]
485
507
  if (!['confirm', 'promote', 'demote', 'archive', 'restore', 'delete'].includes(verb) || !id) {
486
- return { kind: 'error', text: '[insight] 用法: /insight <动作|save|edit> …' }
508
+ return { kind: 'error', text: '[insight] 用法: /tasks insight <动作|save|edit> …' }
487
509
  }
488
510
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
489
511
  const gs = new GlobalStore(cfgInsight(config).globalFile || defaultGlobalFile()).load()
490
512
  const res = actInsight({ store, gs, action: verb, scope, id, taskId, cfg: cfgInsight(config) })
491
513
  store.commit(() => 0) // 项目侧(tasks/insights)落盘
492
514
  gs.commit() // global 侧若有变更落盘
515
+ if (res.ok && (store.lastSaveOk === false || gs.lastCommitOk === false)) {
516
+ return { kind: 'error', text: `${res.text};但写盘失败(权限/磁盘/锁),重启后会丢失` }
517
+ }
493
518
  return res.ok ? { kind: 'success', text: res.text } : { kind: 'error', text: res.text }
494
519
  } catch (err) {
495
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
  }
package/src/enhancer.js CHANGED
@@ -73,18 +73,6 @@ export function initTypeScript(config) {
73
73
  return null
74
74
  }
75
75
 
76
- export function getTypeScript() {
77
- return ts
78
- }
79
-
80
- export function hasTypeScript() {
81
- return ts !== null
82
- }
83
-
84
- export function getTsPath() {
85
- return tsPath
86
- }
87
-
88
76
  export function getTsVersion() {
89
77
  return tsVersion
90
78
  }
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * watch 的失败过去只打一行日志,懒索引的单文件失败甚至整段吞掉(`catch {}`),于是
5
5
  * "某些文件一直没进语料"没有任何可观察面。这里按根记住最近失败的 rel 与原因,
6
- * 由 index_repo / memory_stats 一并报出。
6
+ * 由 index_repo / pm_stats 一并报出。
7
7
  *
8
8
  * 不持久化是刻意的:watch 每轮都会重试,问题仍在时失败会重新登记;重启后立刻又能看见。
9
9
  */
@@ -113,13 +113,16 @@ export function toFileUpdate(rel, plan, record) {
113
113
  * 不再重建 doc↔symbol 链接:链接是读取期解算的派生关系(见 src/link.js),
114
114
  * 所以这里也没有了那个「中间批次跳过链接、最后一批统一做」的 `link` 参数。
115
115
  *
116
- * @param {{updates: object[], unseen?: Set<string>|null, root?: string|null}} args
116
+ * @param {{updates: object[], unseen?: Set<string>|null, root?: string|null,
117
+ * isExcludedRel?: ((rel: string) => boolean)|null}} args
117
118
  * `root` 给出时,显式索引过、且文件仍在盘上的条目不会被 unseen 清理删掉:它们本来就不在
118
119
  * 扫描清单里(.gitignore 排除),"没扫到"不等于"被删了"。
120
+ * `isExcludedRel` 必须先于 explicit 豁免生效:roots.exclude 是"这棵子树一律不进索引",
121
+ * 显式 index_doc 过的文件也不能因为 explicit 标记而在排除后继续可检索。
119
122
  * @returns {{stale: string[], removed: number}} stale 是 CAS 失败(并发改动)的 rel,
120
123
  * 调用方应让它们保持「未落快照」状态,下一轮重试。
121
124
  */
122
- export function commitFileUpdates(store, { updates, unseen = null, root = null }) {
125
+ export function commitFileUpdates(store, { updates, unseen = null, root = null, isExcludedRel = null }) {
123
126
  const stale = []
124
127
  let removed = 0
125
128
  store.commit((s) => {
@@ -133,6 +136,12 @@ export function commitFileUpdates(store, { updates, unseen = null, root = null }
133
136
  if (unseen) {
134
137
  for (const rel of Object.keys(s.files)) {
135
138
  if (unseen.has(rel)) continue
139
+ // 排除规则优先于 explicit:被 roots.exclude 命中的文件即使显式索引过也必须摘掉。
140
+ if (isExcludedRel && isExcludedRel(rel)) {
141
+ s.removeFile(rel)
142
+ removed++
143
+ continue
144
+ }
136
145
  if (root && s.files[rel]?.explicit && existsSync(path.join(root, rel))) continue
137
146
  s.removeFile(rel)
138
147
  removed++