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

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.
package/src/store.js CHANGED
@@ -6,6 +6,7 @@ import { acquireDirLock, storeKey, unlinkWithRetry, writeJsonAtomic } from './ut
6
6
  import { debugPersistence } from './util/persist.js'
7
7
  import { trackDirty, untrackDirty } from './util/flush.js'
8
8
  import { backfillDerivedTriggers } from './readiness.js'
9
+ import { isRecord, newerIso } from './util/value.js'
9
10
 
10
11
  const FORMAT_FILE = 'format.json'
11
12
  const INDEX_FILE = 'index.json'
@@ -236,18 +237,6 @@ export function _storeCacheKeysForTest() {
236
237
  /** 已就"无法迁移的旧 store"告警过的目录:避免每次 load() 都刷一行。 */
237
238
  const migrationWarned = new Set()
238
239
 
239
- /** 纯对象判定(排除 null / 数组):磁盘读入的 JSON 形状校验统一走它。 */
240
- function isRecord(value) {
241
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
242
- }
243
-
244
- /** 两个 ISO 时间戳的先后;缺失/非法一律 0,保证可比较。 */
245
- function newerIso(a, b) {
246
- const ta = Date.parse(a || '') || 0
247
- const tb = Date.parse(b || '') || 0
248
- return ta - tb
249
- }
250
-
251
240
  /**
252
241
  * 合并同一任务在两份快照里的 `insights`:以**上次落盘的 id 基线**做三方判断,基线没有、
253
242
  * 本地有 → 本地新增;基线有、本地没有 → 本地删除(不复活);两边都有 → `updatedAt` 新者胜。
@@ -435,6 +424,11 @@ export class ProjectMemoryStore {
435
424
  this._dirtyBinding = false
436
425
  this._dirtyWatch = false
437
426
  this._formatWritten = false
427
+ /**
428
+ * 旧库迁移被保护性跳过(entries.json 有数据但 index.json 缺失/损坏)。
429
+ * 置位后 save() 不允许写 format.json:那个标记会让下一次 load 把旧文件当迁移残留删掉。
430
+ */
431
+ this._legacyBlocked = false
438
432
  this._idfCache = null
439
433
  /** entries 的变更计数:IDF 缓存与符号索引(读取期链接)都据此失效。 */
440
434
  this._entriesVersion = 0
@@ -490,9 +484,32 @@ export class ProjectMemoryStore {
490
484
  return this
491
485
  }
492
486
 
487
+ /** 迁移保护:置位后 save() 不写 format.json,下一次 load 会重试迁移而不是删旧文件。 */
488
+ _markLegacyBlocked(message) {
489
+ this._legacyBlocked = true
490
+ if (migrationWarned.has(this.dir)) return
491
+ migrationWarned.add(this.dir)
492
+ console.error(`[dsh-project-memory] ${message}`)
493
+ }
494
+
493
495
  _migrateLegacyIfNeeded() {
494
496
  const formatPath = path.join(this.dir, FORMAT_FILE)
495
- if (loadJson(formatPath, null)?.version === 2) {
497
+ const formatDoc = loadJson(formatPath, null)
498
+ if (formatDoc?.version === 2) {
499
+ // 危险组合:format.json 已经写了,但 entries.json 还有数据/读不出来。正常迁移的标记带
500
+ // `migratedFrom`;没有它就是"某次 save() 在迁移被跳过后补写了 format"(旧版只把
501
+ // !formatWritten 当脏)。这时绝不能把 entries.json 当迁移残留删掉——那正是整库静默消失的路径。
502
+ const legacyEntriesPathV2 = path.join(this.dir, ENTRIES_FILE)
503
+ let legacyV2 = null
504
+ if (existsSafe(legacyEntriesPathV2)) legacyV2 = loadJson(legacyEntriesPathV2, null)
505
+ const legacyHasPayload = isRecord(legacyV2) && Object.keys(legacyV2).length > 0
506
+ const legacyUnreadable = existsSafe(legacyEntriesPathV2) && !isRecord(legacyV2)
507
+ if (formatDoc.migratedFrom !== 'legacy' && (legacyHasPayload || legacyUnreadable)) {
508
+ this._markLegacyBlocked(
509
+ `legacy ${ENTRIES_FILE} still exists next to a non-migration ${FORMAT_FILE}; keeping it (delete the stale ${FORMAT_FILE} after migrating manually)`,
510
+ )
511
+ return
512
+ }
496
513
  // 迁移在“写完标记、删旧文件前”崩溃会留下死文件;这里顺手清掉
497
514
  for (const stale of [path.join(this.dir, ENTRIES_FILE), path.join(this.dir, INDEX_FILE)]) {
498
515
  if (existsSafe(stale)) {
@@ -514,7 +531,9 @@ export class ProjectMemoryStore {
514
531
  const entries = loadJson(legacyEntriesPath, null)
515
532
  if (!isRecord(index) || !isRecord(entries)) {
516
533
  const hasEntries = isRecord(entries) && Object.keys(entries).length > 0
517
- if (!hasEntries) {
534
+ // entries.json 读不出来但文件仍在(loadJson 的备份也失败了):同样按"有数据"保护。
535
+ const unreadableEntries = !isRecord(entries) && existsSafe(legacyEntriesPath)
536
+ if (!hasEntries && !unreadableEntries) {
518
537
  // entries 损坏(已备份)或本就是空的:没有可保护的数据,按空旧库收尾。
519
538
  writeJsonAtomic(formatPath, { version: 2, layout: 'sharded' })
520
539
  for (const stale of [legacyEntriesPath, legacyIndexPath]) {
@@ -528,12 +547,23 @@ export class ProjectMemoryStore {
528
547
  }
529
548
  // index.json 是 entries.json → rel 的唯一映射;它缺失时继续迁移会写出 0 个 shard 再删掉
530
549
  // 完好的 entries.json,等于静默清空。保留现场,不写 format 标记,等修好后再迁。
531
- if (!migrationWarned.has(this.dir)) {
532
- migrationWarned.add(this.dir)
533
- console.error(`[dsh-project-memory] legacy store at ${this.dir} has ${ENTRIES_FILE} but no readable ${INDEX_FILE}; migration skipped to protect it`)
534
- }
550
+ this._markLegacyBlocked(
551
+ unreadableEntries
552
+ ? `legacy ${ENTRIES_FILE} is unreadable and could not be backed up; migration skipped to protect it`
553
+ : `legacy store at ${this.dir} has ${ENTRIES_FILE} but no readable ${INDEX_FILE}; migration skipped to protect it`,
554
+ )
535
555
  return
536
556
  }
557
+ if (!isRecord(index.files)) {
558
+ // 与"index.json 缺失"同等对待:entries 非空而 files 不是对象时继续迁移会写出 0 个 shard
559
+ // 再把两个旧文件删掉(只留两行日志)。
560
+ if (Object.keys(entries).length > 0) {
561
+ this._markLegacyBlocked(
562
+ `legacy store at ${this.dir} has ${ENTRIES_FILE} but ${INDEX_FILE} has no readable files map; migration skipped to protect it`,
563
+ )
564
+ return
565
+ }
566
+ }
537
567
  const files = isRecord(index.files) ? index.files : {}
538
568
  const orphans = Object.keys(entries).filter((rel) => !(rel in files))
539
569
  if (orphans.length) {
@@ -551,7 +581,7 @@ export class ProjectMemoryStore {
551
581
  }
552
582
  writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: files[rel], entries: list.map(withoutPersistedDerived) })
553
583
  }
554
- writeJsonAtomic(formatPath, { version: 2, layout: 'sharded' })
584
+ writeJsonAtomic(formatPath, { version: 2, layout: 'sharded', migratedFrom: 'legacy' })
555
585
  for (const stale of [legacyEntriesPath, path.join(this.dir, INDEX_FILE)]) {
556
586
  try {
557
587
  unlinkSync(stale)
@@ -640,7 +670,16 @@ export class ProjectMemoryStore {
640
670
  else if (task.insights !== undefined) task.insights = []
641
671
  if (Array.isArray(task.files)) task.files = task.files.filter((f) => typeof f === 'string' && f)
642
672
  else task.files = []
673
+ // `steps` 是第三条:对象/字符串形状会让 `(task.steps || []).map` 与 `for...of` 抛错,
674
+ // 而 pre-step 的 catch 会把整步注入降级(连 project/global insight 一起不注入)。
675
+ if (!Array.isArray(task.steps)) task.steps = []
643
676
  if (!isRecord(task.fileMeta)) task.fileMeta = {}
677
+ else {
678
+ // 单个 rel 的值不是对象时 `touchTaskFile()` 会往字符串上写属性而抛错:按空对象归一。
679
+ for (const rel of Object.keys(task.fileMeta)) {
680
+ if (!isRecord(task.fileMeta[rel])) task.fileMeta[rel] = {}
681
+ }
682
+ }
644
683
  }
645
684
  const bindingDoc = this._loadJson(path.join(this.dir, BINDING_FILE), {})
646
685
  this.binding = isRecord(bindingDoc) ? bindingDoc : {}
@@ -729,11 +768,17 @@ export class ProjectMemoryStore {
729
768
  this.insights = { ...diskDoc, items: diskDoc.items.filter(isRecord) }
730
769
  } else {
731
770
  const now = new Date().toISOString()
732
- const known = new Set(this.insights.items.map((it) => it.id))
771
+ // 锁内重读到的 diskDoc 可能已有另一个进程刚写入的条目(只是还没写 migratedAt)。
772
+ // 不能拿等锁前的 this.insights 整份覆盖:那会把对方的条目静默丢掉。
773
+ const baseDoc = isRecord(diskDoc) && Array.isArray(diskDoc.items)
774
+ ? { ...diskDoc, items: diskDoc.items.filter(isRecord) }
775
+ : this.insights
776
+ const mergedItems = [...baseDoc.items]
777
+ const known = new Set(mergedItems.map((it) => it.id))
733
778
  for (const item of legacy) {
734
779
  if (!item || !item.problem || known.has(item.id)) continue
735
780
  known.add(item.id)
736
- this.insights.items.push({
781
+ mergedItems.push({
737
782
  id: item.id,
738
783
  kind: 'experience',
739
784
  scope: 'project',
@@ -751,7 +796,7 @@ export class ProjectMemoryStore {
751
796
  })
752
797
  imported++
753
798
  }
754
- this.insights.migratedAt = now
799
+ this.insights = { ...baseDoc, items: mergedItems, migratedAt: now }
755
800
  mkdirSync(this.dir, { recursive: true })
756
801
  writeJsonAtomic(insightsPath, this.insights, { ensureDir: false })
757
802
  }
@@ -881,6 +926,10 @@ export class ProjectMemoryStore {
881
926
  // 没有脏数据就不落盘:watch 每轮对每个根都无条件 commit → save,否则末尾的 IDF 缓存失效
882
927
  // 会打在跨实例共享的 store 上,等于每轮清空一次复用。待压实队列不算脏,但也要有界推进。
883
928
  const compacting = this._compactQueue.size > 0
929
+ // `!formatWritten` 只在**真有内容**时才算脏:否则一次空提交(或 global-only 写入后
930
+ // 对 project store 的 commit)就会给没有记忆的项目造出 `.dsh-project-memory/format.json`,
931
+ // 还会被 nestedStoreRoots 当成“自带 store 的嵌套项目”跳过整棵子树。
932
+ const hasContent = this.hasContent
884
933
  const dirty =
885
934
  compacting ||
886
935
  this._dirtyShards.size > 0 ||
@@ -889,7 +938,7 @@ export class ProjectMemoryStore {
889
938
  this._dirtyTasks ||
890
939
  this._dirtyBinding ||
891
940
  this._dirtyWatch ||
892
- !this._formatWritten
941
+ (!this._formatWritten && !this._legacyBlocked && hasContent)
893
942
  if (dirty) {
894
943
  // 目录可能在 load 之后被外部删掉:`_storeDirReady` 只当"上次写过"的快路径,命中时补一次
895
944
  // stat;失配就重建目录,并让分片/格式/忽略三处的已就绪状态一起失效。
@@ -945,7 +994,7 @@ export class ProjectMemoryStore {
945
994
  try {
946
995
  // 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
947
996
  this._mergeAuxFromDisk()
948
- if (!this._formatWritten) {
997
+ if (!this._formatWritten && !this._legacyBlocked) {
949
998
  writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' }, { ensureDir: false })
950
999
  this._formatWritten = true
951
1000
  }
@@ -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 } 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 里截断。 */
@@ -29,30 +29,23 @@ export function forgetTool(config) {
29
29
  return defineTool({
30
30
  name: 'forget',
31
31
  description:
32
- 'Delete memories by id or matching keywords, at task/project/global scope. Real deletion, no undo; '
33
- + 'the last 5 deleted entries are kept in deleted.json. A keyword matching more than the cap deletes nothing '
34
- + 'and lists the candidates instead.',
32
+ 'Delete memories by id or keywords (task/project/global). Real deletion, no undo; '
33
+ + 'the last 5 deleted entries stay in deleted.json. Above the match cap nothing is deleted, '
34
+ + 'only the candidates are listed.',
35
35
  parameters: {
36
36
  id_or_query: {
37
37
  type: 'string',
38
38
  required: true,
39
- description: '精确 id 或关键词;id 优先',
39
+ description: 'exact id or keywords; id takes priority',
40
40
  },
41
41
  root: {
42
42
  type: 'string',
43
- description: '项目根(默认当前工作目录)',
43
+ description: 'project root (default: cwd)',
44
44
  },
45
45
  },
46
- output: {
47
- schema: { type: 'string' },
48
- render: (_args, value) => [{ type: 'text', text: value }],
49
- },
46
+ output: TEXT_OUTPUT,
50
47
  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)
48
+ const { memoryDir, store, cfg } = openProjectContext(exec, args, config)
56
49
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
57
50
  let res
58
51
  store.commit((s) => {
@@ -1,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT } from './output.js'
2
3
  import path from 'node:path'
3
4
  import { statSync } from 'node:fs'
4
5
  import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
@@ -15,17 +16,14 @@ export function indexDocTool(ctx, config) {
15
16
  file_path: {
16
17
  type: 'string',
17
18
  required: true,
18
- description: '文档绝对路径',
19
+ description: 'absolute path of the document',
19
20
  },
20
21
  root: {
21
22
  type: 'string',
22
- description: '项目根(默认会话项目根)',
23
+ description: 'project root (default: session project root)',
23
24
  },
24
25
  },
25
- output: {
26
- schema: { type: 'string' },
27
- render: (_args, value) => [{ type: 'text', text: value }],
28
- },
26
+ output: TEXT_OUTPUT,
29
27
  async execute(args, exec) {
30
28
  const filePath = assertReadableFile(args.file_path, config.maxFileSizeMb)
31
29
  // roots.exclude 是"这棵子树里的文件一律不进索引":显式 index_doc 也要服从。
@@ -1,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT } from './output.js'
2
3
  import path from 'node:path'
3
4
  import { statSync } from 'node:fs'
4
5
  import { assertIndexRoot, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, resolveIndexRoot, scanLimits, storeKey } from '../util/fs.js'
@@ -150,17 +151,14 @@ export function indexRepoTool(ctx, config) {
150
151
  root: {
151
152
  type: 'string',
152
153
  required: true,
153
- description: '项目根(相对路径按会话当前工作目录解析)',
154
+ description: 'project root (relative: session cwd)',
154
155
  },
155
156
  reindex: {
156
157
  type: 'boolean',
157
- description: '忽略哈希,强制重抽',
158
+ description: 'ignore hashes, force re-extraction',
158
159
  },
159
160
  },
160
- output: {
161
- schema: { type: 'string' },
162
- render: (_args, value) => [{ type: 'text', text: value }],
163
- },
161
+ output: TEXT_OUTPUT,
164
162
  async execute(args, exec) {
165
163
  // 相对 root 按会话当前工作目录解析(不是宿主进程 cwd)——见 util/fs.js 的 resolveIndexRoot。
166
164
  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 } 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'
@@ -10,24 +11,25 @@ import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
10
11
  import { createWriteCosine } from '../auto-inject.js'
11
12
 
12
13
  export function lessonTool(config) {
13
- const kindDesc = 'lesson(坑→改法) | decision(选择+理由) | procedure(步骤) | experience(问题→解法);默认 lesson。'
14
+ const kindDesc = 'lesson (pitfall → fix) | decision (choice + reason) | procedure (steps) | experience (problem → solution); default lesson.'
14
15
  const scopeDesc =
15
- 'task(任务私有) | project(项目资产) | global(跨项目);默认:绑定任务时 task,否则 project;给 id 时就地更新。'
16
+ 'task | project | global; default: task when a task is bound, else project; passing id updates in place.'
16
17
  return defineTool({
17
18
  name: 'save_lesson',
18
19
  description:
19
- '写入一条教训 / 决策 / 流程(单条 insight)。只写下次仍成立的判据与命令;某次运行的值(版本号、计数、分支名)不进正文。写入前与既有记忆比对:高相似度自动覆盖(旧值留在 prev),'
20
- + '较近的提示近邻 id。发现记错/过时:带 id 再写一次即就地覆盖;确定要删用 forget。',
20
+ 'One lesson / decision / procedure (a single insight). Keep only the criterion and command that stay true next time; run-specific values (version numbers, counts, branch names) stay out. '
21
+ + 'It compares against existing memory first: high similarity overwrites (old value kept in prev), a near match returns the nearest id. '
22
+ + 'If an entry you saw is wrong, stale or too thin to act on, pass its id and write again to update it in place instead of adding a new one; use forget to delete.',
21
23
  parameters: {
22
- id: { type: 'string', description: '既有条目 id(就地更新,忽略 scope)' },
23
- title: { type: 'string', description: '一行标题' },
24
+ id: { type: 'string', description: 'existing entry id (in-place update)' },
25
+ title: { type: 'string', description: 'one-line title' },
24
26
  kind: { type: 'string', enum: INSIGHT_KINDS, description: kindDesc },
25
27
  scope: { type: 'string', enum: INSIGHT_SCOPES, description: scopeDesc },
26
- pattern: { type: 'string', description: '错误模式' },
27
- fix: { type: 'string', description: '修正做法' },
28
- choice: { type: 'string', description: '选了什么' },
29
- reason: { type: 'string', description: '为什么' },
30
- steps: { type: 'array', items: { type: 'string' }, description: '有序步骤' },
28
+ pattern: { type: 'string', description: 'error pattern' },
29
+ fix: { type: 'string', description: 'corrected practice' },
30
+ choice: { type: 'string', description: 'what was chosen' },
31
+ reason: { type: 'string', description: 'why' },
32
+ steps: { type: 'array', items: { type: 'string' }, description: 'ordered steps' },
31
33
  trigger: {
32
34
  type: 'object',
33
35
  additionalProperties: false,
@@ -37,23 +39,23 @@ export function lessonTool(config) {
37
39
  additionalProperties: false,
38
40
  properties: {
39
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' },
40
- writes: { type: 'array', items: { type: 'string' }, description: '项目相对路径,禁 glob' },
41
- intents: { type: 'array', items: { type: 'string' }, description: '意图词(CJK≥2,拉丁≥5)' },
42
+ writes: { type: 'array', items: { type: 'string' }, description: 'project-relative paths, no glob' },
43
+ intents: { type: 'array', items: { type: 'string' }, description: 'intent words (CJK ≥2, latin ≥5)' },
42
44
  },
43
- description: '唯一触发面:三者取或;不写则只能靠检索命中,不会主动注入。',
45
+ description: 'the only trigger surface: any of the three; without it the entry is retrieval-only.',
44
46
  },
45
47
  guard: {
46
48
  type: 'object',
47
49
  additionalProperties: false,
48
50
  properties: {
49
- paths: { type: 'array', items: { type: 'string' }, description: '写目标须命中其一' },
51
+ paths: { type: 'array', items: { type: 'string' }, description: 'write target must match one of them' },
50
52
  not_paths: { type: 'array', items: { type: 'string' } },
51
- hosts: { type: 'array', items: { type: 'string' }, description: '如 wsl' },
52
- tags: { type: 'array', items: { type: 'string' }, description: '画像 tag 交集' },
53
+ hosts: { type: 'array', items: { type: 'string' }, description: 'e.g. wsl' },
54
+ tags: { type: 'array', items: { type: 'string' }, description: 'profile tag intersection' },
53
55
  },
54
- description: '收窄条件:全部满足才放行。',
56
+ description: 'narrowing conditions: all must hold.',
55
57
  },
56
- prevents: { type: 'string', description: '不知道它会做错什么' },
58
+ prevents: { type: 'string', description: 'what breaks without this entry' },
57
59
  // 旧字段:历史条目与旧调用仍可能带它们,保留形状但不占描述预算。
58
60
  keywords: { type: 'array', items: { type: 'string' } },
59
61
  symbols: { type: 'array', items: { type: 'string' } },
@@ -61,23 +63,19 @@ export function lessonTool(config) {
61
63
  paths: { type: 'array', items: { type: 'string' } },
62
64
  scope: { type: 'array', items: { type: 'string' } },
63
65
  },
64
- description: '命中即在动手前注入;when 是唯一触发面,guard 只能收窄。',
66
+ description: 'injects before acting when matched; when is the only trigger surface.',
65
67
  },
66
- task_id: { type: 'string', description: '目标任务 id' },
67
- files: { type: 'array', items: { type: 'string' }, description: '关联文件(项目相对)' },
68
- symbols: { type: 'array', items: { type: 'string' }, description: '关联符号' },
68
+ task_id: { type: 'string', description: 'target task id' },
69
+ files: { type: 'array', items: { type: 'string' }, description: 'related files (project-relative)' },
70
+ symbols: { type: 'array', items: { type: 'string' }, description: 'related symbols' },
69
71
  confidence: { type: 'number', description: '0..1' },
70
- root: { type: 'string', description: '项目根' },
72
+ root: { type: 'string', description: 'project root' },
71
73
  },
72
- output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
74
+ output: TEXT_OUTPUT,
73
75
  async execute(args, exec) {
74
- const root = resolveSafeIndexRoot(exec, args.root, config)
75
- assertIndexRoot(root, args.root || root)
76
+ const { root, memoryDir, store, cfg } = openProjectContext(exec, args, config)
76
77
  // 写入期约束:files 只收项目内相对路径(schema 早就这么承诺,此前没有校验)。
77
78
  const citationFiles = normalizeCitationFiles(args.files, root)
78
- const memoryDir = memoryRootFor(root, config.memoryDir)
79
- const store = new ProjectMemoryStore(memoryDir).load()
80
- const cfg = cfgInsight(config)
81
79
  const sid = sessionIdOf(exec)
82
80
  const boundTaskId = sid ? store.getBoundTaskId(sid) : undefined
83
81
  const taskId = args.task_id || boundTaskId
@@ -0,0 +1,5 @@
1
+ // 纯文本工具结果:所有工具共用的 output 声明;宿主按 render 出文本块。
2
+ export const TEXT_OUTPUT = {
3
+ schema: { type: 'string' },
4
+ render: (_args, value) => [{ type: 'text', text: value }],
5
+ }
@@ -1,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT } 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'
@@ -61,31 +62,29 @@ export function queryMemoryTool(ctx, config) {
61
62
  name: 'query_memory',
62
63
  description:
63
64
  'Search project memory: docs, symbols, experience and insights. Returns cited sources or insight ids. '
64
- + 'Use before grepping for orientation, a spec constraint, or a past decision.',
65
+ + 'Use before grepping for orientation, a spec constraint, or a past decision. '
66
+ + 'After a query, update stale or wrong entries right away (save_lesson with that id).',
65
67
  parameters: {
66
68
  query: {
67
69
  type: 'string',
68
70
  required: true,
69
- description: 'What to look for',
71
+ description: 'what to look for',
70
72
  },
71
73
  root: {
72
74
  type: 'string',
73
- description: '项目根(默认当前工作目录)',
75
+ description: 'project root (default: cwd)',
74
76
  },
75
77
  type: {
76
78
  type: 'string',
77
79
  enum: ['all', 'doc', 'symbol', 'experience', 'insight', 'task'],
78
- description: 'all|doc|symbol|experience|insight|task;默认 all',
80
+ description: 'all|doc|symbol|experience|insight|task; default all',
79
81
  },
80
82
  limit: {
81
83
  type: 'number',
82
- description: '最多返回条数,默认 8',
84
+ description: 'max results, default 8',
83
85
  },
84
86
  },
85
- output: {
86
- schema: { type: 'string' },
87
- render: (_args, value) => [{ type: 'text', text: value }],
88
- },
87
+ output: TEXT_OUTPUT,
89
88
  async execute(args, exec) {
90
89
  const root = resolveSafeIndexRoot(exec, args.root, config)
91
90
  // 读路径也要验根存在。这条不是洁癖:可选的向量层(leanvec)在空 store 上会建
@@ -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 } 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'
@@ -11,38 +12,30 @@ export function rememberTool(config) {
11
12
  name: 'remember',
12
13
  description:
13
14
  'Save a problem→solution note as kind:experience; same dedup as save_lesson. '
14
- + 'Prefer save_lesson for anything that is not a problem→solution note.',
15
+ + 'Prefer save_lesson for anything else.',
15
16
  parameters: {
16
17
  problem: {
17
18
  type: 'string',
18
19
  required: true,
19
- description: '问题/现象',
20
+ description: 'problem / symptom',
20
21
  },
21
22
  solution: {
22
23
  type: 'string',
23
24
  required: true,
24
- description: '具体解法',
25
+ description: 'concrete fix',
25
26
  },
26
27
  root: {
27
28
  type: 'string',
28
- description: '项目根(默认当前工作目录)',
29
+ description: 'project root (default: cwd)',
29
30
  },
30
31
  source_file: {
31
32
  type: 'string',
32
- description: '关联文件(项目相对)',
33
+ description: 'related file (project-relative)',
33
34
  },
34
35
  },
35
- output: {
36
- schema: { type: 'string' },
37
- render: (_args, value) => [{ type: 'text', text: value }],
38
- },
36
+ output: TEXT_OUTPUT,
39
37
  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)
38
+ const { root, memoryDir, store, cfg } = openProjectContext(exec, args, config)
46
39
  // 与 save_lesson 同一条约束:files 只收项目内相对路径,项目外/逃出根的丢弃并回报。
47
40
  const citation = normalizeCitationFiles(args.source_file ? [args.source_file] : [], root)
48
41
  ensureGlobalInit(config) // 幂等:project 写入可能被自动提升到 global
@@ -1,4 +1,5 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import { TEXT_OUTPUT } 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'
@@ -17,13 +18,10 @@ export function statsTool(config) {
17
18
  parameters: {
18
19
  root: {
19
20
  type: 'string',
20
- description: '项目根(默认当前工作目录)',
21
+ description: 'project root (default: cwd)',
21
22
  },
22
23
  },
23
- output: {
24
- schema: { type: 'string' },
25
- render: (_args, value) => [{ type: 'text', text: value }],
26
- },
24
+ output: TEXT_OUTPUT,
27
25
  async execute(args, exec) {
28
26
  const root = resolveSafeIndexRoot(exec, args.root, config)
29
27
  // 读路径也要验根存在:可选的向量层(leanvec)在索引空 store 时会落盘 vectors 缓存,