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

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/ops.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // 路径 token 规则收在 util/path-token.js —— 它无依赖,两个模块共用。
6
6
 
7
7
  import { extractPathTokens } from './util/path-token.js'
8
+ import { patchFilePaths } from './util/patch.js'
8
9
 
9
10
  /** op 闭集。新增一个 op 必须同时想清楚:它是动作,不是话题。 */
10
11
  export const OP_IDS = [
@@ -59,7 +60,7 @@ export const LEGACY_ACTION_ALIAS = {
59
60
  'write-docs': null,
60
61
  }
61
62
 
62
- const WRITE_TOOLS = new Set(['write', 'edit', 'multi_edit', 'apply_patch', 'str_replace', 'create_file', 'notebook_edit'])
63
+ const WRITE_TOOLS = new Set(['write', 'edit', 'multi_edit', 'str_replace', 'create_file', 'notebook_edit'])
63
64
  const READ_IMAGE_TOOLS = new Set(['read_image'])
64
65
  const INDEX_TOOLS = new Set(['index_doc', 'index_repo', 'watch_repo'])
65
66
  const FETCH_TOOLS = new Set(['web_fetch', 'web_search'])
@@ -156,19 +157,51 @@ function tokenizeWords(segment) {
156
157
  return out
157
158
  }
158
159
 
159
- /** 跳过环境变量赋值与 sudo/env/time 之类包装,返回真正的命令头与参数。 */
160
+ /** shell 复合命令的关键字:它们不是可执行命令,跳过后再取真正的命令头。 */
161
+ const SHELL_KEYWORDS = new Set([
162
+ 'if', 'then', 'else', 'elif', 'fi', 'while', 'until', 'for', 'do', 'done',
163
+ 'case', 'esac', 'function', 'in', 'select', 'time',
164
+ ])
165
+ /**
166
+ * 包装器带值的选项:`nice -n 10 npm publish` / `sudo -u user rm` / `env -u NAME rm`。
167
+ * 只跳过选项本身不够——值会被当成命令头,动作与写目标一起丢。
168
+ */
169
+ const WRAPPER_VALUE_FLAGS = new Set([
170
+ '-n', '--adjustment', '-u', '--user', '-g', '--group', '-C', '--chdir', '-p', '--prompt',
171
+ '-r', '--role', '-t', '--type', '-U', '--other-user', '-f', '--format', '-o', '--output',
172
+ '-S', '--split-string', '-c', '--command', '-D', '--chdir',
173
+ ])
174
+
175
+ /** 跳过环境变量赋值、包装器(及其选项/值)与 shell 关键字,返回真正的命令头与参数。 */
160
176
  function commandHead(tokens) {
161
177
  let i = 0
178
+ /** 最近一个包装器:`time -p` 与 `sudo -p <prompt>` 的 -p 语义不同,需要知道是谁。 */
179
+ let wrapper = null
162
180
  while (i < tokens.length) {
163
181
  const t = tokens[i]
164
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || WRAPPERS.has(t) || t === '(') { i++; continue }
182
+ if (WRAPPERS.has(t)) { wrapper = t; i++; continue }
183
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || SHELL_KEYWORDS.has(t)) { i++; continue }
184
+ if (t === '(' || t === '{' || t === '}' || t === ')') { i++; continue }
185
+ if (t.startsWith('-') && t !== '-') {
186
+ // 包装器/命令的选项:带值的连值一起跳,避免把值当成可执行命令。
187
+ // `time -p` 是 POSIX 的“不打印计时”,不带值;其余同名 -p(sudo -p prompt)带值。
188
+ const takesValue = WRAPPER_VALUE_FLAGS.has(t) && !(wrapper === 'time' && t === '-p')
189
+ if (takesValue && i + 1 < tokens.length) i += 2
190
+ else i++
191
+ continue
192
+ }
165
193
  break
166
194
  }
167
- const raw = tokens[i] || ''
195
+ let raw = tokens[i] || ''
196
+ // `(rm` / `{rm` 这类紧挨着的分段:剥掉开头括号再取命令头。
197
+ raw = raw.replace(/^[({]+/, '')
168
198
  // 目录(两种分隔符)+ Windows 可执行后缀都要剥:`C:\Program Files\nodejs\npm.cmd` → `npm`。
169
199
  // 只 `split('/')` 会让 Windows 上的绝对路径命令头整个失配,`.cmd`/`.exe` 同理。
170
200
  const head = raw.split(/[\\/]/).pop().toLowerCase().replace(/\.(exe|cmd|bat|com|ps1)$/, '')
171
201
  let rest = tokens.slice(i + 1)
202
+ if (rest.length && /[)}]+$/.test(rest[rest.length - 1])) {
203
+ rest[rest.length - 1] = rest[rest.length - 1].replace(/[)}]+$/, '')
204
+ }
172
205
  if (rest.length && rest[rest.length - 1] === ')') rest = rest.slice(0, -1)
173
206
  return { head, rest }
174
207
  }
@@ -181,8 +214,31 @@ const BENCH_SCRIPT = /^(bench|benchmark)(:[\w.-]+)?$/i
181
214
  /** 包管理器里带值的全局 flag(`npm --prefix x …`)。 */
182
215
  const PM_VALUE_FLAGS = new Set(['-C', '--prefix', '--cwd', '-w', '--workspace', '--filter', '-F', '--dir'])
183
216
 
217
+ /**
218
+ * 包管理器子命令:先扫已知动词(`publish` / `version` / `run` / `exec` …),再退回第一个非选项。
219
+ * 不能直接取第一个非 `-` 参数:`npm --registry <url> publish` / `npm --otp 123456 publish`
220
+ * 会先把 flag 的值当子命令,发布动作因此识别不到(而 `npm publish --registry …` 正常)。
221
+ */
222
+ const PM_VERBS = new Set([
223
+ 'publish', 'pack', 'version', 'run', 'run-script', 'exec', 'dlx', 'x', 'test', 't', 'tst',
224
+ 'install', 'i', 'add', 'remove', 'rm', 'uninstall', 'un', 'update', 'up', 'link', 'why',
225
+ 'audit', 'config', 'init', 'create', 'start', 'stop', 'restart', 'rebuild', 'ci', 'dedupe',
226
+ 'prune', 'outdated', 'view', 'info', 'search', 'login', 'logout', 'whoami', 'owner', 'team',
227
+ 'token', 'deprecate', 'dist-tag', 'unpublish', 'workspace', 'workspaces',
228
+ ])
229
+
184
230
  /** 跳过全局 flag,返回第一个子命令及其后的参数。 */
185
231
  function packageSubcommand(args) {
232
+ for (let i = 0; i < args.length; i++) {
233
+ const a = args[i]
234
+ if (typeof a !== 'string') continue
235
+ if (a.startsWith('-')) {
236
+ if (PM_VALUE_FLAGS.has(a)) i++
237
+ continue
238
+ }
239
+ if (PM_VERBS.has(a.toLowerCase())) return { sub: a.toLowerCase(), rest: args.slice(i + 1) }
240
+ }
241
+ // 没有已知动词:退回旧行为,保留 `yarn bench` / `pnpm dlx …` 这类按脚本名直接跑的形态。
186
242
  for (let i = 0; i < args.length; i++) {
187
243
  if (args[i].startsWith('-')) {
188
244
  if (PM_VALUE_FLAGS.has(args[i])) i++
@@ -391,6 +447,33 @@ export function classifyToolCall(name, argsText) {
391
447
  const tool = String(name || '').toLowerCase()
392
448
  const { command, path } = argsFields(argsText)
393
449
  if (SHELL_TOOLS.has(tool)) return classifyShellCommand(command || String(argsText || ''))
450
+ // 宿主的 `str_replace_editor` 用 path + command(view/create/str_replace/insert),
451
+ // 不是 file_path;view 是读,其余三个才是写。漏掉它时文件编辑既不产 file-write,也进不了
452
+ // TaskBridge 的热点文件。
453
+ if (tool === 'str_replace_editor') {
454
+ const obj = safeJson(argsText) || {}
455
+ const filePath = typeof obj.path === 'string' ? obj.path : ''
456
+ const cmd = typeof obj.command === 'string' ? obj.command.toLowerCase() : ''
457
+ if (!filePath || !['create', 'str_replace', 'insert'].includes(cmd)) {
458
+ return { ops: [], targets: [], hosts: [] }
459
+ }
460
+ const targets = [filePath, ...extractPathTokens(filePath)]
461
+ return { ops: ['file-write'], targets: [...new Set(targets)], hosts: [] }
462
+ }
463
+ // 0.2.2 的 `apply_patch` 没有 path/file_path:目标文件只写在补丁正文的
464
+ // `*** Add/Update/Delete File:` 与 `*** Move to:` 行里。漏掉它时跨文件补丁
465
+ // 只留下一个没有目标的 file-write,审计与热点都指不到具体文件。
466
+ // 同名工具若走 `path`/`file_path`(非 dsh 形状),退回通用路径,别把旧行为弄丢。
467
+ if (tool === 'apply_patch') {
468
+ const obj = safeJson(argsText) || {}
469
+ const files = patchFilePaths(obj.input)
470
+ const fromArgs = files.length > 0
471
+ ? files
472
+ : [obj.file_path, obj.path].filter((v) => typeof v === 'string' && v)
473
+ const targets = fromArgs.flatMap((p) => [p, ...extractPathTokens(p)])
474
+ const hosts = targets.some((t) => WSL_HINT_RE.test(t)) ? ['wsl'] : []
475
+ return { ops: ['file-write'], targets: [...new Set(targets)], hosts }
476
+ }
394
477
  if (READ_IMAGE_TOOLS.has(tool)) return { ops: ['read-image'], targets: [], hosts: [] }
395
478
  if (INDEX_TOOLS.has(tool)) return { ops: ['index-doc'], targets: [], hosts: [] }
396
479
  if (FETCH_TOOLS.has(tool)) return { ops: ['fetch-web'], targets: [], hosts: [] }
package/src/recall.js CHANGED
@@ -152,7 +152,8 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
152
152
  }
153
153
  if (boundTaskId && store && typeof store.getTask === 'function') {
154
154
  const task = store.getTask(boundTaskId)
155
- for (const it of (task && task.insights) || []) {
155
+ // 归档任务不再向绑定会话提供任务级记忆(与 buildInjection 的 task 守卫同一判据)。
156
+ for (const it of (task && !task.archived && task.insights) || []) {
156
157
  if (!it || it.archived) continue
157
158
  // 任务级也要挡草稿:reflection 写的是 draft:true,未确认前不该被召回。
158
159
  if (it.draft === true) continue
@@ -8,8 +8,10 @@ import { sessionWorkingDir } from '../util/session-dir.js'
8
8
  import { ProjectMemoryStore } from '../store.js'
9
9
  import { BoundedMap } from '../util/session-cache.js'
10
10
  import { stepContent, stepStatus } from '../util/task-view.js'
11
+ import { patchFilePaths } from '../util/patch.js'
11
12
 
12
- const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image'])
13
+ // apply_patch 的参数是整段补丁文本,路径在正文里(见 util/patch.js),单独分支处理。
14
+ const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image', 'str_replace_editor', 'apply_patch'])
13
15
  const WRITE_TOOLS = new Set(['write', 'edit']) // 编辑/写入 = 高热点
14
16
  const READ_TOOLS = new Set(['read', 'read_image'])
15
17
  const MAX_FILES_PER_TASK = 100
@@ -266,21 +268,53 @@ export function onSessionEvent(config, session, event, meta, ctx) {
266
268
  } catch {
267
269
  return
268
270
  }
269
- const raw = typeof args?.file_path === 'string' ? args.file_path : null
270
- if (!raw) return
271
- const rel = normalizeRelFile(root, raw)
272
- if (!rel) return
273
- const kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
274
- if (!kind) return
275
271
  // 文件工具调用是最高频的写口:每次 commit 都落盘会把 tasks.json 写成“每读一个文件一次”。
276
272
  // 这里只改内存 + 标脏,回合结束(turn/end)或会话销毁时统一 flush。
277
- store.commit((s) => {
273
+ const record = (rels, kind) => store.commit((s) => {
278
274
  const task = s.getTask(taskId)
279
275
  if (!task || task.archived) return
280
- touchTaskFile(task, rel, kind, now)
276
+ for (const rel of rels) touchTaskFile(task, rel, kind, now)
281
277
  task.lastActiveAt = now
282
278
  s.markTasksDirty()
283
279
  }, { save: false })
280
+
281
+ // 0.2.2 的 apply_patch:路径只在补丁正文的文件头里,没有 file_path / path。
282
+ // 相对路径以会话当前工作目录为基准(= 宿主文档约定的“Session working directory”),
283
+ // 再归一到项目根;项目外的路径由 normalizeRelFile 丢掉。
284
+ // Delete/Move 也记为写:任务卡片关心“这次任务碰过哪些文件”,而不是它们是否还存在。
285
+ // 正文里一个路径都取不到时**不返回**:同名工具若走 path/file_path 参数,交给下面的通用分支。
286
+ if (data.name === 'apply_patch') {
287
+ const base = typeof cwd === 'string' && cwd ? cwd : root
288
+ const rels = []
289
+ for (const target of patchFilePaths(args?.input)) {
290
+ const rel = normalizeRelFile(root, path.isAbsolute(target) ? target : path.resolve(base, target))
291
+ if (rel) rels.push(rel)
292
+ }
293
+ if (rels.length > 0) {
294
+ record(rels, 'write')
295
+ return
296
+ }
297
+ }
298
+
299
+ // read/write/edit/read_image 用 file_path;宿主的 str_replace_editor 用 path。
300
+ const raw = typeof args?.file_path === 'string'
301
+ ? args.file_path
302
+ : typeof args?.path === 'string' ? args.path : null
303
+ if (!raw) return
304
+ const rel = normalizeRelFile(root, raw)
305
+ if (!rel) return
306
+ let kind = null
307
+ if (data.name === 'str_replace_editor') {
308
+ const cmd = typeof args?.command === 'string' ? args.command.toLowerCase() : ''
309
+ if (cmd === 'view') kind = 'read'
310
+ else if (['create', 'str_replace', 'insert'].includes(cmd)) kind = 'write'
311
+ } else if (data.name === 'apply_patch') {
312
+ kind = 'write' // 补丁没解析出文件头时的 path/file_path 变体:仍是写
313
+ } else {
314
+ kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
315
+ }
316
+ if (!kind) return
317
+ record([rel], kind)
284
318
  }
285
319
  }
286
320
 
package/src/store.js CHANGED
@@ -435,6 +435,11 @@ export class ProjectMemoryStore {
435
435
  this._dirtyBinding = false
436
436
  this._dirtyWatch = false
437
437
  this._formatWritten = false
438
+ /**
439
+ * 旧库迁移被保护性跳过(entries.json 有数据但 index.json 缺失/损坏)。
440
+ * 置位后 save() 不允许写 format.json:那个标记会让下一次 load 把旧文件当迁移残留删掉。
441
+ */
442
+ this._legacyBlocked = false
438
443
  this._idfCache = null
439
444
  /** entries 的变更计数:IDF 缓存与符号索引(读取期链接)都据此失效。 */
440
445
  this._entriesVersion = 0
@@ -490,9 +495,32 @@ export class ProjectMemoryStore {
490
495
  return this
491
496
  }
492
497
 
498
+ /** 迁移保护:置位后 save() 不写 format.json,下一次 load 会重试迁移而不是删旧文件。 */
499
+ _markLegacyBlocked(message) {
500
+ this._legacyBlocked = true
501
+ if (migrationWarned.has(this.dir)) return
502
+ migrationWarned.add(this.dir)
503
+ console.error(`[dsh-project-memory] ${message}`)
504
+ }
505
+
493
506
  _migrateLegacyIfNeeded() {
494
507
  const formatPath = path.join(this.dir, FORMAT_FILE)
495
- if (loadJson(formatPath, null)?.version === 2) {
508
+ const formatDoc = loadJson(formatPath, null)
509
+ if (formatDoc?.version === 2) {
510
+ // 危险组合:format.json 已经写了,但 entries.json 还有数据/读不出来。正常迁移的标记带
511
+ // `migratedFrom`;没有它就是"某次 save() 在迁移被跳过后补写了 format"(旧版只把
512
+ // !formatWritten 当脏)。这时绝不能把 entries.json 当迁移残留删掉——那正是整库静默消失的路径。
513
+ const legacyEntriesPathV2 = path.join(this.dir, ENTRIES_FILE)
514
+ let legacyV2 = null
515
+ if (existsSafe(legacyEntriesPathV2)) legacyV2 = loadJson(legacyEntriesPathV2, null)
516
+ const legacyHasPayload = isRecord(legacyV2) && Object.keys(legacyV2).length > 0
517
+ const legacyUnreadable = existsSafe(legacyEntriesPathV2) && !isRecord(legacyV2)
518
+ if (formatDoc.migratedFrom !== 'legacy' && (legacyHasPayload || legacyUnreadable)) {
519
+ this._markLegacyBlocked(
520
+ `legacy ${ENTRIES_FILE} still exists next to a non-migration ${FORMAT_FILE}; keeping it (delete the stale ${FORMAT_FILE} after migrating manually)`,
521
+ )
522
+ return
523
+ }
496
524
  // 迁移在“写完标记、删旧文件前”崩溃会留下死文件;这里顺手清掉
497
525
  for (const stale of [path.join(this.dir, ENTRIES_FILE), path.join(this.dir, INDEX_FILE)]) {
498
526
  if (existsSafe(stale)) {
@@ -514,7 +542,9 @@ export class ProjectMemoryStore {
514
542
  const entries = loadJson(legacyEntriesPath, null)
515
543
  if (!isRecord(index) || !isRecord(entries)) {
516
544
  const hasEntries = isRecord(entries) && Object.keys(entries).length > 0
517
- if (!hasEntries) {
545
+ // entries.json 读不出来但文件仍在(loadJson 的备份也失败了):同样按"有数据"保护。
546
+ const unreadableEntries = !isRecord(entries) && existsSafe(legacyEntriesPath)
547
+ if (!hasEntries && !unreadableEntries) {
518
548
  // entries 损坏(已备份)或本就是空的:没有可保护的数据,按空旧库收尾。
519
549
  writeJsonAtomic(formatPath, { version: 2, layout: 'sharded' })
520
550
  for (const stale of [legacyEntriesPath, legacyIndexPath]) {
@@ -528,12 +558,23 @@ export class ProjectMemoryStore {
528
558
  }
529
559
  // index.json 是 entries.json → rel 的唯一映射;它缺失时继续迁移会写出 0 个 shard 再删掉
530
560
  // 完好的 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
- }
561
+ this._markLegacyBlocked(
562
+ unreadableEntries
563
+ ? `legacy ${ENTRIES_FILE} is unreadable and could not be backed up; migration skipped to protect it`
564
+ : `legacy store at ${this.dir} has ${ENTRIES_FILE} but no readable ${INDEX_FILE}; migration skipped to protect it`,
565
+ )
535
566
  return
536
567
  }
568
+ if (!isRecord(index.files)) {
569
+ // 与"index.json 缺失"同等对待:entries 非空而 files 不是对象时继续迁移会写出 0 个 shard
570
+ // 再把两个旧文件删掉(只留两行日志)。
571
+ if (Object.keys(entries).length > 0) {
572
+ this._markLegacyBlocked(
573
+ `legacy store at ${this.dir} has ${ENTRIES_FILE} but ${INDEX_FILE} has no readable files map; migration skipped to protect it`,
574
+ )
575
+ return
576
+ }
577
+ }
537
578
  const files = isRecord(index.files) ? index.files : {}
538
579
  const orphans = Object.keys(entries).filter((rel) => !(rel in files))
539
580
  if (orphans.length) {
@@ -551,7 +592,7 @@ export class ProjectMemoryStore {
551
592
  }
552
593
  writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: files[rel], entries: list.map(withoutPersistedDerived) })
553
594
  }
554
- writeJsonAtomic(formatPath, { version: 2, layout: 'sharded' })
595
+ writeJsonAtomic(formatPath, { version: 2, layout: 'sharded', migratedFrom: 'legacy' })
555
596
  for (const stale of [legacyEntriesPath, path.join(this.dir, INDEX_FILE)]) {
556
597
  try {
557
598
  unlinkSync(stale)
@@ -640,7 +681,16 @@ export class ProjectMemoryStore {
640
681
  else if (task.insights !== undefined) task.insights = []
641
682
  if (Array.isArray(task.files)) task.files = task.files.filter((f) => typeof f === 'string' && f)
642
683
  else task.files = []
684
+ // `steps` 是第三条:对象/字符串形状会让 `(task.steps || []).map` 与 `for...of` 抛错,
685
+ // 而 pre-step 的 catch 会把整步注入降级(连 project/global insight 一起不注入)。
686
+ if (!Array.isArray(task.steps)) task.steps = []
643
687
  if (!isRecord(task.fileMeta)) task.fileMeta = {}
688
+ else {
689
+ // 单个 rel 的值不是对象时 `touchTaskFile()` 会往字符串上写属性而抛错:按空对象归一。
690
+ for (const rel of Object.keys(task.fileMeta)) {
691
+ if (!isRecord(task.fileMeta[rel])) task.fileMeta[rel] = {}
692
+ }
693
+ }
644
694
  }
645
695
  const bindingDoc = this._loadJson(path.join(this.dir, BINDING_FILE), {})
646
696
  this.binding = isRecord(bindingDoc) ? bindingDoc : {}
@@ -729,11 +779,17 @@ export class ProjectMemoryStore {
729
779
  this.insights = { ...diskDoc, items: diskDoc.items.filter(isRecord) }
730
780
  } else {
731
781
  const now = new Date().toISOString()
732
- const known = new Set(this.insights.items.map((it) => it.id))
782
+ // 锁内重读到的 diskDoc 可能已有另一个进程刚写入的条目(只是还没写 migratedAt)。
783
+ // 不能拿等锁前的 this.insights 整份覆盖:那会把对方的条目静默丢掉。
784
+ const baseDoc = isRecord(diskDoc) && Array.isArray(diskDoc.items)
785
+ ? { ...diskDoc, items: diskDoc.items.filter(isRecord) }
786
+ : this.insights
787
+ const mergedItems = [...baseDoc.items]
788
+ const known = new Set(mergedItems.map((it) => it.id))
733
789
  for (const item of legacy) {
734
790
  if (!item || !item.problem || known.has(item.id)) continue
735
791
  known.add(item.id)
736
- this.insights.items.push({
792
+ mergedItems.push({
737
793
  id: item.id,
738
794
  kind: 'experience',
739
795
  scope: 'project',
@@ -751,7 +807,7 @@ export class ProjectMemoryStore {
751
807
  })
752
808
  imported++
753
809
  }
754
- this.insights.migratedAt = now
810
+ this.insights = { ...baseDoc, items: mergedItems, migratedAt: now }
755
811
  mkdirSync(this.dir, { recursive: true })
756
812
  writeJsonAtomic(insightsPath, this.insights, { ensureDir: false })
757
813
  }
@@ -881,6 +937,10 @@ export class ProjectMemoryStore {
881
937
  // 没有脏数据就不落盘:watch 每轮对每个根都无条件 commit → save,否则末尾的 IDF 缓存失效
882
938
  // 会打在跨实例共享的 store 上,等于每轮清空一次复用。待压实队列不算脏,但也要有界推进。
883
939
  const compacting = this._compactQueue.size > 0
940
+ // `!formatWritten` 只在**真有内容**时才算脏:否则一次空提交(或 global-only 写入后
941
+ // 对 project store 的 commit)就会给没有记忆的项目造出 `.dsh-project-memory/format.json`,
942
+ // 还会被 nestedStoreRoots 当成“自带 store 的嵌套项目”跳过整棵子树。
943
+ const hasContent = this.hasContent
884
944
  const dirty =
885
945
  compacting ||
886
946
  this._dirtyShards.size > 0 ||
@@ -889,7 +949,7 @@ export class ProjectMemoryStore {
889
949
  this._dirtyTasks ||
890
950
  this._dirtyBinding ||
891
951
  this._dirtyWatch ||
892
- !this._formatWritten
952
+ (!this._formatWritten && !this._legacyBlocked && hasContent)
893
953
  if (dirty) {
894
954
  // 目录可能在 load 之后被外部删掉:`_storeDirReady` 只当"上次写过"的快路径,命中时补一次
895
955
  // stat;失配就重建目录,并让分片/格式/忽略三处的已就绪状态一起失效。
@@ -945,7 +1005,7 @@ export class ProjectMemoryStore {
945
1005
  try {
946
1006
  // 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
947
1007
  this._mergeAuxFromDisk()
948
- if (!this._formatWritten) {
1008
+ if (!this._formatWritten && !this._legacyBlocked) {
949
1009
  writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' }, { ensureDir: false })
950
1010
  this._formatWritten = true
951
1011
  }
@@ -29,18 +29,18 @@ 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
46
  output: {
@@ -15,11 +15,11 @@ export function indexDocTool(ctx, config) {
15
15
  file_path: {
16
16
  type: 'string',
17
17
  required: true,
18
- description: '文档绝对路径',
18
+ description: 'absolute path of the document',
19
19
  },
20
20
  root: {
21
21
  type: 'string',
22
- description: '项目根(默认会话项目根)',
22
+ description: 'project root (default: session project root)',
23
23
  },
24
24
  },
25
25
  output: {
@@ -150,11 +150,11 @@ export function indexRepoTool(ctx, config) {
150
150
  root: {
151
151
  type: 'string',
152
152
  required: true,
153
- description: '项目根(相对路径按会话当前工作目录解析)',
153
+ description: 'project root (relative: session cwd)',
154
154
  },
155
155
  reindex: {
156
156
  type: 'boolean',
157
- description: '忽略哈希,强制重抽',
157
+ description: 'ignore hashes, force re-extraction',
158
158
  },
159
159
  },
160
160
  output: {
@@ -10,24 +10,25 @@ import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
10
10
  import { createWriteCosine } from '../auto-inject.js'
11
11
 
12
12
  export function lessonTool(config) {
13
- const kindDesc = 'lesson(坑→改法) | decision(选择+理由) | procedure(步骤) | experience(问题→解法);默认 lesson。'
13
+ const kindDesc = 'lesson (pitfall → fix) | decision (choice + reason) | procedure (steps) | experience (problem → solution); default lesson.'
14
14
  const scopeDesc =
15
- 'task(任务私有) | project(项目资产) | global(跨项目);默认 project;给 id 时就地更新。'
15
+ 'task | project | global; default: task when a task is bound, else project; passing id updates in place.'
16
16
  return defineTool({
17
17
  name: 'save_lesson',
18
18
  description:
19
- '写入一条教训 / 决策 / 流程(单条 insight)。只写下次仍成立的判据与命令;某次运行的值(版本号、计数、分支名)不进正文。写入前与既有记忆比对:高相似度自动覆盖(旧值留在 prev),'
20
- + '较近的提示近邻 id。发现记错/过时:带 id 再写一次即就地覆盖;确定要删用 forget。',
19
+ '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. '
20
+ + 'It compares against existing memory first: high similarity overwrites (old value kept in prev), a near match returns the nearest id. '
21
+ + '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
22
  parameters: {
22
- id: { type: 'string', description: '既有条目 id(就地更新,忽略 scope)' },
23
- title: { type: 'string', description: '一行标题' },
23
+ id: { type: 'string', description: 'existing entry id (in-place update)' },
24
+ title: { type: 'string', description: 'one-line title' },
24
25
  kind: { type: 'string', enum: INSIGHT_KINDS, description: kindDesc },
25
26
  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: '有序步骤' },
27
+ pattern: { type: 'string', description: 'error pattern' },
28
+ fix: { type: 'string', description: 'corrected practice' },
29
+ choice: { type: 'string', description: 'what was chosen' },
30
+ reason: { type: 'string', description: 'why' },
31
+ steps: { type: 'array', items: { type: 'string' }, description: 'ordered steps' },
31
32
  trigger: {
32
33
  type: 'object',
33
34
  additionalProperties: false,
@@ -37,23 +38,23 @@ export function lessonTool(config) {
37
38
  additionalProperties: false,
38
39
  properties: {
39
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' },
40
- writes: { type: 'array', items: { type: 'string' }, description: '项目相对路径,禁 glob' },
41
- intents: { type: 'array', items: { type: 'string' }, description: '意图词(CJK≥2,拉丁≥5)' },
41
+ writes: { type: 'array', items: { type: 'string' }, description: 'project-relative paths, no glob' },
42
+ intents: { type: 'array', items: { type: 'string' }, description: 'intent words (CJK ≥2, latin ≥5)' },
42
43
  },
43
- description: '唯一触发面:三者取或;不写则只能靠检索命中,不会主动注入。',
44
+ description: 'the only trigger surface: any of the three; without it the entry is retrieval-only.',
44
45
  },
45
46
  guard: {
46
47
  type: 'object',
47
48
  additionalProperties: false,
48
49
  properties: {
49
- paths: { type: 'array', items: { type: 'string' }, description: '写目标须命中其一' },
50
+ paths: { type: 'array', items: { type: 'string' }, description: 'write target must match one of them' },
50
51
  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 交集' },
52
+ hosts: { type: 'array', items: { type: 'string' }, description: 'e.g. wsl' },
53
+ tags: { type: 'array', items: { type: 'string' }, description: 'profile tag intersection' },
53
54
  },
54
- description: '收窄条件:全部满足才放行。',
55
+ description: 'narrowing conditions: all must hold.',
55
56
  },
56
- prevents: { type: 'string', description: '不知道它会做错什么' },
57
+ prevents: { type: 'string', description: 'what breaks without this entry' },
57
58
  // 旧字段:历史条目与旧调用仍可能带它们,保留形状但不占描述预算。
58
59
  keywords: { type: 'array', items: { type: 'string' } },
59
60
  symbols: { type: 'array', items: { type: 'string' } },
@@ -61,13 +62,13 @@ export function lessonTool(config) {
61
62
  paths: { type: 'array', items: { type: 'string' } },
62
63
  scope: { type: 'array', items: { type: 'string' } },
63
64
  },
64
- description: '命中即在动手前注入;when 是唯一触发面,guard 只能收窄。',
65
+ description: 'injects before acting when matched; when is the only trigger surface.',
65
66
  },
66
- task_id: { type: 'string', description: '目标任务 id' },
67
- files: { type: 'array', items: { type: 'string' }, description: '关联文件(项目相对)' },
68
- symbols: { type: 'array', items: { type: 'string' }, description: '关联符号' },
67
+ task_id: { type: 'string', description: 'target task id' },
68
+ files: { type: 'array', items: { type: 'string' }, description: 'related files (project-relative)' },
69
+ symbols: { type: 'array', items: { type: 'string' }, description: 'related symbols' },
69
70
  confidence: { type: 'number', description: '0..1' },
70
- root: { type: 'string', description: '项目根' },
71
+ root: { type: 'string', description: 'project root' },
71
72
  },
72
73
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
73
74
  async execute(args, exec) {
@@ -100,7 +101,9 @@ export function lessonTool(config) {
100
101
  if (!args.id && !raw.title && !raw.pattern && !raw.choice) {
101
102
  return truncate(JSON.stringify({ success: false, error: '需要 title / pattern / choice 之一(或给 id 做就地更新)' }), config.maxOutputChars || 8000)
102
103
  }
103
- if (!INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
104
+ // 只有新建才补默认 kind;带 id 的就地更新必须“只覆盖传了的字段”,
105
+ // 否则一次改 fix/reason 会把 decision/procedure 静默降级成 lesson。
106
+ if (!args.id && !INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
104
107
 
105
108
  let scope = args.scope
106
109
  if (!scope) scope = taskId ? 'task' : 'project'
@@ -61,25 +61,26 @@ export function queryMemoryTool(ctx, config) {
61
61
  name: 'query_memory',
62
62
  description:
63
63
  '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.',
64
+ + 'Use before grepping for orientation, a spec constraint, or a past decision. '
65
+ + 'After a query, update stale or wrong entries right away (save_lesson with that id).',
65
66
  parameters: {
66
67
  query: {
67
68
  type: 'string',
68
69
  required: true,
69
- description: 'What to look for',
70
+ description: 'what to look for',
70
71
  },
71
72
  root: {
72
73
  type: 'string',
73
- description: '项目根(默认当前工作目录)',
74
+ description: 'project root (default: cwd)',
74
75
  },
75
76
  type: {
76
77
  type: 'string',
77
78
  enum: ['all', 'doc', 'symbol', 'experience', 'insight', 'task'],
78
- description: 'all|doc|symbol|experience|insight|task;默认 all',
79
+ description: 'all|doc|symbol|experience|insight|task; default all',
79
80
  },
80
81
  limit: {
81
82
  type: 'number',
82
- description: '最多返回条数,默认 8',
83
+ description: 'max results, default 8',
83
84
  },
84
85
  },
85
86
  output: {
@@ -11,25 +11,25 @@ export function rememberTool(config) {
11
11
  name: 'remember',
12
12
  description:
13
13
  '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.',
14
+ + 'Prefer save_lesson for anything else.',
15
15
  parameters: {
16
16
  problem: {
17
17
  type: 'string',
18
18
  required: true,
19
- description: '问题/现象',
19
+ description: 'problem / symptom',
20
20
  },
21
21
  solution: {
22
22
  type: 'string',
23
23
  required: true,
24
- description: '具体解法',
24
+ description: 'concrete fix',
25
25
  },
26
26
  root: {
27
27
  type: 'string',
28
- description: '项目根(默认当前工作目录)',
28
+ description: 'project root (default: cwd)',
29
29
  },
30
30
  source_file: {
31
31
  type: 'string',
32
- description: '关联文件(项目相对)',
32
+ description: 'related file (project-relative)',
33
33
  },
34
34
  },
35
35
  output: {
@@ -17,7 +17,7 @@ export function statsTool(config) {
17
17
  parameters: {
18
18
  root: {
19
19
  type: 'string',
20
- description: '项目根(默认当前工作目录)',
20
+ description: 'project root (default: cwd)',
21
21
  },
22
22
  },
23
23
  output: {