@yolk_vat-y/dsh-project-memory 0.6.11 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +104 -120
  2. package/README.md +14 -105
  3. package/README.zh-CN.md +14 -105
  4. package/client/client.js +228 -95
  5. package/client/client.js.map +1 -1
  6. package/package.json +2 -2
  7. package/scripts/file-peak.mjs +1 -1
  8. package/scripts/tool-schema-size.mjs +1 -1
  9. package/skills/project-memory/SKILL.md +1 -1
  10. package/skills/project-memory/scripts/pm-digest.mjs +20 -6
  11. package/src/audit.js +10 -2
  12. package/src/auto-inject.js +124 -38
  13. package/src/client/MemoryView.tsx +119 -40
  14. package/src/client/TaskCommandNode.tsx +6 -4
  15. package/src/client/TaskComponents.tsx +13 -16
  16. package/src/client/TaskPanel.tsx +41 -15
  17. package/src/client/client.ts +4 -7
  18. package/src/client/paging.js +1 -14
  19. package/src/client/settings-card.tsx +9 -0
  20. package/src/client/task-data-store.ts +57 -7
  21. package/src/client/task-hooks.ts +0 -2
  22. package/src/client/task-scope.js +16 -1
  23. package/src/client/task-ui-store.ts +1 -1
  24. package/src/commands/insight-actions.js +91 -94
  25. package/src/commands/task-actions.js +7 -5
  26. package/src/commands/tasks.js +34 -10
  27. package/src/doc-index.js +3 -1
  28. package/src/enhancer.js +0 -12
  29. package/src/index-failures.js +1 -1
  30. package/src/index-pipeline.js +11 -2
  31. package/src/index.js +60 -14
  32. package/src/inject-visible.js +282 -0
  33. package/src/insight-store.js +133 -68
  34. package/src/lazy.js +29 -23
  35. package/src/llm-route.js +1 -1
  36. package/src/llm.js +1 -8
  37. package/src/ops.js +18 -5
  38. package/src/parsers/pdfjs-parser.js +3 -33
  39. package/src/project-memory-service.js +195 -0
  40. package/src/project-profile.js +0 -4
  41. package/src/setup/taskbridge.js +38 -6
  42. package/src/store.js +639 -147
  43. package/src/symbols.js +2 -4
  44. package/src/tools/context.js +14 -0
  45. package/src/tools/forget.js +7 -17
  46. package/src/tools/index-doc.js +62 -21
  47. package/src/tools/index-repo.js +17 -15
  48. package/src/tools/lesson-tools.js +10 -13
  49. package/src/tools/output.js +33 -0
  50. package/src/tools/query-memory.js +7 -12
  51. package/src/tools/remember.js +8 -18
  52. package/src/tools/stats.js +4 -9
  53. package/src/tools/task-tools.js +23 -22
  54. package/src/tools/watch-repo.js +16 -15
  55. package/src/util/flush.js +1 -1
  56. package/src/util/fs.js +135 -20
  57. package/src/util/insight-fields.js +22 -0
  58. package/src/util/message-source.js +20 -0
  59. package/src/util/relative-time.js +24 -0
  60. package/src/util/search.js +0 -1
  61. package/src/util/task-view.js +8 -15
  62. package/src/util/value.js +16 -0
  63. package/src/vector-index.js +2 -2
  64. package/src/watch.js +25 -8
  65. package/client/client.d.ts +0 -27
  66. package/client/client.d.ts.map +0 -1
  67. package/client/style.css +0 -395
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 {
@@ -0,0 +1,14 @@
1
+ // 工具执行入口的项目上下文:根解析/校验、记忆目录、store 加载、insight 配置。
2
+ // 校验必须在建目录之前:否则一个拼错的 root 会被 mkdir 成字面量目录。
3
+ import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
4
+ import { ProjectMemoryStore } from '../store.js'
5
+ import { cfgInsight } from '../insight-store.js'
6
+
7
+ export function openProjectContext(exec, args, config) {
8
+ const root = resolveSafeIndexRoot(exec, args.root, config)
9
+ assertIndexRoot(root, args.root || root)
10
+ const memoryDir = memoryRootFor(root, config.memoryDir)
11
+ const store = new ProjectMemoryStore(memoryDir).load()
12
+ const cfg = cfgInsight(config)
13
+ return { root, memoryDir, store, cfg }
14
+ }
@@ -1,7 +1,7 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
- import { ProjectMemoryStore } from '../store.js'
4
- import { cfgInsight, DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
+ import { openProjectContext } from './context.js'
4
+ import { DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
5
5
  import { forgetVectorRows } from '../vector-index.js'
6
6
 
7
7
  /** 回报用的一行:`ins_xxx《标题》(project)`。标题已在 removeMemory 里截断。 */
@@ -38,21 +38,11 @@ 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
- },
45
- },
46
- output: {
47
- schema: { type: 'string' },
48
- render: (_args, value) => [{ type: 'text', text: value }],
41
+ root: rootParam(),
49
42
  },
43
+ output: TEXT_OUTPUT,
50
44
  async execute(args, exec) {
51
- const root = resolveSafeIndexRoot(exec, args.root, config)
52
- assertIndexRoot(root, args.root || root)
53
- const memoryDir = memoryRootFor(root, config.memoryDir)
54
- const store = new ProjectMemoryStore(memoryDir).load()
55
- const cfg = cfgInsight(config)
45
+ const { memoryDir, store, cfg } = openProjectContext(exec, args, config)
56
46
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
57
47
  let res
58
48
  store.commit((s) => {
@@ -72,7 +62,7 @@ export function forgetTool(config) {
72
62
  }
73
63
  if (!res || !res.ok || !res.removed.length) return 'No matching memory found.'
74
64
  return `Removed ${res.removed.length} memory entries:\n`
75
- + res.removed.map((e) => `- ${line(e)}`).join('\n')
65
+ + res.removed.map((e) => `- ${line(e)}`).join('\n') + persistenceNote(store, globalStore)
76
66
  + keptHint(res)
77
67
  },
78
68
  })
@@ -1,9 +1,11 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
2
3
  import path from 'node:path'
3
- import { statSync } from 'node:fs'
4
+ import { existsSync, statSync } from 'node:fs'
4
5
  import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
5
6
  import { buildDocEntries } from '../doc-pipeline.js'
6
7
  import { docEntriesNeedBackfill } from '../doc-index.js'
8
+ import { fileKind } from '../index-pipeline.js'
7
9
  import { ProjectMemoryStore } from '../store.js'
8
10
 
9
11
  export function indexDocTool(ctx, config) {
@@ -17,25 +19,20 @@ export function indexDocTool(ctx, config) {
17
19
  required: true,
18
20
  description: 'absolute path of the document',
19
21
  },
20
- root: {
21
- type: 'string',
22
- description: 'project root (default: session project root)',
23
- },
24
- },
25
- output: {
26
- schema: { type: 'string' },
27
- render: (_args, value) => [{ type: 'text', text: value }],
22
+ root: rootParam({ description: 'project root (default: session project root)' }),
28
23
  },
24
+ output: TEXT_OUTPUT,
29
25
  async execute(args, exec) {
30
- 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
+ )
31
34
  // roots.exclude 是"这棵子树里的文件一律不进索引":显式 index_doc 也要服从。
32
35
  const excluded = excludedEntryForPath(filePath, config)
33
- if (excluded) {
34
- return (
35
- `Not indexed: ${filePath} is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(excluded.raw)}. ` +
36
- 'Remove that entry from `config.roots.exclude` under `- id: project-memory` if this file should be indexed.'
37
- )
38
- }
39
36
  const explicit = args.root && args.root.trim() ? args.root : null
40
37
  let root
41
38
  if (explicit) {
@@ -48,6 +45,13 @@ export function indexDocTool(ctx, config) {
48
45
  const sessionRoot = sessionMemoryRootOrNull(exec, config)
49
46
  root = findProjectRoot(filePath, { sessionRoot, config })
50
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
+ }
51
55
  return (
52
56
  `Not indexed: ${filePath} is not inside a detected project ` +
53
57
  '(no .git / package.json / pyproject.toml … marker above it). Pass root explicitly to place the memory store.'
@@ -65,9 +69,45 @@ export function indexDocTool(ctx, config) {
65
69
  )
66
70
  }
67
71
 
68
- const store = new ProjectMemoryStore(memoryDir).load()
69
-
70
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()
71
111
  // mtime 必须在读正文之前取:记录里的 mtime 不能比内容新,否则懒索引的快路径会跳过之后的真实改动。
72
112
  let mtimeMs
73
113
  try {
@@ -82,7 +122,7 @@ export function indexDocTool(ctx, config) {
82
122
  if (existing && existing.sha256 === hash && !docEntriesNeedBackfill(store.entries[rel])) {
83
123
  // 旧记录没有 explicit 时在这里补上:否则重新 index_doc 一次也救不回被扫描清理掉的文件。
84
124
  if (!existing.explicit) store.commit((s) => s.markFile(rel, { ...existing, explicit: true }))
85
- 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)
86
126
  }
87
127
 
88
128
  const entries = await buildDocEntries(rel, filePath, {
@@ -92,10 +132,11 @@ export function indexDocTool(ctx, config) {
92
132
  maxPdfPages: config.maxPdfPages,
93
133
  })
94
134
  if (entries === null) {
95
- return store.commit((s) => {
135
+ const text = store.commit((s) => {
96
136
  s.removeFile(rel)
97
137
  return `Skipped: ${rel} looks like a reflection dump, not a document.`
98
138
  })
139
+ return text + persistenceNote(store)
99
140
  }
100
141
 
101
142
  return store.commit((s) => {
@@ -109,7 +150,7 @@ export function indexDocTool(ctx, config) {
109
150
  .map((e) => ` - ${e.title} @ ${rel}:${e.sourceLine}`)
110
151
  .join('\n')
111
152
  return `Indexed: ${rel}\nEntries: ${entries.length}\n${preview}`
112
- })
153
+ }) + persistenceNote(store)
113
154
  },
114
155
  })
115
156
  }
@@ -1,11 +1,12 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
2
3
  import path from 'node:path'
3
- import { statSync } from 'node:fs'
4
- 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'
5
6
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from '../index-pipeline.js'
6
7
  import { ProjectMemoryStore } from '../store.js'
7
8
  import { onFileIndexed, isTypeScriptFile, enhanceQueueStats } from '../enhancer.js'
8
- import { listIndexFailures } from '../index-failures.js'
9
+ import { clearIndexFailure, listIndexFailures } from '../index-failures.js'
9
10
 
10
11
  /**
11
12
  * 每批提交的文件数。旧实现把整棵树的 updates 攒到最后一次性 commit:一次全量扫描的
@@ -68,6 +69,8 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
68
69
  if (batch.length >= COMMIT_BATCH) flushBatch()
69
70
  continue
70
71
  }
72
+ // 本轮已成功处理:之前任何瞬时失败都应从“后台失败”账本里消失。
73
+ clearIndexFailure(root, rel)
71
74
  batch.push(toFileUpdate(rel, plan, record))
72
75
  if (plan.key === DROP) skipped++
73
76
  else if (plan.type === 'code') {
@@ -77,8 +80,9 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
77
80
  indexed++
78
81
  }
79
82
  if (batch.length >= COMMIT_BATCH) flushBatch()
80
- } catch {
81
- failures.push(rel)
83
+ } catch (err) {
84
+ // 带上原因:只有路径的报告无法区分"没权限"和"解析器崩了"。
85
+ failures.push(`${rel} (${err?.message || err})`)
82
86
  }
83
87
  }
84
88
 
@@ -89,6 +93,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
89
93
  updates: batch,
90
94
  unseen: truncated ? null : seen,
91
95
  root,
96
+ isExcludedRel: (rel) => Boolean(excludedEntryForPath(path.join(root, rel), config)),
92
97
  })
93
98
  const stats = store.stats()
94
99
  let report =
@@ -117,6 +122,10 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
117
122
  if (failures.length) {
118
123
  report += `\nfailed to index ${failures.length} file(s): ${failures.join(', ')}`
119
124
  }
125
+ // 已删除的失败项也要摘掉,否则一次瞬时失败会永久出现在报告里。
126
+ for (const item of listIndexFailures(root, 50).items) {
127
+ if (!existsSync(path.join(root, item.rel))) clearIndexFailure(root, item.rel)
128
+ }
120
129
  // 后台(watch / 懒索引)的失败不在本次扫描里,但它们同样意味着"这些文件没进语料"。
121
130
  // 过去只写日志,用户看不到;这里跟随本次结果一起报出来。
122
131
  const background = listIndexFailures(root, 5)
@@ -137,7 +146,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
137
146
  ': their L1 regex symbols are unaffected; they are re-queued on the next index or change.'
138
147
  }
139
148
 
140
- return report
149
+ return report + persistenceNote(store)
141
150
  }
142
151
 
143
152
  export function indexRepoTool(ctx, config) {
@@ -147,20 +156,13 @@ export function indexRepoTool(ctx, config) {
147
156
  'Index a project into memory (docs + code symbols), incremental by content hash. '
148
157
  + 'Call once per project, then query_memory.',
149
158
  parameters: {
150
- root: {
151
- type: 'string',
152
- required: true,
153
- description: 'project root (relative: session cwd)',
154
- },
159
+ root: rootParam({ required: true, description: 'project root (relative: session cwd)' }),
155
160
  reindex: {
156
161
  type: 'boolean',
157
162
  description: 'ignore hashes, force re-extraction',
158
163
  },
159
164
  },
160
- output: {
161
- schema: { type: 'string' },
162
- render: (_args, value) => [{ type: 'text', text: value }],
163
- },
165
+ output: TEXT_OUTPUT,
164
166
  async execute(args, exec) {
165
167
  // 相对 root 按会话当前工作目录解析(不是宿主进程 cwd)——见 util/fs.js 的 resolveIndexRoot。
166
168
  const root = resolveIndexRoot(exec, args.root)
@@ -1,8 +1,9 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { assertIndexRoot, memoryRootFor, normalizeCitationFiles, resolveSafeIndexRoot } from '../util/fs.js'
3
- import { ProjectMemoryStore } from '../store.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
+ import { openProjectContext } from './context.js'
4
+ import { normalizeCitationFiles } from '../util/fs.js'
4
5
  import { truncate } from '../util/text.js'
5
- import { cfgInsight, saveInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
6
+ import { saveInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
6
7
  import { ensureGlobalInit } from '../global-seed.js'
7
8
  import { INSIGHT_KINDS, INSIGHT_SCOPES } from '../insight-store.js'
8
9
  import { sessionIdOf } from '../util/task-view.js'
@@ -37,8 +38,8 @@ export function lessonTool(config) {
37
38
  type: 'object',
38
39
  additionalProperties: false,
39
40
  properties: {
40
- 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' },
41
- 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' },
42
43
  intents: { type: 'array', items: { type: 'string' }, description: 'intent words (CJK ≥2, latin ≥5)' },
43
44
  },
44
45
  description: 'the only trigger surface: any of the three; without it the entry is retrieval-only.',
@@ -68,17 +69,13 @@ export function lessonTool(config) {
68
69
  files: { type: 'array', items: { type: 'string' }, description: 'related files (project-relative)' },
69
70
  symbols: { type: 'array', items: { type: 'string' }, description: 'related symbols' },
70
71
  confidence: { type: 'number', description: '0..1' },
71
- root: { type: 'string', description: 'project root' },
72
+ root: rootParam(),
72
73
  },
73
- output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
74
+ output: TEXT_OUTPUT,
74
75
  async execute(args, exec) {
75
- const root = resolveSafeIndexRoot(exec, args.root, config)
76
- assertIndexRoot(root, args.root || root)
76
+ const { root, memoryDir, store, cfg } = openProjectContext(exec, args, config)
77
77
  // 写入期约束:files 只收项目内相对路径(schema 早就这么承诺,此前没有校验)。
78
78
  const citationFiles = normalizeCitationFiles(args.files, root)
79
- const memoryDir = memoryRootFor(root, config.memoryDir)
80
- const store = new ProjectMemoryStore(memoryDir).load()
81
- const cfg = cfgInsight(config)
82
79
  const sid = sessionIdOf(exec)
83
80
  const boundTaskId = sid ? store.getBoundTaskId(sid) : undefined
84
81
  const taskId = args.task_id || boundTaskId
@@ -136,7 +133,7 @@ export function lessonTool(config) {
136
133
  const note = citationFiles.dropped.length
137
134
  ? `\n(${citationFiles.dropped.length} 个 files 既不是项目内相对路径也不是项目内绝对路径,已丢弃:${citationFiles.dropped.slice(0, 3).join(', ')}${citationFiles.dropped.length > 3 ? ' …' : ''})`
138
135
  : ''
139
- return truncate(body + note, config.maxOutputChars || 8000)
136
+ return truncate(body + note + persistenceNote(store, globalStore), config.maxOutputChars || 8000)
140
137
  },
141
138
  })
142
139
  }
@@ -0,0 +1,33 @@
1
+ // 纯文本工具结果:所有工具共用的 output 声明;宿主按 render 出文本块。
2
+ export const TEXT_OUTPUT = {
3
+ schema: { type: 'string' },
4
+ render: (_args, value) => [{ type: 'text', text: value }],
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,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
2
3
  import path from 'node:path'
3
4
  import { assertIndexRoot, memoryDirName, memoryRootFor, nestedStoreRoots, resolveSafeIndexRoot } from '../util/fs.js'
4
5
  import { ProjectMemoryStore, storeOverview } from '../store.js'
@@ -69,10 +70,7 @@ export function queryMemoryTool(ctx, config) {
69
70
  required: true,
70
71
  description: 'what to look for',
71
72
  },
72
- root: {
73
- type: 'string',
74
- description: 'project root (default: cwd)',
75
- },
73
+ root: rootParam(),
76
74
  type: {
77
75
  type: 'string',
78
76
  enum: ['all', 'doc', 'symbol', 'experience', 'insight', 'task'],
@@ -80,13 +78,10 @@ export function queryMemoryTool(ctx, config) {
80
78
  },
81
79
  limit: {
82
80
  type: 'number',
83
- 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)',
84
82
  },
85
83
  },
86
- output: {
87
- schema: { type: 'string' },
88
- render: (_args, value) => [{ type: 'text', text: value }],
89
- },
84
+ output: TEXT_OUTPUT,
90
85
  async execute(args, exec) {
91
86
  const root = resolveSafeIndexRoot(exec, args.root, config)
92
87
  // 读路径也要验根存在。这条不是洁癖:可选的向量层(leanvec)在空 store 上会建
@@ -97,7 +92,7 @@ export function queryMemoryTool(ctx, config) {
97
92
  // 空查询不是"全部":recallItems 会过滤空串,rankEntriesStreaming 随即返回
98
93
  // entries.slice(0, limit)(任意条目、分数 0),task 分支的 includes('') 更是命中所有任务。
99
94
  if (!String(args.query ?? '').trim()) {
100
- 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.'
101
96
  }
102
97
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
103
98
  const type = args.type || 'all'
@@ -294,8 +289,8 @@ export function queryMemoryTool(ctx, config) {
294
289
  overview.files === 0
295
290
  ? '. The store has never been indexed.'
296
291
  : overview.latest
297
- ? `, last indexed at ${overview.latest}. Use memory_stats to see what the store contains.`
298
- : '. 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.'
299
294
  const nestedNote = wantMemory && memHitCount === 0 ? nestedIndexNote(root, config) : ''
300
295
  return (
301
296
  `No memory matches for "${args.query}" in ${root}. ${hint}\n` +
@@ -1,7 +1,8 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { assertIndexRoot, memoryRootFor, normalizeCitationFiles, resolveSafeIndexRoot } from '../util/fs.js'
3
- import { ProjectMemoryStore } from '../store.js'
4
- import { cfgInsight, saveInsight, GlobalStore, defaultGlobalFile } from '../insight-store.js'
2
+ import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
+ import { openProjectContext } from './context.js'
4
+ import { normalizeCitationFiles } from '../util/fs.js'
5
+ import { saveInsight, GlobalStore, defaultGlobalFile } from '../insight-store.js'
5
6
  import { ensureGlobalInit } from '../global-seed.js'
6
7
  import { vectorItemsFrom } from '../vector-index.js'
7
8
  import { createWriteCosine } from '../auto-inject.js'
@@ -23,26 +24,15 @@ export function rememberTool(config) {
23
24
  required: true,
24
25
  description: 'concrete fix',
25
26
  },
26
- root: {
27
- type: 'string',
28
- description: 'project root (default: cwd)',
29
- },
27
+ root: rootParam(),
30
28
  source_file: {
31
29
  type: 'string',
32
30
  description: 'related file (project-relative)',
33
31
  },
34
32
  },
35
- output: {
36
- schema: { type: 'string' },
37
- render: (_args, value) => [{ type: 'text', text: value }],
38
- },
33
+ output: TEXT_OUTPUT,
39
34
  async execute(args, exec) {
40
- const root = resolveSafeIndexRoot(exec, args.root, config)
41
- // 写盘前校验根:否则一个拼错的 root 会被 mkdir 成字面量目录(连同 .dsh-project-memory)。
42
- assertIndexRoot(root, args.root || root)
43
- const memoryDir = memoryRootFor(root, config.memoryDir)
44
- const store = new ProjectMemoryStore(memoryDir).load()
45
- const cfg = cfgInsight(config)
35
+ const { root, memoryDir, store, cfg } = openProjectContext(exec, args, config)
46
36
  // 与 save_lesson 同一条约束:files 只收项目内相对路径,项目外/逃出根的丢弃并回报。
47
37
  const citation = normalizeCitationFiles(args.source_file ? [args.source_file] : [], root)
48
38
  ensureGlobalInit(config) // 幂等:project 写入可能被自动提升到 global
@@ -69,7 +59,7 @@ export function rememberTool(config) {
69
59
  const dropped = citation.dropped.length
70
60
  ? `\n(${citation.dropped.length} 个 source_file 不是项目内路径,已丢弃)`
71
61
  : ''
72
- 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)}`
73
63
  },
74
64
  })
75
65
  }
@@ -1,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
2
3
  import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
4
  import { ProjectMemoryStore, storeOverview } from '../store.js'
4
5
  import { cfgInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
@@ -11,19 +12,13 @@ const TOP_N = 30
11
12
 
12
13
  export function statsTool(config) {
13
14
  return defineTool({
14
- name: 'memory_stats',
15
+ name: 'pm_stats',
15
16
  description:
16
17
  'Show store totals, last index time and the per-file index list.',
17
18
  parameters: {
18
- root: {
19
- type: 'string',
20
- description: 'project root (default: cwd)',
21
- },
22
- },
23
- output: {
24
- schema: { type: 'string' },
25
- render: (_args, value) => [{ type: 'text', text: value }],
19
+ root: rootParam(),
26
20
  },
21
+ output: TEXT_OUTPUT,
27
22
  async execute(args, exec) {
28
23
  const root = resolveSafeIndexRoot(exec, args.root, config)
29
24
  // 读路径也要验根存在:可选的向量层(leanvec)在索引空 store 时会落盘 vectors 缓存,
@@ -1,6 +1,6 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
- import { ProjectMemoryStore } from '../store.js'
2
+ import { TEXT_OUTPUT, rootParam } from './output.js'
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'
6
6
  import { genTaskId, hash8, adoptStepsToSession, shouldAdoptToHost } from '../setup/taskbridge.js'
@@ -21,13 +21,11 @@ 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
- output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
26
+ output: TEXT_OUTPUT,
27
27
  async execute(args, exec) {
28
- const root = resolveSafeIndexRoot(exec, args.root, config)
29
- assertIndexRoot(root, args.root || root)
30
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
28
+ const { store } = openProjectContext(exec, args, config)
31
29
  const tasks = store.getTasks()
32
30
  if (!tasks.length) {
33
31
  return '任务记录: 0 套(先做一步再建清单,或用 select_task 新建)'
@@ -44,18 +42,17 @@ export function selectTaskTool(config, host) {
44
42
  return defineTool({
45
43
  name: 'select_task',
46
44
  description:
47
- 'Bind the session to a task (its todo list and files read afterwards sync into it). Exact taskId, or an exact title match'
48
- + '(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.',
49
48
  parameters: {
50
49
  taskId: { type: 'string', description: 'exact task id' },
51
50
  title: { type: 'string', description: 'exact title; creates if absent' },
52
- root: { type: 'string', description: 'project root (default: cwd)' },
51
+ root: rootParam(),
53
52
  },
54
- output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
53
+ output: TEXT_OUTPUT,
55
54
  async execute(args, exec) {
56
- const root = resolveSafeIndexRoot(exec, args.root, config)
57
- assertIndexRoot(root, args.root || root)
58
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
55
+ const { root, store } = openProjectContext(exec, args, config)
59
56
  const sid = sessionIdOf(exec)
60
57
  const now = new Date().toISOString()
61
58
  const error = (msg) => truncate(JSON.stringify({ success: false, error: msg }), config.maxOutputChars)
@@ -124,7 +121,7 @@ export function selectTaskTool(config, host) {
124
121
 
125
122
  // 反向接管:绑定成功后,把任务步骤推成宿主 todo/write(dsh 清单跟随我们的任务)
126
123
  if (shouldAdoptToHost(config)) {
127
- adoptStepsToSession(exec?.agent?.session || exec?.ctx?.session, task)
124
+ adoptStepsToSession(exec?.agent?.session || exec?.ctx?.session, task, { force: true })
128
125
  }
129
126
 
130
127
  // 反思钩子:切走旧任务时异步收割(默认关,零成本;失败只记日志)
@@ -139,6 +136,7 @@ export function selectTaskTool(config, host) {
139
136
  files: task.files,
140
137
  insights: task.insights || [], // v0.5:任务级 lessons/decisions/procedures
141
138
  hint: hint + ';请据此用 todo_write 重建本会话清单',
139
+ ...(store.lastSaveOk === false ? { persisted: false, warning: '内存已绑定,但 tasks.json 未落盘(权限/磁盘/锁);退出前会重试。' } : {}),
142
140
  }
143
141
  return truncate(JSON.stringify(card), config.maxOutputChars)
144
142
  },
@@ -150,7 +148,7 @@ export function showTaskPanelTool(config) {
150
148
  name: 'show_task_panel',
151
149
  description: 'Open the task panel in the UI.',
152
150
  parameters: {},
153
- output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
151
+ output: TEXT_OUTPUT,
154
152
  async execute() {
155
153
  // 开面板的动作在**客户端**:这个工具名被 src/client/ShowTaskPanelNode.tsx 认领,
156
154
  // 结果节点一渲染就由浏览器侧调 `taskUIStore.open()`。
@@ -170,13 +168,11 @@ export function archiveTaskTool(config, host) {
170
168
  description: 'Archive a task (restore by selecting it again).',
171
169
  parameters: {
172
170
  taskId: { type: 'string', required: true, description: 'task id' },
173
- root: { type: 'string', description: 'project root (default: cwd)' },
171
+ root: rootParam(),
174
172
  },
175
- output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
173
+ output: TEXT_OUTPUT,
176
174
  async execute(args, exec) {
177
- const root = resolveSafeIndexRoot(exec, args.root, config)
178
- assertIndexRoot(root, args.root || root)
179
- const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
175
+ const { root, store } = openProjectContext(exec, args, config)
180
176
  const task = store.getTask(args.taskId)
181
177
  if (!task) return truncate(JSON.stringify({ success: false, error: 'Task not found' }), config.maxOutputChars)
182
178
  if (task.archived) return truncate(JSON.stringify({ success: false, error: 'Already archived' }), config.maxOutputChars)
@@ -190,7 +186,12 @@ export function archiveTaskTool(config, host) {
190
186
  store.save()
191
187
  // 反思钩子:归档即收割最终教训(默认关)
192
188
  fireReflect(config, host, root, args.taskId, 'archive', resolveRoute(exec, config))
193
- 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)
194
195
  },
195
196
  })
196
197
  }