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

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 (43) hide show
  1. package/CHANGELOG.md +162 -8
  2. package/README.md +44 -26
  3. package/README.zh-CN.md +42 -24
  4. package/client/client.js +272 -138
  5. package/client/client.js.map +1 -1
  6. package/cordis.patch.yml +6 -1
  7. package/package.json +3 -2
  8. package/scripts/bench-synthetic.mjs +22 -11
  9. package/src/audit.js +36 -32
  10. package/src/auto-inject.js +55 -32
  11. package/src/client/MemoryView.tsx +72 -4
  12. package/src/client/ShowTaskPanelNode.tsx +8 -5
  13. package/src/client/TaskCommandNode.tsx +22 -17
  14. package/src/client/TaskComponents.tsx +18 -3
  15. package/src/client/TaskPanel.tsx +50 -85
  16. package/src/client/client.ts +26 -6
  17. package/src/client/commands.ts +67 -0
  18. package/src/client/task-ui-store.ts +15 -2
  19. package/src/commands/insight-actions.js +1 -1
  20. package/src/commands/task-actions.js +57 -3
  21. package/src/commands/tasks.js +1 -1
  22. package/src/index.js +29 -11
  23. package/src/insight-store.js +200 -78
  24. package/src/lazy.js +7 -3
  25. package/src/ops.js +1 -1
  26. package/src/readiness.js +1 -1
  27. package/src/recall.js +76 -30
  28. package/src/setup/taskbridge.js +37 -6
  29. package/src/store.js +315 -44
  30. package/src/tools/forget.js +11 -8
  31. package/src/tools/index-doc.js +14 -8
  32. package/src/tools/index-repo.js +10 -11
  33. package/src/tools/lesson-tools.js +25 -35
  34. package/src/tools/query-memory.js +81 -28
  35. package/src/tools/remember.js +14 -11
  36. package/src/tools/stats.js +26 -3
  37. package/src/tools/task-tools.js +11 -12
  38. package/src/tools/watch-repo.js +6 -8
  39. package/src/types.js +9 -4
  40. package/src/util/fs.js +502 -37
  41. package/src/util/search.js +6 -27
  42. package/src/vector-index.js +175 -22
  43. package/src/watch.js +15 -10
@@ -164,7 +164,14 @@ export function MiniBar({ label, hint, showHints, position, theme, onMove, open
164
164
  style={{ left: position.x, top: position.y }}
165
165
  data-theme={theme === 'native' ? undefined : theme}
166
166
  onMouseDown={onMouseDown}
167
+ onKeyDown={(e) => {
168
+ if (e.key === 'Enter' || e.key === ' ') {
169
+ e.preventDefault()
170
+ open()
171
+ }
172
+ }}
167
173
  role="button"
174
+ tabIndex={0}
168
175
  title={showHints ? hint : undefined}
169
176
  aria-label={hint}
170
177
  >
@@ -244,7 +251,7 @@ export function TaskCard({
244
251
  if (headClickTimer.current !== null) window.clearTimeout(headClickTimer.current)
245
252
  }, [])
246
253
 
247
- const handleHeadClick = (e: React.MouseEvent<HTMLButtonElement>) => {
254
+ const handleHeadClick = (e: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) => {
248
255
  if (suppressHeadClick.current) {
249
256
  // 上一次 mousedown 落在标题编辑框内(失焦提交产生),吞掉这次点击,不切换展开
250
257
  suppressHeadClick.current = false
@@ -269,9 +276,17 @@ export function TaskCard({
269
276
 
270
277
  return (
271
278
  <article data-task-id={task.id} className={`${css.card}${isBound ? ` ${css.cardBound}` : ''}`}>
272
- <button
279
+ <div
273
280
  className={css.cardHead}
281
+ role="button"
282
+ tabIndex={0}
274
283
  onClick={handleHeadClick}
284
+ onKeyDown={(e) => {
285
+ if (e.key === 'Enter' || e.key === ' ') {
286
+ e.preventDefault()
287
+ handleHeadClick(e)
288
+ }
289
+ }}
275
290
  onMouseDownCapture={() => {
276
291
  // 标题编辑中,点击卡片头任意处都会先失焦提交;标记该次点击以在 onClick 中吞掉,
277
292
  // 避免“改名提交一下、卡片又收起/展开一下”的误切换。
@@ -311,7 +326,7 @@ export function TaskCard({
311
326
  <span className={css.updated}>{timeAgo(task.updatedAt || task.lastActiveAt)}</span>
312
327
  <span className={css.chevron}>{expanded ? <IconChevronUpOutline14 /> : <IconChevronDownOutline14 />}</span>
313
328
  </div>
314
- </button>
329
+ </div>
315
330
  {steps.length > 0 && (
316
331
  <div className={css.track}>
317
332
  <div className={css.trackFill} style={{ width: `${pct}%` }} />
@@ -13,8 +13,9 @@ import {
13
13
  IconQuestionOutline14,
14
14
  } from './icons.ts'
15
15
  import { createTranslate, zh, en } from './locales.ts'
16
+ import { invokeCommand } from './commands.ts'
16
17
  import { missingServices, service } from './services.ts'
17
- import { useTaskData, useTaskDataActions, parseTaskPayloadText, type TaskStep } from './task-data-store.ts'
18
+ import { useTaskData, useTaskDataActions, parseTaskPayloadText } from './task-data-store.ts'
18
19
  import { useTaskUI, useTaskUIActions, PANEL_VIEWS } from './task-ui-store.ts'
19
20
  import { MiniBar, TaskCard } from './TaskComponents.tsx'
20
21
  import { MemoryView, type InsightScope } from './MemoryView.tsx'
@@ -78,6 +79,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
78
79
  const degraded = missingServices(ctx)
79
80
  const sessionId = useSessionId(ctx)
80
81
  const [syncing, setSyncing] = useState(false)
82
+ const syncingRef = useRef(false)
81
83
  const [syncedAt, setSyncedAt] = useState(0)
82
84
  const [syncError, setSyncError] = useState<string | null>(null)
83
85
  // 提示信息开关落在 UI store(持久化):关掉后面板内所有悬停 title 气泡都不再弹出。
@@ -109,28 +111,25 @@ function TaskPanelView({ ctx }: { ctx: any }) {
109
111
  }
110
112
 
111
113
  const runLine = async (line: string): Promise<boolean> => {
112
- // 软探测(services.ts):`remote.commands` 是**独立注册的扁平服务**,必须按整名读;
113
- // `ctx.remote.commands` 走属性路径,会被 inject 门控挡下(本插件顶层 inject 为空)。
114
- const commands = service(ctx, 'remote.commands')
115
- if (!sessionId || !commands || typeof commands.execute !== 'function') {
116
- setSyncError(t('panel.no-channel'))
114
+ const result = await invokeCommand(ctx, sessionId, line)
115
+ if (!result.ok) {
116
+ setSyncError(result.error === 'no-channel' ? t('panel.no-channel') : (result.error || t('panel.sync-failed')))
117
117
  return false
118
118
  }
119
- let response: any
119
+ return applyPayload(result.text)
120
+ }
121
+
122
+ // 锁用 ref 而不是渲染快照里的 state:同一 tick 的两次触发也能被挡住。
123
+ const withLock = async (fn: () => Promise<unknown>): Promise<void> => {
124
+ if (syncingRef.current) return
125
+ syncingRef.current = true
126
+ setSyncing(true)
120
127
  try {
121
- response = await commands.execute(sessionId, line, [])
122
- } catch (err) {
123
- setSyncError(String((err as { message?: unknown } | null | undefined)?.message ?? err))
124
- return false
125
- }
126
- const envelope = response as { ok?: boolean; value?: any } | null | undefined
127
- const execution = envelope && typeof envelope === 'object' && 'value' in envelope ? envelope.value : envelope
128
- const result = execution?.result ?? execution
129
- if (result?.kind === 'error') {
130
- setSyncError(result.text ?? 'command error')
131
- return false
128
+ await fn()
129
+ } finally {
130
+ syncingRef.current = false
131
+ setSyncing(false)
132
132
  }
133
- return applyPayload(result?.text)
134
133
  }
135
134
 
136
135
  /**
@@ -145,51 +144,27 @@ function TaskPanelView({ ctx }: { ctx: any }) {
145
144
  * 它们各自会推宿主清单(adoptStepsToSession),不需要巡检式补写。
146
145
  */
147
146
  const refresh = async (): Promise<void> => {
148
- if (syncing) return
149
- setSyncing(true)
150
- try {
151
- await runLine('/tasks')
152
- } finally {
153
- setSyncing(false)
154
- }
147
+ await withLock(() => runLine('/tasks'))
155
148
  }
156
149
 
157
150
  const handleAction = async (verb: 'switch' | 'archive', taskId: string): Promise<void> => {
158
- if (syncing) return
159
- setSyncing(true)
160
- try {
161
- await runLine(`/tasks ${verb} ${taskId}`)
162
- } finally {
163
- setSyncing(false)
164
- }
151
+ await withLock(() => runLine(`/tasks ${verb} ${taskId}`))
165
152
  }
166
153
 
167
154
  // v0.5:任务卡内联记忆动作(confirm/promote/delete 于 /insight task 层),随后刷新任务数据
168
155
  const handleInsightTask = async (action: 'confirm' | 'promote' | 'delete', id: string): Promise<void> => {
169
- if (syncing) return
170
- setSyncing(true)
171
- try {
156
+ await withLock(async () => {
172
157
  await runLine(`/tasks insight ${action} task ${id}`)
173
- await refresh()
174
- } finally {
175
- setSyncing(false)
176
- }
177
- }
178
-
179
- const pushSteps = (taskId: string, steps: TaskStep[]): void => {
180
- void runLine(`/tasks todos ${JSON.stringify(steps.map((s) => ({ content: s.content, status: s.status })))}`)
158
+ await runLine('/tasks')
159
+ })
181
160
  }
182
161
 
183
162
  const cycleStatus = (taskId: string, index: number) => {
184
163
  const task = data.tasks.find((tt) => tt.id === taskId)
185
164
  if (!task) return
186
- const steps = task.steps || []
187
- const next = steps.map((s, i) => {
188
- if (i !== index) return s
189
- const cur = STATUS_CYCLE.indexOf(s.status)
190
- return { ...s, status: STATUS_CYCLE[(cur + 1) % STATUS_CYCLE.length] }
191
- })
192
- pushSteps(taskId, next)
165
+ const cur = STATUS_CYCLE.indexOf((task.steps || [])[index]?.status as (typeof STATUS_CYCLE)[number])
166
+ const next = STATUS_CYCLE[(cur + 1) % STATUS_CYCLE.length]
167
+ void withLock(() => runLine(`/tasks step ${taskId} ${index} ${next}`))
193
168
  }
194
169
 
195
170
  const commitStepText = (taskId: string, index: number, value: string) => {
@@ -198,19 +173,15 @@ function TaskPanelView({ ctx }: { ctx: any }) {
198
173
  if (!task) return
199
174
  const same = (task.steps || [])[index]?.content === trimmed
200
175
  if (same || !trimmed) return
201
- const next = (task.steps || []).map((s, i) => (i === index ? { ...s, content: trimmed } : s))
202
- pushSteps(taskId, next)
176
+ void withLock(() => runLine(`/tasks step-text ${taskId} ${index} ${JSON.stringify(trimmed)}`))
203
177
  }
204
178
 
205
179
  const reorderSteps = (taskId: string, fromIndex: number, toIndex: number) => {
206
180
  if (fromIndex === toIndex) return
207
181
  const task = data.tasks.find((tt) => tt.id === taskId)
208
182
  if (!task) return
209
- const steps = [...(task.steps || [])]
210
- const [moved] = steps.splice(fromIndex, 1)
211
- const targetIndex = toIndex > fromIndex ? toIndex - 1 : toIndex
212
- steps.splice(targetIndex, 0, moved)
213
- pushSteps(taskId, steps)
183
+ // 服务端按拖拽的 from/to 自己算落点;这里不再回写整份数组。
184
+ void withLock(() => runLine(`/tasks step-move ${taskId} ${fromIndex} ${toIndex}`))
214
185
  }
215
186
 
216
187
  const commitTitle = (taskId: string, value: string) => {
@@ -219,12 +190,12 @@ function TaskPanelView({ ctx }: { ctx: any }) {
219
190
  if (!task) return
220
191
  const same = task.title === trimmed
221
192
  if (same || !trimmed) return
222
- void runLine(`/tasks rename ${taskId} ${JSON.stringify(trimmed)}`)
193
+ void withLock(() => runLine(`/tasks rename ${taskId} ${JSON.stringify(trimmed)}`))
223
194
  }
224
195
 
225
196
  const expand = () => {
226
197
  uiActions.open()
227
- if (Date.now() - Math.max(data.lastUpdate, syncedAt) > 30_000) {
198
+ if (Date.now() - Math.max(data.lastUpdate, syncedAt) > 5_000) {
228
199
  void refresh()
229
200
  }
230
201
  }
@@ -239,6 +210,9 @@ function TaskPanelView({ ctx }: { ctx: any }) {
239
210
 
240
211
  const panelRef = useRef<HTMLDivElement>(null)
241
212
  const drag = useRef<{ dx: number; dy: number } | null>(null)
213
+ // 拖动期间位置只进本地 state;mouseup 才写 UI store(否则每个 mousemove 都同步写 localStorage)。
214
+ const [dragPos, setDragPos] = useState<{ x: number; y: number } | null>(null)
215
+ const dragPosRef = useRef<{ x: number; y: number } | null>(null)
242
216
 
243
217
  const handleDragStart = (e: React.MouseEvent) => {
244
218
  if (e.target !== e.currentTarget) return
@@ -251,40 +225,31 @@ function TaskPanelView({ ctx }: { ctx: any }) {
251
225
  const height = panelRef.current?.offsetHeight ?? 480
252
226
  const x = Math.max(8, Math.min(window.innerWidth - width - 8, ev.clientX - drag.current.dx))
253
227
  const y = Math.max(8, Math.min(window.innerHeight - 64, ev.clientY - drag.current.dy))
254
- uiActions.setPanelPosition({ x, y })
228
+ dragPosRef.current = { x, y }
229
+ setDragPos({ x, y })
255
230
  }
256
231
  const onUp = () => {
257
232
  drag.current = null
258
233
  window.removeEventListener('mousemove', onMove)
259
234
  window.removeEventListener('mouseup', onUp)
235
+ if (dragPosRef.current) uiActions.setPanelPosition(dragPosRef.current)
236
+ dragPosRef.current = null
237
+ setDragPos(null)
260
238
  }
261
239
  window.addEventListener('mousemove', onMove)
262
240
  window.addEventListener('mouseup', onUp)
263
241
  }
264
242
 
265
- // 会话切换时仅同步数据,不自动打开面板
243
+ // 只在面板打开、或切回任务页时补一次数据;切到记忆页不发任务命令。
244
+ // 命令节点本身由 TaskCommandNode 隐藏,所以这次补数据不会在对话里留下可见行;
245
+ // 但切回任务页必须刷新,否则刚在记忆页确认/提升的草稿状态会一直显示旧值。
246
+ const refreshRef = useRef<() => void>(() => {})
247
+ refreshRef.current = () => { void refresh() }
266
248
  useEffect(() => {
267
- if (!sessionId) return
268
- // 仅当面板已打开时才自动刷新
269
- if (!ui.closed) {
270
- void refresh()
271
- }
272
- }, [sessionId])
273
-
274
- // 监听模型工具请求打开面板
275
- useEffect(() => {
276
- const ctxWithEvents = ctx
277
- const handler = () => {
278
- uiActions.open()
279
- if (Date.now() - Math.max(data.lastUpdate, syncedAt) > 30_000) {
280
- void refresh()
281
- }
282
- }
283
- ctxWithEvents?.events?.on?.('dsh:task-panel:show', handler)
284
- return () => {
285
- ctxWithEvents?.events?.off?.('dsh:task-panel:show', handler)
286
- }
287
- }, [ctx, uiActions, data.lastUpdate, syncedAt, refresh])
249
+ if (ui.closed || !sessionId || ui.view !== 'task') return
250
+ if (Date.now() - Math.max(data.lastUpdate, syncedAt) < 5_000) return
251
+ refreshRef.current()
252
+ }, [ui.closed, ui.view, sessionId])
288
253
 
289
254
  // 彻底隐藏:不渲染任何东西
290
255
  if (ui.closed) {
@@ -320,7 +285,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
320
285
  <div
321
286
  className={css.panel}
322
287
  ref={panelRef}
323
- style={{ left: ui.panelPosition.x, top: ui.panelPosition.y }}
288
+ style={{ left: (dragPos ?? ui.panelPosition).x, top: (dragPos ?? ui.panelPosition).y }}
324
289
  data-theme={style === 'native' ? undefined : style}
325
290
  >
326
291
  <div className={css.dragHandle} onMouseDown={handleDragStart} title={showHints ? t('task.drag') : undefined}>
@@ -417,7 +382,7 @@ function TaskPanelView({ ctx }: { ctx: any }) {
417
382
  {syncError && <div className={css.notice}>{t('panel.sync-failed')}: {syncError}</div>}
418
383
 
419
384
  {view !== 'task' ? (
420
- <MemoryView ctx={ctx} sessionId={sessionId} scope={view as InsightScope} boundTaskId={data.boundTaskId} showHints={showHints} t={t} />
385
+ <MemoryView ctx={ctx} sessionId={sessionId} scope={view as InsightScope} root={data.root ?? null} boundTaskId={data.boundTaskId} showHints={showHints} t={t} />
421
386
  ) : activeTasks.length === 0 ? (
422
387
  <div className={css.emptyState}>
423
388
  <p className={css.emptyTitle}>{t('panel.empty')}</p>
@@ -89,13 +89,33 @@ function registerSlashSource(ctx: any): void {
89
89
  * @param ctx - client 根上下文
90
90
  */
91
91
  function registerTaskPanel(ctx: any): void {
92
- const mount = (slots: any): void => {
92
+ const mount = (slots: any, effect?: (fn: () => () => void) => void): void => {
93
93
  if (!slots || typeof slots.inject !== 'function') {
94
94
  console.warn(`[${NS}] host has no slots service — task panel disabled`)
95
95
  return
96
96
  }
97
+ // 每个 register 都挂到 effect 上:HMR/禁用再启用时先释放旧注册,否则同 id 重复注册会抛。
98
+ const keep = (off: unknown): void => {
99
+ if (typeof off !== 'function') return
100
+ const dispose = () => {
101
+ try {
102
+ off()
103
+ } catch {
104
+ // 宿主已经拆掉这个槽:忽略
105
+ }
106
+ }
107
+ if (typeof effect === 'function') effect(() => dispose)
108
+ }
109
+ const register = (spec: object, component: any): void => {
110
+ try {
111
+ keep(slots.register(spec, component))
112
+ } catch (err) {
113
+ console.warn(`[${NS}] slot registration failed:`, err)
114
+ }
115
+ }
116
+
97
117
  try {
98
- slots.inject('shell.overlay', () => slots.register(
118
+ slots.inject('shell.overlay', () => register(
99
119
  {
100
120
  name: 'shell.overlay',
101
121
  id: 'dsh-project-memory-task-panel',
@@ -109,7 +129,7 @@ function registerTaskPanel(ctx: any): void {
109
129
  // 合并后只剩一条用户命令 /tasks(子动词都记在同一个命令名下)。
110
130
  const nodeKeys = ['tasks']
111
131
  for (const key of nodeKeys) {
112
- slots.inject('conversation.chat.commandview', () => slots.register(
132
+ slots.inject('conversation.chat.commandview', () => register(
113
133
  { name: 'conversation.chat.commandview', key },
114
134
  TaskCommandNode
115
135
  ))
@@ -118,7 +138,7 @@ function registerTaskPanel(ctx: any): void {
118
138
  // 工具调用视图:`show_task_panel` 的唯一实际效果就是开面板,而面板状态在浏览器侧;
119
139
  // 宿主进程碰不到它(宿主契约里 `ToolRunContext` 没有 `ctx`)。认领这个**工具名**后,
120
140
  // 工具结果一渲染就把面板打开 —— 见 ShowTaskPanelNode.tsx。
121
- registerShowTaskPanelView(slots)
141
+ registerShowTaskPanelView(slots, keep)
122
142
  } catch (err) {
123
143
  console.warn(`[${NS}] task panel registration failed:`, err)
124
144
  }
@@ -126,13 +146,13 @@ function registerTaskPanel(ctx: any): void {
126
146
 
127
147
  if (typeof ctx?.inject === 'function') {
128
148
  try {
129
- ctx.inject(['slots'], (scope: any) => mount(scope?.slots ?? service(ctx, 'slots')))
149
+ ctx.inject(['slots'], (scope: any) => mount(scope?.slots ?? service(ctx, 'slots'), scope?.effect))
130
150
  return
131
151
  } catch (err) {
132
152
  console.warn(`[${NS}] slots injection failed:`, err)
133
153
  }
134
154
  }
135
- mount(service(ctx, 'slots'))
155
+ mount(service(ctx, 'slots'), typeof ctx?.effect === 'function' ? ctx.effect.bind(ctx) : undefined)
136
156
  }
137
157
 
138
158
  /**
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 客户端命令调用层:所有 `remote.commands.execute` 只走这里。
3
+ *
4
+ * 三件事必须集中在一处,否则每个调用点都会各漏一项:
5
+ * - 超时/取消(宿主 RPC 不返回时不能把面板永久锁死);
6
+ * - 信封解析(宿主 `{ok:false,error}` 与 `{ok:true,value}` 是两种形状);
7
+ * - 错误归一(调用点只关心 ok/text/error,不重复猜)。
8
+ */
9
+ import { service } from './services.ts'
10
+
11
+ export interface InvokeResult {
12
+ ok: boolean
13
+ text: string
14
+ error?: string
15
+ }
16
+
17
+ function errorText(value: unknown): string {
18
+ if (typeof value === 'string') return value
19
+ if (value && typeof value === 'object') {
20
+ const record = value as { message?: unknown; code?: unknown }
21
+ if (typeof record.message === 'string' && record.message) return record.message
22
+ if (typeof record.code === 'string' && record.code) return record.code
23
+ }
24
+ return ''
25
+ }
26
+
27
+ /**
28
+ * 执行一条 `/tasks` 命令。
29
+ * @param ctx client 上下文(服务一律软探测)
30
+ * @param sessionId 当前会话;为空表示没有可用数据通道
31
+ * @param line 完整命令行(以 `/tasks` 开头)
32
+ * @param timeoutMs 超时;到点 abort,调用方拿到可重试的错误态
33
+ */
34
+ export async function invokeCommand(
35
+ ctx: any,
36
+ sessionId: string | null,
37
+ line: string,
38
+ timeoutMs = 15_000,
39
+ ): Promise<InvokeResult> {
40
+ const commands = service(ctx, 'remote.commands')
41
+ if (!sessionId || !commands || typeof commands.execute !== 'function') {
42
+ return { ok: false, text: '', error: 'no-channel' }
43
+ }
44
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
45
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
46
+ try {
47
+ const response = await commands.execute(sessionId, line, [], controller?.signal)
48
+ const envelope = response && typeof response === 'object' ? response as { ok?: boolean; value?: any; error?: unknown } : null
49
+ if (envelope && envelope.ok === false) {
50
+ return { ok: false, text: '', error: errorText(envelope.error) || 'command rejected' }
51
+ }
52
+ const execution = envelope && 'value' in envelope ? envelope.value : envelope
53
+ if (execution === undefined || execution === null) {
54
+ return { ok: false, text: '', error: 'unknown or malformed command' }
55
+ }
56
+ const result = execution.result ?? execution
57
+ if (result?.kind === 'error') {
58
+ return { ok: false, text: '', error: String(result.text ?? 'command error') }
59
+ }
60
+ return { ok: true, text: typeof result?.text === 'string' ? result.text : '' }
61
+ } catch (err) {
62
+ const aborted = controller?.signal.aborted === true
63
+ return { ok: false, text: '', error: aborted ? 'command timed out' : String((err as { message?: unknown } | null | undefined)?.message ?? err) }
64
+ } finally {
65
+ if (timer !== null) clearTimeout(timer)
66
+ }
67
+ }
@@ -43,6 +43,19 @@ function defaultPosition(): { x: number; y: number } {
43
43
  return { x: 0, y: 0 }
44
44
  }
45
45
 
46
+ /** 位置必须留在视口内:换小屏/拔掉外接屏后,持久化的坐标可能已经看不见。 */
47
+ function clampPosition(value: unknown): { x: number; y: number } {
48
+ if (typeof window === 'undefined') return defaultPosition()
49
+ const pos = value as { x?: unknown; y?: unknown } | null | undefined
50
+ const x = Number(pos?.x)
51
+ const y = Number(pos?.y)
52
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return defaultPosition()
53
+ return {
54
+ x: Math.max(8, Math.min(x, window.innerWidth - 80)),
55
+ y: Math.max(8, Math.min(y, window.innerHeight - 40)),
56
+ }
57
+ }
58
+
46
59
  /**
47
60
  * 启动时的初始状态:
48
61
  * - closed 恒为 true(不读取 localStorage 的 closed),刷新后面板隐藏;
@@ -56,7 +69,7 @@ function getDefaultUIState(): TaskUIState {
56
69
  const parsed = JSON.parse(saved)
57
70
  return {
58
71
  expandedTaskIds: Array.isArray(parsed.expandedTaskIds) ? parsed.expandedTaskIds : [],
59
- panelPosition: parsed.panelPosition ?? defaultPosition(),
72
+ panelPosition: clampPosition(parsed.panelPosition),
60
73
  minimized: parsed.minimized !== false,
61
74
  closed: true,
62
75
  theme: typeof parsed.theme === 'string' ? parsed.theme : 'native',
@@ -114,7 +127,7 @@ export const taskUIStore = {
114
127
  setUIState({ ...uiState, expandedTaskIds: taskIds })
115
128
  },
116
129
  setPanelPosition(pos: { x: number; y: number }): void {
117
- setUIState({ ...uiState, panelPosition: pos })
130
+ setUIState({ ...uiState, panelPosition: clampPosition(pos) })
118
131
  },
119
132
  open(): void {
120
133
  setUIState({ ...uiState, minimized: false, closed: false })
@@ -396,7 +396,7 @@ export function insightCommandDefinition(config, ctx) {
396
396
  const { cwd } = invocationContext(invocation)
397
397
  const lineRaw = (invocation?.rawInput || '').trim()
398
398
  const raw = lineRaw.split(/\s+/).filter(Boolean)
399
- const root = projectRootFor(cwd)
399
+ const root = projectRootFor(cwd, config)
400
400
  if (!root) return { kind: 'error', text: NO_PROJECT_ROOT_NOTE }
401
401
  if (!raw[0]) return { kind: 'error', text: '[insight] 用法见面板' }
402
402
  const verb = raw[0]
@@ -7,7 +7,7 @@ import { renderTaskSnapshot, buildTaskPayload } from './tasks.js'
7
7
  import { fireReflect } from '../reflection-pipeline.js'
8
8
  import { resolveRoute } from '../llm-route.js'
9
9
  import { fencedJson, invocationContext } from './invocation.js'
10
- import { stepContent, stepProgress, stepStatus } from '../util/task-view.js'
10
+ import { STEP_STATUSES, stepContent, stepProgress, stepStatus } from '../util/task-view.js'
11
11
 
12
12
  function describeTask(t) {
13
13
  const { done, total } = stepProgress(t)
@@ -36,7 +36,7 @@ function withTaskSnapshot(config, cwd, sid, store, note) {
36
36
  const active = tasks.filter((t) => !t.archived)
37
37
  const archived = tasks.length - active.length
38
38
  const boundId = sid ? store.getBoundTaskId(sid) : null
39
- const root = projectRootFor(cwd)
39
+ const root = projectRootFor(cwd, config)
40
40
  const human = `项目 ${root}\n${note}\n任务: ${active.length} 套${archived ? `(归档 ${archived})` : ''}`
41
41
  const payload = buildTaskPayload(active, boundId, archived, root)
42
42
  return { kind: 'success', text: fencedJson(human, payload) }
@@ -73,7 +73,7 @@ export function taskCommandDefinition(config, ctx) {
73
73
  }
74
74
  return snap
75
75
  }
76
- if (!['unbind', 'todos', 'rename'].includes(verb) && (!taskId || rest.length)) {
76
+ if (!['unbind', 'todos', 'rename', 'step', 'step-move', 'step-text'].includes(verb) && (!taskId || rest.length)) {
77
77
  return { kind: 'error', text: '[task] 用法: /task switch|archive <任务id> | unbind' }
78
78
  }
79
79
  const { root, store } = taskStoreFor(cwd, config)
@@ -90,6 +90,58 @@ export function taskCommandDefinition(config, ctx) {
90
90
  return withTaskSnapshot(config, cwd, sid, store, note)
91
91
  }
92
92
 
93
+ // 单步原子写:客户端不再回写整份 steps,避免两个并发动作互相覆盖。
94
+ if (verb === 'step' || verb === 'step-move' || verb === 'step-text') {
95
+ if (!taskId) return { kind: 'error', text: `[task] ${verb} 需要任务 id` }
96
+ const task = store.getTask(taskId)
97
+ if (!task) return { kind: 'error', text: `[task] 找不到任务: ${taskId}` }
98
+ if (!Array.isArray(task.steps)) task.steps = []
99
+ if (verb === 'step') {
100
+ const index = Number(rest[0])
101
+ const status = rest[1]
102
+ if (!Number.isInteger(index) || !STEP_STATUSES.has(status) || !task.steps[index]) {
103
+ return { kind: 'error', text: '[task] step 需要 <index> <pending|in_progress|completed>' }
104
+ }
105
+ const prev = task.steps[index]
106
+ task.steps[index] = {
107
+ ...(prev && typeof prev === 'object' ? prev : { content: stepContent(prev) }),
108
+ status,
109
+ }
110
+ } else if (verb === 'step-move') {
111
+ const from = Number(rest[0])
112
+ 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' }
115
+ }
116
+ const [moved] = task.steps.splice(from, 1)
117
+ const target = to > from ? to - 1 : to
118
+ task.steps.splice(Math.max(0, Math.min(target, task.steps.length)), 0, moved)
119
+ } else {
120
+ const index = Number(rest[0])
121
+ const payload = restAfter(raw, 3).trim()
122
+ let content = payload
123
+ try {
124
+ const parsed = JSON.parse(payload)
125
+ if (typeof parsed === 'string') content = parsed
126
+ } catch { /* 非 JSON 时按原样取 payload */ }
127
+ if (!Number.isInteger(index) || !task.steps[index] || !content.trim()) {
128
+ return { kind: 'error', text: '[task] step-text 需要 <index> <json文本>' }
129
+ }
130
+ const prev = task.steps[index]
131
+ task.steps[index] = {
132
+ ...(prev && typeof prev === 'object' ? prev : { content: stepContent(prev) }),
133
+ content: content.trim(),
134
+ }
135
+ }
136
+ const now = new Date().toISOString()
137
+ task.updatedAt = now
138
+ task.lastActiveAt = now
139
+ store.markTasksDirty()
140
+ store.save()
141
+ if (shouldAdoptToHost(config)) adoptStepsToSession(session, task)
142
+ return withTaskSnapshot(config, cwd, sid, store, `已更新「${task.title}」步骤`)
143
+ }
144
+
93
145
  // /task rename <任务id> <json标题> —— 双击任务标题改名
94
146
  if (verb === 'rename') {
95
147
  if (!taskId) return { kind: 'error', text: '[task] rename 需要任务 id(由卡片双击调用)' }
@@ -178,6 +230,8 @@ export function taskCommandDefinition(config, ctx) {
178
230
  if (task.archived) return { kind: 'error', text: `[task] 已归档: ${task.title}` }
179
231
  task.archived = true
180
232
  task.updatedAt = new Date().toISOString()
233
+ // 归档 = 停止续做:绑定一并清掉,否则 binding.json 会永久指向这条已归档任务。
234
+ store.removeBindingsForTask(task.id)
181
235
  store.markTasksDirty()
182
236
  store.save()
183
237
  // 反思钩子:归档即收割(默认关)
@@ -32,7 +32,7 @@ export function buildTaskPayload(tasks, boundId, archived, root = null) {
32
32
  * 任务动作命令复用同一函数,面板只需解析尾部 JSON 即可刷新。
33
33
  */
34
34
  export function renderTaskSnapshot(config, cwd, sid) {
35
- const root = projectRootFor(cwd)
35
+ const root = projectRootFor(cwd, config)
36
36
  if (!root) return { kind: 'error', text: NO_PROJECT_ROOT_NOTE }
37
37
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
38
38
  const tasks = store.getTasks()
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import Schema from '@deepseek-ai/schemastery'
2
- import { DEFAULT_SCAN_DEPTH, DEFAULT_SCAN_FILES, isUnsafeRoot } from './util/fs.js'
2
+ import { DEFAULT_SCAN_DEPTH, DEFAULT_SCAN_FILES, assertSafeRoot } from './util/fs.js'
3
3
  import { indexDocTool } from './tools/index-doc.js'
4
4
  import { indexRepoTool, indexRepository } from './tools/index-repo.js'
5
5
  import { queryMemoryTool } from './tools/query-memory.js'
@@ -45,9 +45,18 @@ export const Config = Schema.object({
45
45
  watch: Schema.boolean().default(true),
46
46
  watchInterval: Schema.number().default(30),
47
47
  // 危险根护栏(issue #5):家目录 / 文件系统根 / 系统目录 / 包管理器前缀(/opt/homebrew …)
48
- // 整体扫描会吃满内存,默认一律拒绝。懒索引、会话审计、任务桥在这类目录里始终零副作用;
49
- // `autoIndexOnFirstUse` 不在此列——本开关同样放行它。其余只放开**显式**带 root 的工具调用。
48
+ // 整体扫描会吃满内存,默认一律拒绝(懒索引、会话审计、任务桥默认零副作用)。
49
+ // `roots.*` 是机器/配置档级的例外表(精确匹配的 allow/deny,子树级前缀的 exclude);
50
+ // `allowUnsafeRoots` 保留为兼容,只放开内置名单,deny / exclude 仍然优先。
50
51
  allowUnsafeRoots: Schema.boolean().default(false),
52
+ roots: Schema.object({
53
+ // 即使在内置名单里也允许作根。精确匹配;文件系统根不在可放行之列。
54
+ allow: Schema.array(Schema.string()).default([]),
55
+ // 这个目录不能当根。精确匹配:子目录仍可各自成根。
56
+ deny: Schema.array(Schema.string()).default([]),
57
+ // 这棵子树里的文件一律不进索引(前缀匹配,含子目录)。
58
+ exclude: Schema.array(Schema.string()).default([]),
59
+ }).default({}),
51
60
  // 单次扫描上限。超过即截断(并跳过"删除本轮未见到条目"的清理,避免把没扫到的文件误删)。
52
61
  // **不可取消**:0 / 负数 / 非数值一律回落默认值(见 util/fs.js 的 scanLimits)。
53
62
  maxScanFiles: Schema.number().default(DEFAULT_SCAN_FILES),
@@ -69,6 +78,7 @@ export const Config = Schema.object({
69
78
  // 但走 cordis.patch.yml 时能不能活到代码取决于宿主是否按「not a declared property」校验
70
79
  // ——无论哪种,文档里的旋钮与 Schema 已经不一致,等于半真半假。默认值以 cfgInsight 的
71
80
  // 兜底值为权威,这里只负责把键暴露出来。
81
+ // 向量带的两条阈值;`0` = 关闭对应那条带(不设 ≠ 0,默认值仍是 0.9 / 0.7)。
72
82
  autoMergeCos: Schema.number().default(0.9),
73
83
  autoMergeMargin: Schema.number().default(0.05),
74
84
  hintCos: Schema.number().default(0.7),
@@ -135,7 +145,18 @@ export const Config = Schema.object({
135
145
  vectorDir: Schema.string(),
136
146
  // 融合权重 (1-α)·BM25归一 + α·余弦。实测**小 k** 上 α=0.5 最优(k=3 64% vs 58%、k=5 69% vs 67%,
137
147
  // α=0.75 时 k=5 到 72%),而 α=1(纯向量)明显更差(hit@10 53% vs 81%)——所以默认 0.5 不是 1。
148
+ // `0` = 关掉重排(连模型都不加载)。它**只**管重排:写入侧去重看 `vectorDedup`。
138
149
  vectorAlpha: Schema.number().default(0.5),
150
+ // 写入侧近重复检测(0.9 自动覆盖 / 0.7 近邻提示)的独立开关。默认开;关掉只影响写入,
151
+ // 不影响召回排序。与 `vectorAlpha` 分开是因为两者是两件事:一个是排序权重,一个是数据写入行为。
152
+ vectorDedup: Schema.boolean().default(true),
153
+ // ⚠ 两个**实验性**旋钮:没有可发布的默认值,所以不设就不启用(不设 ≠ 0)。
154
+ // itemMin —— 提示通道的条目级余弦地板(低于它不进提示通道)
155
+ // speakMin —— 通道级"语义救援"阈值(层内最高余弦够高时,本轮免于被 hintMinSupport 静音)
156
+ // 两者都在真实交付上量过分辨力(结论见 src/auto-inject.js 的 scoreHints 注释:**证据不足**),
157
+ // 留在这里是为了能在真实数据上复现那组 A/B,而不是当出厂判据。
158
+ vectorItemMin: Schema.number(),
159
+ vectorSpeakMin: Schema.number(),
139
160
  // legacy `trigger.scope` 的处置。默认 **ignore**:它的值由作者手写,几乎不可能落在
140
161
  // 自动派生的项目画像 tag 空间里(实测唯一一条带 scope 的条目因此永远无法命中),
141
162
  // 拿它当收窄条件只会判死条目。`readiness.js` 的注释一直写的是"默认忽略",这里此前
@@ -226,14 +247,11 @@ export function apply(ctx, config) {
226
247
  // 全量索引 cwd 是显式开启的行为,但"cwd 是家目录"几乎总是误用:拒绝并说明,
227
248
  // 而不是替用户把整棵树扫一遍(旧实现直接 indexRepository(ctx, config, cwd),
228
249
  // 没有任何护栏——这正是 issue #5 里最直接的 OOM 入口)。
229
- if (isUnsafeRoot(root) && config.allowUnsafeRoots !== true) {
230
- if (!cancelled) {
231
- console.error(
232
- `[dsh-project-memory] autoIndexOnFirstUse skipped: cwd ${root} is not a project root ` +
233
- '(home / system / package-manager prefix). Start dsh inside a project directory, ' +
234
- 'or set allowUnsafeRoots: true to override.',
235
- )
236
- }
250
+ // 这里走与工具调用同一个 assertSafeRoot:roots.allow / deny / exclude 全部生效。
251
+ try {
252
+ assertSafeRoot(root, { config })
253
+ } catch (err) {
254
+ if (!cancelled) console.error(`[dsh-project-memory] autoIndexOnFirstUse skipped: ${err.message}`)
237
255
  return
238
256
  }
239
257
  try {