@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
package/src/symbols.js CHANGED
@@ -398,8 +398,6 @@ function matchShell(line) {
398
398
  }
399
399
 
400
400
  function extractParamsAndReturn(line) {
401
- const trimmed = line.trim()
402
-
403
401
  // Try to extract params and return type from function declaration
404
402
  // Matches: function name(params): returnType { or => returnType {
405
403
  const funcMatch = line.match(/function\s+([A-Za-z_$][\w$]*)\s*(\([^)]*\))\s*(?::\s*([^{]+))?\s*\{/)
@@ -417,8 +415,8 @@ function extractParamsAndReturn(line) {
417
415
 
418
416
  // Arrow function without explicit return type: const name = (params) => {
419
417
  const arrowSimple = line.match(/const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?\(([^)]*)\)\s*=>/)
420
- if (arrowMatch) {
421
- return `${arrowMatch[1]}(${arrowMatch[2]})`
418
+ if (arrowSimple) {
419
+ return `${arrowSimple[1]}(${arrowSimple[2]})`
422
420
  }
423
421
 
424
422
  // Class method: methodName(params): returnType {
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
5
5
  import { forgetVectorRows } from '../vector-index.js'
@@ -38,10 +38,7 @@ export function forgetTool(config) {
38
38
  required: true,
39
39
  description: 'exact id or keywords; id takes priority',
40
40
  },
41
- root: {
42
- type: 'string',
43
- description: 'project root (default: cwd)',
44
- },
41
+ root: rootParam(),
45
42
  },
46
43
  output: TEXT_OUTPUT,
47
44
  async execute(args, exec) {
@@ -65,7 +62,7 @@ export function forgetTool(config) {
65
62
  }
66
63
  if (!res || !res.ok || !res.removed.length) return 'No matching memory found.'
67
64
  return `Removed ${res.removed.length} memory entries:\n`
68
- + res.removed.map((e) => `- ${line(e)}`).join('\n')
65
+ + res.removed.map((e) => `- ${line(e)}`).join('\n') + persistenceNote(store, globalStore)
69
66
  + keptHint(res)
70
67
  },
71
68
  })
@@ -1,10 +1,11 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import path from 'node:path'
4
- import { statSync } from 'node:fs'
4
+ import { existsSync, statSync } from 'node:fs'
5
5
  import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
6
6
  import { buildDocEntries } from '../doc-pipeline.js'
7
7
  import { docEntriesNeedBackfill } from '../doc-index.js'
8
+ import { fileKind } from '../index-pipeline.js'
8
9
  import { ProjectMemoryStore } from '../store.js'
9
10
 
10
11
  export function indexDocTool(ctx, config) {
@@ -18,22 +19,20 @@ export function indexDocTool(ctx, config) {
18
19
  required: true,
19
20
  description: 'absolute path of the document',
20
21
  },
21
- root: {
22
- type: 'string',
23
- description: 'project root (default: session project root)',
24
- },
22
+ root: rootParam({ description: 'project root (default: session project root)' }),
25
23
  },
26
24
  output: TEXT_OUTPUT,
27
25
  async execute(args, exec) {
28
- const filePath = assertReadableFile(args.file_path, config.maxFileSizeMb)
26
+ // 相对路径按会话当前工作目录解析;直接用会落到宿主进程 cwd(web profile 里可能是 /)。
27
+ const rawPath = typeof args.file_path === 'string' ? args.file_path : ''
28
+ // 先只做“存在且可读”检查(不限大小):超大/被 exclude 的文件也要能解析出 root,
29
+ // 才能把旧索引摘掉。
30
+ const filePath = assertReadableFile(
31
+ path.isAbsolute(rawPath) ? rawPath : path.resolve(resolveIndexRoot(exec), rawPath),
32
+ 0,
33
+ )
29
34
  // roots.exclude 是"这棵子树里的文件一律不进索引":显式 index_doc 也要服从。
30
35
  const excluded = excludedEntryForPath(filePath, config)
31
- if (excluded) {
32
- return (
33
- `Not indexed: ${filePath} is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(excluded.raw)}. ` +
34
- 'Remove that entry from `config.roots.exclude` under `- id: project-memory` if this file should be indexed.'
35
- )
36
- }
37
36
  const explicit = args.root && args.root.trim() ? args.root : null
38
37
  let root
39
38
  if (explicit) {
@@ -46,6 +45,13 @@ export function indexDocTool(ctx, config) {
46
45
  const sessionRoot = sessionMemoryRootOrNull(exec, config)
47
46
  root = findProjectRoot(filePath, { sessionRoot, config })
48
47
  if (!root) {
48
+ // 被 exclude 的文件在无标记目录里先命中排除规则:报排除原因(此时也没有可清理的 store)。
49
+ if (excluded) {
50
+ return (
51
+ `Not indexed: ${filePath} is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(excluded.raw)}. ` +
52
+ 'Remove that entry from `config.roots.exclude` under `- id: project-memory` if this file should be indexed.'
53
+ )
54
+ }
49
55
  return (
50
56
  `Not indexed: ${filePath} is not inside a detected project ` +
51
57
  '(no .git / package.json / pyproject.toml … marker above it). Pass root explicitly to place the memory store.'
@@ -63,9 +69,45 @@ export function indexDocTool(ctx, config) {
63
69
  )
64
70
  }
65
71
 
66
- const store = new ProjectMemoryStore(memoryDir).load()
67
-
68
72
  const rel = storeKey(relRaw.split(path.sep).join('/'))
73
+ // index_doc 只接受文档。此前不校验后缀,代码文件会被 buildDocEntries 当文本抽成
74
+ // 一条 doc chunk,并用 type:'doc' 覆盖掉 index_repo 写下的同 rel 符号条目——
75
+ // 符号层随即查不到东西,直到下一次 index_repo 才自愈。
76
+ const kind = fileKind(path.extname(filePath).toLowerCase())
77
+ if (kind !== 'doc') {
78
+ const why = kind === 'code'
79
+ ? 'this is a source file; use index_repo (or lazy indexing) for code symbols'
80
+ : 'unsupported extension (index_doc accepts PDF/MD/txt)'
81
+ return `Not indexed: ${rel} — ${why}. The existing record was left untouched.`
82
+ }
83
+ const storeExists = existsSync(memoryDir)
84
+
85
+ // 被排除 / 超大:旧版本留下的索引必须摘掉,否则 query_memory 会继续命中已删除的内容。
86
+ // 但没有 store 时绝不能为了“清理”先建一个空 store(老契约:拒绝不产生副作用)。
87
+ const dropStale = (reason) => {
88
+ if (!storeExists) return reason
89
+ const staleStore = new ProjectMemoryStore(memoryDir).load()
90
+ return staleStore.commit((s) => {
91
+ s.removeFile(rel)
92
+ return reason
93
+ }) + persistenceNote(staleStore)
94
+ }
95
+ if (excluded) {
96
+ return dropStale(
97
+ `Not indexed: ${filePath} is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(excluded.raw)}. ` +
98
+ `Removed stale index (if any). Remove that entry from \`config.roots.exclude\` under \`- id: project-memory\` if this file should be indexed.`,
99
+ )
100
+ }
101
+ const sizeLimit = config.maxFileSizeMb
102
+ if (sizeLimit) {
103
+ let size = 0
104
+ try { size = statSync(filePath).size } catch { size = 0 }
105
+ if (size > sizeLimit * 1024 * 1024) {
106
+ return dropStale(`Not indexed: ${rel} is now ${(size / 1024 / 1024).toFixed(1)} MB, over the ${sizeLimit} MB limit. Removed stale index (if any).`)
107
+ }
108
+ }
109
+
110
+ const store = new ProjectMemoryStore(memoryDir).load()
69
111
  // mtime 必须在读正文之前取:记录里的 mtime 不能比内容新,否则懒索引的快路径会跳过之后的真实改动。
70
112
  let mtimeMs
71
113
  try {
@@ -80,7 +122,7 @@ export function indexDocTool(ctx, config) {
80
122
  if (existing && existing.sha256 === hash && !docEntriesNeedBackfill(store.entries[rel])) {
81
123
  // 旧记录没有 explicit 时在这里补上:否则重新 index_doc 一次也救不回被扫描清理掉的文件。
82
124
  if (!existing.explicit) store.commit((s) => s.markFile(rel, { ...existing, explicit: true }))
83
- return `Skipped (unchanged): ${rel}\nAlready indexed with ${(store.entries[rel] || []).length} entry/entries.`
125
+ return `Skipped (unchanged): ${rel}\nAlready indexed with ${(store.entries[rel] || []).length} entry/entries.` + persistenceNote(store)
84
126
  }
85
127
 
86
128
  const entries = await buildDocEntries(rel, filePath, {
@@ -90,10 +132,11 @@ export function indexDocTool(ctx, config) {
90
132
  maxPdfPages: config.maxPdfPages,
91
133
  })
92
134
  if (entries === null) {
93
- return store.commit((s) => {
135
+ const text = store.commit((s) => {
94
136
  s.removeFile(rel)
95
137
  return `Skipped: ${rel} looks like a reflection dump, not a document.`
96
138
  })
139
+ return text + persistenceNote(store)
97
140
  }
98
141
 
99
142
  return store.commit((s) => {
@@ -107,7 +150,7 @@ export function indexDocTool(ctx, config) {
107
150
  .map((e) => ` - ${e.title} @ ${rel}:${e.sourceLine}`)
108
151
  .join('\n')
109
152
  return `Indexed: ${rel}\nEntries: ${entries.length}\n${preview}`
110
- })
153
+ }) + persistenceNote(store)
111
154
  },
112
155
  })
113
156
  }
@@ -1,12 +1,12 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import path from 'node:path'
4
- import { statSync } from 'node:fs'
5
- import { assertIndexRoot, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, resolveIndexRoot, scanLimits, storeKey } from '../util/fs.js'
4
+ import { existsSync, statSync } from 'node:fs'
5
+ import { assertIndexRoot, assertSafeRoot, excludedEntryForPath, listProjectFiles, memoryDirName, memoryRootFor, relativePath, resolveIndexRoot, scanLimits, storeKey } from '../util/fs.js'
6
6
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from '../index-pipeline.js'
7
7
  import { ProjectMemoryStore } from '../store.js'
8
8
  import { onFileIndexed, isTypeScriptFile, enhanceQueueStats } from '../enhancer.js'
9
- import { listIndexFailures } from '../index-failures.js'
9
+ import { clearIndexFailure, listIndexFailures } from '../index-failures.js'
10
10
 
11
11
  /**
12
12
  * 每批提交的文件数。旧实现把整棵树的 updates 攒到最后一次性 commit:一次全量扫描的
@@ -69,6 +69,8 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
69
69
  if (batch.length >= COMMIT_BATCH) flushBatch()
70
70
  continue
71
71
  }
72
+ // 本轮已成功处理:之前任何瞬时失败都应从“后台失败”账本里消失。
73
+ clearIndexFailure(root, rel)
72
74
  batch.push(toFileUpdate(rel, plan, record))
73
75
  if (plan.key === DROP) skipped++
74
76
  else if (plan.type === 'code') {
@@ -78,8 +80,9 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
78
80
  indexed++
79
81
  }
80
82
  if (batch.length >= COMMIT_BATCH) flushBatch()
81
- } catch {
82
- failures.push(rel)
83
+ } catch (err) {
84
+ // 带上原因:只有路径的报告无法区分"没权限"和"解析器崩了"。
85
+ failures.push(`${rel} (${err?.message || err})`)
83
86
  }
84
87
  }
85
88
 
@@ -90,6 +93,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
90
93
  updates: batch,
91
94
  unseen: truncated ? null : seen,
92
95
  root,
96
+ isExcludedRel: (rel) => Boolean(excludedEntryForPath(path.join(root, rel), config)),
93
97
  })
94
98
  const stats = store.stats()
95
99
  let report =
@@ -118,6 +122,10 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
118
122
  if (failures.length) {
119
123
  report += `\nfailed to index ${failures.length} file(s): ${failures.join(', ')}`
120
124
  }
125
+ // 已删除的失败项也要摘掉,否则一次瞬时失败会永久出现在报告里。
126
+ for (const item of listIndexFailures(root, 50).items) {
127
+ if (!existsSync(path.join(root, item.rel))) clearIndexFailure(root, item.rel)
128
+ }
121
129
  // 后台(watch / 懒索引)的失败不在本次扫描里,但它们同样意味着"这些文件没进语料"。
122
130
  // 过去只写日志,用户看不到;这里跟随本次结果一起报出来。
123
131
  const background = listIndexFailures(root, 5)
@@ -138,7 +146,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
138
146
  ': their L1 regex symbols are unaffected; they are re-queued on the next index or change.'
139
147
  }
140
148
 
141
- return report
149
+ return report + persistenceNote(store)
142
150
  }
143
151
 
144
152
  export function indexRepoTool(ctx, config) {
@@ -148,11 +156,7 @@ export function indexRepoTool(ctx, config) {
148
156
  'Index a project into memory (docs + code symbols), incremental by content hash. '
149
157
  + 'Call once per project, then query_memory.',
150
158
  parameters: {
151
- root: {
152
- type: 'string',
153
- required: true,
154
- description: 'project root (relative: session cwd)',
155
- },
159
+ root: rootParam({ required: true, description: 'project root (relative: session cwd)' }),
156
160
  reindex: {
157
161
  type: 'boolean',
158
162
  description: 'ignore hashes, force re-extraction',
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { normalizeCitationFiles } from '../util/fs.js'
5
5
  import { truncate } from '../util/text.js'
@@ -38,8 +38,8 @@ export function lessonTool(config) {
38
38
  type: 'object',
39
39
  additionalProperties: false,
40
40
  properties: {
41
- ops: { type: 'array', items: { type: 'string' }, description: 'file-write|file-delete|shell-run|git-commit|git-push|release|npm-publish|deploy|migrate|render-doc|index-doc|read-image|fetch-web|run-bench|query-memory' },
42
- writes: { type: 'array', items: { type: 'string' }, description: 'project-relative paths, no glob' },
41
+ ops: { type: 'array', items: { type: 'string' }, description: 'file-write|file-delete|shell-run|git-commit|git-push|release|npm-publish|go-public|deploy|migrate|render-doc|index-doc|read-image|fetch-web|run-bench|query-memory' },
42
+ writes: { type: 'array', items: { type: 'string' }, description: 'project-relative paths; `*` wildcards are allowed' },
43
43
  intents: { type: 'array', items: { type: 'string' }, description: 'intent words (CJK ≥2, latin ≥5)' },
44
44
  },
45
45
  description: 'the only trigger surface: any of the three; without it the entry is retrieval-only.',
@@ -69,7 +69,7 @@ export function lessonTool(config) {
69
69
  files: { type: 'array', items: { type: 'string' }, description: 'related files (project-relative)' },
70
70
  symbols: { type: 'array', items: { type: 'string' }, description: 'related symbols' },
71
71
  confidence: { type: 'number', description: '0..1' },
72
- root: { type: 'string', description: 'project root' },
72
+ root: rootParam(),
73
73
  },
74
74
  output: TEXT_OUTPUT,
75
75
  async execute(args, exec) {
@@ -133,7 +133,7 @@ export function lessonTool(config) {
133
133
  const note = citationFiles.dropped.length
134
134
  ? `\n(${citationFiles.dropped.length} 个 files 既不是项目内相对路径也不是项目内绝对路径,已丢弃:${citationFiles.dropped.slice(0, 3).join(', ')}${citationFiles.dropped.length > 3 ? ' …' : ''})`
135
135
  : ''
136
- return truncate(body + note, config.maxOutputChars || 8000)
136
+ return truncate(body + note + persistenceNote(store, globalStore), config.maxOutputChars || 8000)
137
137
  },
138
138
  })
139
139
  }
@@ -3,3 +3,31 @@ export const TEXT_OUTPUT = {
3
3
  schema: { type: 'string' },
4
4
  render: (_args, value) => [{ type: 'text', text: value }],
5
5
  }
6
+
7
+ /**
8
+ * 工具参数里的 `root` 声明。可选根缺省由 `openProjectContext` 解析成会话工作目录所属的项目根,
9
+ * 所以描述里必须把默认值写出来——否则模型只能猜"不传会怎样"。
10
+ *
11
+ * 这段 4 行字面量曾在 9 个工具文件里各抄一份,可选根的措辞漂成两种(`save_lesson` 只写
12
+ * "project root",其余写 "(default: cwd)")。描述文本**仍是参数**:`index_doc` 的根从
13
+ * `file_path` 反推,`index_repo` / `watch_repo` 必须显式给根——这三类默认值不同,不能在
14
+ * 调用点被抹平;收敛的是形状与"不传 root"的统一语义,不是把所有工具改成同一句话。
15
+ * @param {{ required?: boolean, description?: string }} [opts]
16
+ * @returns {{ type: 'string', description: string, required?: true }}
17
+ */
18
+ export function rootParam({ required = false, description = 'project root (session cwd, or its nearest project marker)' } = {}) {
19
+ return required ? { type: 'string', required: true, description } : { type: 'string', description }
20
+ }
21
+
22
+ /**
23
+ * 写盘失败的统一提示。`save()` / `commit()` 在锁竞争、只读挂载、ENOSPC、目录不可建时返回 false
24
+ * 而不抛(重试与退出 flush 仍会尝试),但工具不能因此报"已保存"。调用方把它拼在成功文案后面。
25
+ * @param {...(object|null|undefined)} stores 可能带 lastSaveOk / lastCommitOk 的 store
26
+ * @returns {string} 需要提示时以两个换行开头
27
+ */
28
+ export function persistenceNote(...stores) {
29
+ const failed = stores.some((s) => s && (s.lastSaveOk === false || s.lastCommitOk === false))
30
+ if (!failed) return ''
31
+ return '\n\n⚠ Not persisted to disk (permissions, disk space, or another dsh process holds the lock). '
32
+ + 'The change is still in memory and will be retried; check the store directory before relying on it.'
33
+ }
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
3
3
  import path from 'node:path'
4
4
  import { assertIndexRoot, memoryDirName, memoryRootFor, nestedStoreRoots, resolveSafeIndexRoot } from '../util/fs.js'
5
5
  import { ProjectMemoryStore, storeOverview } from '../store.js'
@@ -70,10 +70,7 @@ export function queryMemoryTool(ctx, config) {
70
70
  required: true,
71
71
  description: 'what to look for',
72
72
  },
73
- root: {
74
- type: 'string',
75
- description: 'project root (default: cwd)',
76
- },
73
+ root: rootParam(),
77
74
  type: {
78
75
  type: 'string',
79
76
  enum: ['all', 'doc', 'symbol', 'experience', 'insight', 'task'],
@@ -81,7 +78,7 @@ export function queryMemoryTool(ctx, config) {
81
78
  },
82
79
  limit: {
83
80
  type: 'number',
84
- description: 'max results, default 8',
81
+ description: 'max results per layer, default 8, capped at 20; `all` can return up to 3x (docs/symbols, insights, experience)',
85
82
  },
86
83
  },
87
84
  output: TEXT_OUTPUT,
@@ -95,7 +92,7 @@ export function queryMemoryTool(ctx, config) {
95
92
  // 空查询不是"全部":recallItems 会过滤空串,rankEntriesStreaming 随即返回
96
93
  // entries.slice(0, limit)(任意条目、分数 0),task 分支的 includes('') 更是命中所有任务。
97
94
  if (!String(args.query ?? '').trim()) {
98
- return 'query must not be empty. Use memory_stats to see what the store contains.'
95
+ return 'query must not be empty. Use pm_stats to see what the store contains.'
99
96
  }
100
97
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
101
98
  const type = args.type || 'all'
@@ -292,8 +289,8 @@ export function queryMemoryTool(ctx, config) {
292
289
  overview.files === 0
293
290
  ? '. The store has never been indexed.'
294
291
  : overview.latest
295
- ? `, last indexed at ${overview.latest}. Use memory_stats to see what the store contains.`
296
- : '. Use memory_stats to see what the store contains.'
292
+ ? `, last indexed at ${overview.latest}. Use pm_stats to see what the store contains.`
293
+ : '. Use pm_stats to see what the store contains.'
297
294
  const nestedNote = wantMemory && memHitCount === 0 ? nestedIndexNote(root, config) : ''
298
295
  return (
299
296
  `No memory matches for "${args.query}" in ${root}. ${hint}\n` +
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { normalizeCitationFiles } from '../util/fs.js'
5
5
  import { saveInsight, GlobalStore, defaultGlobalFile } from '../insight-store.js'
@@ -24,10 +24,7 @@ export function rememberTool(config) {
24
24
  required: true,
25
25
  description: 'concrete fix',
26
26
  },
27
- root: {
28
- type: 'string',
29
- description: 'project root (default: cwd)',
30
- },
27
+ root: rootParam(),
31
28
  source_file: {
32
29
  type: 'string',
33
30
  description: 'related file (project-relative)',
@@ -62,7 +59,7 @@ export function rememberTool(config) {
62
59
  const dropped = citation.dropped.length
63
60
  ? `\n(${citation.dropped.length} 个 source_file 不是项目内路径,已丢弃)`
64
61
  : ''
65
- return `${verb} experience note (${result.id}).${result.hint ? ` ${result.hint}` : ''}${dropped}`
62
+ return `${verb} experience note (${result.id}).${result.hint ? ` ${result.hint}` : ''}${dropped}${persistenceNote(store, globalStore)}`
66
63
  },
67
64
  })
68
65
  }
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
3
3
  import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
4
4
  import { ProjectMemoryStore, storeOverview } from '../store.js'
5
5
  import { cfgInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
@@ -12,14 +12,11 @@ const TOP_N = 30
12
12
 
13
13
  export function statsTool(config) {
14
14
  return defineTool({
15
- name: 'memory_stats',
15
+ name: 'pm_stats',
16
16
  description:
17
17
  'Show store totals, last index time and the per-file index list.',
18
18
  parameters: {
19
- root: {
20
- type: 'string',
21
- description: 'project root (default: cwd)',
22
- },
19
+ root: rootParam(),
23
20
  },
24
21
  output: TEXT_OUTPUT,
25
22
  async execute(args, exec) {
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { truncate } from '../util/text.js'
5
5
  import { sessionIdOf, stepProgress, timeAgo } from '../util/task-view.js'
@@ -21,7 +21,7 @@ export function listTasksTool(config) {
21
21
  description:
22
22
  'List this project\'s task records (archived included). Look here first in a new or resumed session, then select_task to pick one.',
23
23
  parameters: {
24
- root: { type: 'string', description: 'project root (default: cwd)' },
24
+ root: rootParam(),
25
25
  },
26
26
  output: TEXT_OUTPUT,
27
27
  async execute(args, exec) {
@@ -42,12 +42,13 @@ export function selectTaskTool(config, host) {
42
42
  return defineTool({
43
43
  name: 'select_task',
44
44
  description:
45
- 'Bind the session to a task (its todo list and files read afterwards sync into it). Exact taskId, or an exact title match'
46
- + '(creates one if absent); returns the task card used to rebuild the checklist.',
45
+ 'Bind the session to a task (its todo list and files read afterwards sync into it). Exact taskId '
46
+ + '(optionally renames/unarchives via title), or an exact title match (creates one if absent); '
47
+ + 'returns the task card used to rebuild the checklist.',
47
48
  parameters: {
48
49
  taskId: { type: 'string', description: 'exact task id' },
49
50
  title: { type: 'string', description: 'exact title; creates if absent' },
50
- root: { type: 'string', description: 'project root (default: cwd)' },
51
+ root: rootParam(),
51
52
  },
52
53
  output: TEXT_OUTPUT,
53
54
  async execute(args, exec) {
@@ -120,7 +121,7 @@ export function selectTaskTool(config, host) {
120
121
 
121
122
  // 反向接管:绑定成功后,把任务步骤推成宿主 todo/write(dsh 清单跟随我们的任务)
122
123
  if (shouldAdoptToHost(config)) {
123
- adoptStepsToSession(exec?.agent?.session || exec?.ctx?.session, task)
124
+ adoptStepsToSession(exec?.agent?.session || exec?.ctx?.session, task, { force: true })
124
125
  }
125
126
 
126
127
  // 反思钩子:切走旧任务时异步收割(默认关,零成本;失败只记日志)
@@ -135,6 +136,7 @@ export function selectTaskTool(config, host) {
135
136
  files: task.files,
136
137
  insights: task.insights || [], // v0.5:任务级 lessons/decisions/procedures
137
138
  hint: hint + ';请据此用 todo_write 重建本会话清单',
139
+ ...(store.lastSaveOk === false ? { persisted: false, warning: '内存已绑定,但 tasks.json 未落盘(权限/磁盘/锁);退出前会重试。' } : {}),
138
140
  }
139
141
  return truncate(JSON.stringify(card), config.maxOutputChars)
140
142
  },
@@ -166,7 +168,7 @@ export function archiveTaskTool(config, host) {
166
168
  description: 'Archive a task (restore by selecting it again).',
167
169
  parameters: {
168
170
  taskId: { type: 'string', required: true, description: 'task id' },
169
- root: { type: 'string', description: 'project root (default: cwd)' },
171
+ root: rootParam(),
170
172
  },
171
173
  output: TEXT_OUTPUT,
172
174
  async execute(args, exec) {
@@ -184,7 +186,12 @@ export function archiveTaskTool(config, host) {
184
186
  store.save()
185
187
  // 反思钩子:归档即收割最终教训(默认关)
186
188
  fireReflect(config, host, root, args.taskId, 'archive', resolveRoute(exec, config))
187
- return truncate(JSON.stringify({ success: true, archived: true, hint: '已归档,select_task 可恢复' }), config.maxOutputChars)
189
+ return truncate(JSON.stringify({
190
+ success: true,
191
+ archived: true,
192
+ hint: '已归档,select_task 可恢复',
193
+ ...(store.lastSaveOk === false ? { persisted: false, warning: '内存已归档,但 tasks.json 未落盘(权限/磁盘/锁);退出前会重试。' } : {}),
194
+ }), config.maxOutputChars)
188
195
  },
189
196
  })
190
197
  }
@@ -1,5 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { TEXT_OUTPUT } from './output.js'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
3
3
  import { existsSync } from 'node:fs'
4
4
  import path from 'node:path'
5
5
  import { assertIndexRoot, assertSafeRoot, memoryRootFor, resolveIndexRoot, rootRejection, sessionMemoryRootOrNull, storeKey } from '../util/fs.js'
@@ -13,11 +13,7 @@ export function watchRepoTool(watchManager, config) {
13
13
  description:
14
14
  'Auto-refresh a project on change; watch=false stops.',
15
15
  parameters: {
16
- root: {
17
- type: 'string',
18
- required: true,
19
- description: 'project root (relative: session cwd)',
20
- },
16
+ root: rootParam({ required: true, description: 'project root (relative: session cwd)' }),
21
17
  watch: {
22
18
  type: 'boolean',
23
19
  description: 'false = stop watching',
@@ -45,13 +41,14 @@ export function watchRepoTool(watchManager, config) {
45
41
  const mirrorSessionWatchlist = async (present) => {
46
42
  // 会话根不可用(家目录/系统目录且无标记)时跳过镜像:那会在不该有项目记忆的目录里
47
43
  // 造出 watch.json,而 watch.json 一旦落在那里,下次以该目录为 cwd 启动又会把它读回来。
48
- if (!sessionRoot || !sessionMemoryDir) return
44
+ if (!sessionRoot || !sessionMemoryDir) return true
49
45
  // Windows/macOS 大小写不敏感:同一目录的两种写法不能当成两个 store 互相镜像。
50
- if (storeKey(path.resolve(sessionMemoryDir)) === storeKey(path.resolve(memoryDir))) return
46
+ if (storeKey(path.resolve(sessionMemoryDir)) === storeKey(path.resolve(memoryDir))) return true
51
47
  const sessionStore = new ProjectMemoryStore(sessionMemoryDir).load()
52
48
  const removed = sessionStore.removeWatch(root)
53
49
  const added = present ? sessionStore.addWatch(root) : false
54
- if (removed || added) sessionStore.save()
50
+ if (removed || added) return sessionStore.save() !== false
51
+ return true
55
52
  }
56
53
 
57
54
  if (args.watch === false) {
@@ -68,12 +65,18 @@ export function watchRepoTool(watchManager, config) {
68
65
  await mirrorSessionWatchlist(false)
69
66
  return `Stopped watching: ${root}`
70
67
  }
71
- new ProjectMemoryStore(memoryDir).load().commit((s) => s.addWatch(root))
72
- await mirrorSessionWatchlist(true)
68
+ const rootStore = new ProjectMemoryStore(memoryDir).load()
69
+ rootStore.commit((s) => s.addWatch(root))
70
+ const mirrored = await mirrorSessionWatchlist(true)
73
71
  watchManager.addRoot(root)
74
72
  const intervalMs = normalizeWatchIntervalMs(Number(cfgValue(config, 'watchInterval')) * 1000)
75
73
  watchManager.start(intervalMs)
76
- return `Watching ${root} (interval ${intervalMs / 1000}s). Docs/code changes will be re-indexed silently.`
74
+ // 进程内已经在监听,但 watch.json 没写成功时重启会静默丢失:必须让调用方看见。
75
+ const persisted = rootStore.lastSaveOk !== false && mirrored
76
+ const warning = persisted
77
+ ? ''
78
+ : '\nWarning: watchlist was not persisted (busy/read-only store); this process keeps watching, but a restart will not restore it.'
79
+ return `Watching ${root} (interval ${intervalMs / 1000}s). Docs/code changes will be re-indexed silently.${warning}`
77
80
  },
78
81
  })
79
82
  }
package/src/util/flush.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * 退出/卸载前的最后一道写盘兜底。
3
3
  *
4
4
  * 为什么需要:保存失败后的后台重试**不能**当正确性保证——用户结束对话、关掉 dsh 时不会等
5
- * 20s 的重试。正确性来自两点:① `save()` 在锁竞争时同步等待(见 store.js 的 LOCK_WAIT_MS);
5
+ * 20s 的重试。正确性来自两点:① `save()` 在锁竞争时同步等待(默认 15s,见 store.js 的 save);
6
6
  * ② 万一仍失败,进程正常退出或插件卸载时再同步写一次。
7
7
  *
8
8
  * 注册的是脏 store(而不是所有 store):只有内存里还有未落盘变更的才需要 flush。