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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +68 -20
  2. package/README.md +14 -105
  3. package/README.zh-CN.md +14 -105
  4. package/client/client.js +311 -163
  5. package/client/client.js.map +1 -1
  6. package/package.json +8 -8
  7. package/scripts/file-peak.mjs +1 -1
  8. package/scripts/tool-schema-size.mjs +1 -1
  9. package/skills/project-memory/SKILL.md +1 -1
  10. package/skills/project-memory/scripts/pm-digest.mjs +20 -6
  11. package/src/audit.js +10 -2
  12. package/src/auto-inject.js +124 -38
  13. package/src/client/MemoryView.tsx +121 -51
  14. package/src/client/TaskCommandNode.tsx +6 -4
  15. package/src/client/TaskComponents.tsx +14 -26
  16. package/src/client/TaskPanel.tsx +44 -23
  17. package/src/client/client.ts +4 -7
  18. package/src/client/i18n.ts +29 -0
  19. package/src/client/kind-label.js +38 -0
  20. package/src/client/paging.js +1 -14
  21. package/src/client/settings-card.tsx +9 -0
  22. package/src/client/slash.ts +4 -15
  23. package/src/client/task-data-store.ts +57 -7
  24. package/src/client/task-hooks.ts +0 -2
  25. package/src/client/task-scope.js +16 -1
  26. package/src/client/task-ui-store.ts +1 -1
  27. package/src/commands/insight-actions.js +85 -60
  28. package/src/commands/task-actions.js +7 -5
  29. package/src/commands/tasks.js +34 -10
  30. package/src/doc-index.js +3 -1
  31. package/src/enhancer.js +0 -12
  32. package/src/index-failures.js +1 -1
  33. package/src/index-pipeline.js +11 -2
  34. package/src/index.js +60 -14
  35. package/src/inject-visible.js +282 -0
  36. package/src/insight-store.js +129 -32
  37. package/src/lazy.js +29 -23
  38. package/src/llm-route.js +1 -1
  39. package/src/ops.js +18 -5
  40. package/src/parsers/pdfjs-parser.js +3 -33
  41. package/src/project-memory-service.js +195 -0
  42. package/src/project-profile.js +0 -4
  43. package/src/setup/taskbridge.js +38 -6
  44. package/src/store.js +638 -135
  45. package/src/symbols.js +2 -4
  46. package/src/tools/forget.js +3 -6
  47. package/src/tools/index-doc.js +61 -18
  48. package/src/tools/index-repo.js +16 -12
  49. package/src/tools/lesson-tools.js +5 -5
  50. package/src/tools/output.js +28 -0
  51. package/src/tools/query-memory.js +6 -9
  52. package/src/tools/remember.js +3 -6
  53. package/src/tools/stats.js +3 -6
  54. package/src/tools/task-tools.js +15 -8
  55. package/src/tools/watch-repo.js +15 -12
  56. package/src/util/flush.js +1 -1
  57. package/src/util/fs.js +135 -20
  58. package/src/util/message-source.js +20 -0
  59. package/src/util/relative-time.js +24 -0
  60. package/src/util/search.js +0 -1
  61. package/src/util/task-view.js +8 -15
  62. package/src/vector-index.js +2 -2
  63. package/src/watch.js +25 -8
  64. package/client/client.d.ts +0 -27
  65. package/client/client.d.ts.map +0 -1
  66. package/client/style.css +0 -395
@@ -0,0 +1,29 @@
1
+ /**
2
+ * client 半边唯一的「按宿主语言取翻译函数」入口。
3
+ *
4
+ * 为什么单独一个模块:同一段「软读 locale 服务 → 中文用 zh、其余(含服务缺失)用 en →
5
+ * createTranslate」原先在 TaskPanel.tsx(getT)与 slash.ts(translator)各写一份。
6
+ * 语言判据是产品语义而不是某次渲染的局部细节:两份副本各自演化时,面板会中文、
7
+ * `/` 菜单却英文,而且看起来都"正常"。收敛到这里,只保留一个事实。
8
+ *
9
+ * 语义(刻意定死):
10
+ * - 只认 `active === 'zh'`;其它值(en / 未知 / 缺失 locale 服务)一律英文——
11
+ * 与旧实现一致,也不把"未知语言"猜成中文;
12
+ * - `service()` 是软探测,宿主没有 locale 服务时这里不抛错,面板照常渲染英文。
13
+ * @module dsh-project-memory/client/i18n
14
+ */
15
+ import { createTranslate, en, zh } from './locales.ts'
16
+ import { service } from './services.ts'
17
+
18
+ /** 翻译函数签名(key 可能是运行期拼出来的,故不按词典 key 做字面量约束)。 */
19
+ export type Translator = (key: string, params?: Record<string, string | number>) => string
20
+
21
+ /**
22
+ * 当前宿主语言对应的翻译函数。
23
+ * @param ctx - client 上下文(缺失/贫服务宿主也能调用)。
24
+ * @returns 翻译函数;语言服务不可读时退回英文。
25
+ */
26
+ export function translatorFor(ctx: any): Translator {
27
+ const active = service(ctx, 'locale')?.getSnapshot?.()?.active
28
+ return createTranslate(active === 'zh' ? zh : en) as unknown as Translator
29
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 记忆 kind 的展示名(纯函数、零依赖,面板卡片与记忆视图共用)。
3
+ *
4
+ * 为什么单独一个模块:同一份「kind → 词典 key」映射原先在两处各抄一份
5
+ * (TaskComponents.tsx 的 insightKindLabel、MemoryView.tsx 的 kindText,逐字相同)。
6
+ * 新增 kind 时漏改一处,两个界面就会对同一条记忆显示不同的标签;而词典 key 本身
7
+ * 是 locales.ts 的一等公民(`mem.kind.*` 中英两份),映射不该散落在组件里。
8
+ *
9
+ * 语义(刻意定死,边缘输入也用测试钉住):
10
+ * - 四个合法 kind 一律走 `t(key)`,语言切换由词典自己负责;
11
+ * - 其余值**原样返回**(字符串化),绝不回退到某个默认 kind —— 脏数据要让调用方看见;
12
+ * - 用 `hasOwn` 而不是 `map[kind] ?? kind` 查表:`kind: '__proto__'` / `'constructor'`
13
+ * 在对象字面量上会命中原型成员(返回函数/对象),React 渲染对象会直接抛
14
+ * "Objects are not valid as a React child"。非 kind 的键必须当成非法值处理。
15
+ * @module dsh-project-memory/client/kind-label
16
+ */
17
+
18
+ /** kind → 词典 key(唯一一份;与 locales.ts 的 `mem.kind.*` 一一对应)。 */
19
+ export const KIND_LABEL_KEYS = Object.freeze({
20
+ lesson: 'mem.kind.lesson',
21
+ decision: 'mem.kind.decision',
22
+ procedure: 'mem.kind.procedure',
23
+ experience: 'mem.kind.experience',
24
+ })
25
+
26
+ /**
27
+ * 一条记忆的 kind 展示名。
28
+ * @param {unknown} kind - 记忆条目的 kind(可能是缺失/脏值)。
29
+ * @param {any} t - 翻译函数。这里刻意不收窄成 `(key: string) => string`:组件的 t 是
30
+ * `ReturnType<typeof createTranslate>`(key 为词典字面量并集),收窄会让严格模式下的
31
+ * 函数参数逆变检查拒绝调用;key 本身由本模块掌管,调用方只需要"能翻译一个字符串 key"。
32
+ * @returns {string} 本地化后的标签;非法 kind 原样字符串化。
33
+ */
34
+ export function insightKindLabel(kind, t) {
35
+ const key = typeof kind === 'string' && Object.hasOwn(KIND_LABEL_KEYS, kind) ? KIND_LABEL_KEYS[kind] : null
36
+ if (key === null) return String(kind ?? '')
37
+ return t(key)
38
+ }
@@ -34,7 +34,7 @@ export function insightListLine(scope, offset, limit) {
34
34
  }
35
35
 
36
36
  /**
37
- * 追加一页并**按 id 去重**。去重是必需的:前缀重放(见 {@link reloadWindowRequest})与并发
37
+ * 追加一页并**按 id 去重**。去重是必需的:前缀重放(见 MemoryView.loadPrefix)与并发
38
38
  * 刷新都可能让同一 id 出现两次,重复行带重复按钮,点错一个就是误删。
39
39
  * @param {ReadonlyArray<{id?: string}>} prev - 已渲染条目。
40
40
  * @param {ReadonlyArray<{id?: string}>} page - 新到的一页。
@@ -48,19 +48,6 @@ export function appendUnique(prev, page) {
48
48
  return [...prev, ...fresh]
49
49
  }
50
50
 
51
- /**
52
- * 动作(archive/delete/promote…)之后的重载窗口:刷新**已加载的整个前缀**而非重置成第一页(否则
53
- * 会把正在看第 5 页的用户弹回顶部);用 offset 分页而非 keyset 游标正是为了让"把 0..N 重取一遍"
54
- * 可行。**上限**:宿主单页最多 {@link HOST_PAGE_MAX} 条且静默截断,`limit` 在这里夹住,余下的由 `nextOffset` 追加。
55
- * @param {number} loadedCount - 当前已渲染条数。
56
- * @param {number} [pageSize] - 每页条数下界,保证至少取一页。
57
- * @returns {{offset: number, limit: number}} 重放请求窗口(limit ≤ HOST_PAGE_MAX)。
58
- */
59
- export function reloadWindowRequest(loadedCount, pageSize = PAGE_SIZE) {
60
- const count = Number.isFinite(loadedCount) && loadedCount > 0 ? Math.floor(loadedCount) : 0
61
- return { offset: 0, limit: Math.min(HOST_PAGE_MAX, Math.max(pageSize, count)) }
62
- }
63
-
64
51
  /**
65
52
  * 把宿主载荷归一成窗口状态,兼容三种形态:新宿主分页(有 `total` + `nextOffset`)、新宿主不
66
53
  * 分页(省略 limit,`nextOffset === null`)、老宿主/老 bundle(两个字段都没有 → 视为一次给全)。
@@ -16,6 +16,7 @@
16
16
  import {
17
17
  Button, SettingsFormModel, Switch, settingsNumberField,
18
18
  } from '@deepseek-ai/dsh-client-ui-primitives'
19
+ import { service } from './services.ts'
19
20
  import type {
20
21
  SettingsFieldSpec, SettingsFieldState, SettingsFormActions, SettingsFormScope, SettingsFormShell,
21
22
  } from '@deepseek-ai/dsh-client-ui-primitives'
@@ -286,6 +287,14 @@ export function SettingsCard(props: SettingsCardProps) {
286
287
  */
287
288
  export function registerSettingsCard(ctx: any): void {
288
289
  if (typeof ctx?.inject !== 'function') return
290
+ // 没有 configForms = 这个宿主根本没有设置卡片能力(老宿主),静默跳过是正确降级。
291
+ // 但它存在、slots/locale 却缺一个时,嵌套 inject 会永远不回调且不报错——这时必须点名。
292
+ if (service(ctx, 'configForms')) {
293
+ const missing = ['slots', 'configForms', 'locale'].filter((name) => !service(ctx, name))
294
+ if (missing.length) {
295
+ console.warn(`[${SETTINGS_NS}] settings card unavailable: missing client service(s) ${missing.join(', ')}`)
296
+ }
297
+ }
289
298
  try {
290
299
  ctx.inject(['slots', 'configForms', 'locale'], (scope: any) => {
291
300
  try {
@@ -4,8 +4,7 @@
4
4
  * 面板 `closed`/`view` 是浏览器侧状态,直接调 `openView(view)`;也不实现 matchSpace / matchEnter。
5
5
  */
6
6
  import type { ComponentType } from 'react'
7
- import { createTranslate, en, zh } from './locales.ts'
8
- import { service } from './services.ts'
7
+ import { translatorFor, type Translator } from './i18n.ts'
9
8
  import type { PanelView } from './task-ui-store.ts'
10
9
  import { IconChecklistOutline16, IconGlobeOutline16, IconLightOutline16 } from './icons.ts'
11
10
 
@@ -65,16 +64,6 @@ export interface SlashSourceDeps {
65
64
  openView(view: PanelView): void
66
65
  }
67
66
 
68
- /** 翻译函数签名(key 来自 ROWS,不是字面量,故不做类型约束)。 */
69
- type Translate = (key: string, params?: Record<string, string | number>) => string
70
-
71
- /** 按当前语言取翻译函数。 */
72
- function translator(ctx: any): Translate {
73
- // 软探测(services.ts):宿主没有翻译服务时退英文,而不是抛错。
74
- const dict = service(ctx, 'locale')?.getSnapshot?.()?.active === 'zh' ? zh : en
75
- return createTranslate(dict) as unknown as Translate
76
- }
77
-
78
67
  /**
79
68
  * 一轮候选:把三行装配成菜单行,再按查询与位置过滤。
80
69
  * 三行都不接参数(动作全在面板卡片里),所以位置过滤只做一件事:非 leading 位置不弹这一整组
@@ -83,7 +72,7 @@ function translator(ctx: any): Translate {
83
72
  * @param req - 宿主给的候选请求(query / position)。
84
73
  * @returns 菜单行;永不抛出。
85
74
  */
86
- export function buildSlashCandidates(t: Translate, req: any): readonly Record<string, unknown>[] {
75
+ export function buildSlashCandidates(t: Translator, req: any): readonly Record<string, unknown>[] {
87
76
  if (req?.position !== undefined && req.position !== 'leading') return []
88
77
  const query = typeof req?.query === 'string' ? req.query.trim().toLowerCase() : ''
89
78
  const rows = ROWS.map((row) => {
@@ -131,7 +120,7 @@ function consumeSpan(deps: SlashSourceDeps, pick: any): boolean {
131
120
  * @param pick - 宿主给的点击载荷。
132
121
  * @returns PickOutcome;拿不到可用形状时返回 undefined(菜单照常关闭,草稿不动)。
133
122
  */
134
- export function dispatchSlashPick(t: Translate, deps: SlashSourceDeps, pick: any): unknown {
123
+ export function dispatchSlashPick(t: Translator, deps: SlashSourceDeps, pick: any): unknown {
135
124
  const title = pick?.candidate?.name
136
125
  if (typeof title !== 'string' || title === '') return undefined
137
126
  const row = ROWS.find((candidate) => t(candidate.labelKey) === title)
@@ -152,7 +141,7 @@ export function dispatchSlashPick(t: Translate, deps: SlashSourceDeps, pick: any
152
141
  * @returns 触发器源;只依赖宿主的公开契约字段。
153
142
  */
154
143
  export function createSlashSource(ctx: any, deps: SlashSourceDeps): Record<string, unknown> {
155
- const t = translator(ctx)
144
+ const t = translatorFor(ctx)
156
145
  return {
157
146
  trigger: '/',
158
147
  name: SLASH_SOURCE_NAME,
@@ -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}` }