@yolk_vat-y/dsh-project-memory 0.6.10 → 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/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(跨项目);默认:绑定任务时 task,否则 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) {
@@ -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: {
@@ -19,9 +19,9 @@ export function listTasksTool(config) {
19
19
  return defineTool({
20
20
  name: 'list_tasks',
21
21
  description:
22
- '列出本项目的任务记录(含归档)。新会话或续接前先看它,再用 select_task 选一个。',
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: '项目根(默认当前工作目录)' },
24
+ root: { type: 'string', description: 'project root (default: cwd)' },
25
25
  },
26
26
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
27
27
  async execute(args, exec) {
@@ -44,12 +44,12 @@ export function selectTaskTool(config, host) {
44
44
  return defineTool({
45
45
  name: 'select_task',
46
46
  description:
47
- '把会话绑定到一个任务(此后 todo 与读过的文件同步进它)。按 taskId 精确绑定,或按 title 完全匹配'
48
- + '(无则新建);返回任务卡用于重建清单。',
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.',
49
49
  parameters: {
50
- taskId: { type: 'string', description: '精确 task id' },
51
- title: { type: 'string', description: '精确标题;无则新建' },
52
- root: { type: 'string', description: '项目根(默认当前工作目录)' },
50
+ taskId: { type: 'string', description: 'exact task id' },
51
+ title: { type: 'string', description: 'exact title; creates if absent' },
52
+ root: { type: 'string', description: 'project root (default: cwd)' },
53
53
  },
54
54
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
55
55
  async execute(args, exec) {
@@ -170,7 +170,7 @@ export function archiveTaskTool(config, host) {
170
170
  description: 'Archive a task (restore by selecting it again).',
171
171
  parameters: {
172
172
  taskId: { type: 'string', required: true, description: 'task id' },
173
- root: { type: 'string', description: '项目根(默认当前工作目录)' },
173
+ root: { type: 'string', description: 'project root (default: cwd)' },
174
174
  },
175
175
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
176
176
  async execute(args, exec) {
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  import { assertIndexRoot, assertSafeRoot, memoryRootFor, resolveIndexRoot, rootRejection, sessionMemoryRootOrNull, storeKey } from '../util/fs.js'
5
5
  import { ProjectMemoryStore } from '../store.js'
6
6
  import { cfgValue } from '../util/config.js'
7
+ import { normalizeWatchIntervalMs } from '../watch.js'
7
8
 
8
9
  export function watchRepoTool(watchManager, config) {
9
10
  return defineTool({
@@ -14,11 +15,11 @@ export function watchRepoTool(watchManager, config) {
14
15
  root: {
15
16
  type: 'string',
16
17
  required: true,
17
- description: '项目根(相对路径按会话当前工作目录解析)',
18
+ description: 'project root (relative: session cwd)',
18
19
  },
19
20
  watch: {
20
21
  type: 'boolean',
21
- description: 'false = 停止监听',
22
+ description: 'false = stop watching',
22
23
  },
23
24
  },
24
25
  output: {
@@ -72,9 +73,9 @@ export function watchRepoTool(watchManager, config) {
72
73
  new ProjectMemoryStore(memoryDir).load().commit((s) => s.addWatch(root))
73
74
  await mirrorSessionWatchlist(true)
74
75
  watchManager.addRoot(root)
75
- const interval = Number(cfgValue(config, 'watchInterval'))
76
- watchManager.start(interval * 1000)
77
- return `Watching ${root} (interval ${interval}s). Docs/code changes will be re-indexed silently.`
76
+ const intervalMs = normalizeWatchIntervalMs(Number(cfgValue(config, 'watchInterval')) * 1000)
77
+ watchManager.start(intervalMs)
78
+ return `Watching ${root} (interval ${intervalMs / 1000}s). Docs/code changes will be re-indexed silently.`
78
79
  },
79
80
  })
80
81
  }
package/src/util/fs.js CHANGED
@@ -254,11 +254,15 @@ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000, hardSta
254
254
  }
255
255
  if (lockIsStale(state, { staleMs, hardLimit, maxHoldMs })) {
256
256
  // 只删"刚刚读到的那个内容":两次读之间锁可能已被别人抢到并重写。
257
+ // 回收失败(只读目录、Windows 杀毒/索引器长期占用)不能无条件 continue:那会变成
258
+ // 无 deadline、无等待的同步自旋,timeoutMs 被完全忽略,save()/commit()/退出 flush 卡死。
259
+ if (Date.now() >= deadline) return null
257
260
  try {
258
261
  if (readFileSync(file, 'utf8') === state.text) unlinkWithRetry(file)
259
262
  } catch {
260
263
  // 已被别处回收,或杀毒瞬时占用;下一轮继续判定
261
264
  }
265
+ Atomics.wait(sleeper, 0, 0, 10)
262
266
  continue
263
267
  }
264
268
  if (Date.now() >= deadline) return null
@@ -610,12 +614,16 @@ export function listProjectFiles(root, opts = {}) {
610
614
  // 配置/状态/密钥(`.env`、`.ssh`),非 git 目录没有"被跟踪=作者同意"这层信号。
611
615
  // 真要索引某个隐藏文件,走显式 `index_doc`(它不受扫描清单限制)。
612
616
  if (segs.some((s) => s.startsWith('.'))) continue
613
- if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
617
+ // 与 walkDir 同口径:`DEFAULT_IGNORE` 只作用于**目录段**,根目录下一个叫 `build`
618
+ // 的普通文件仍然要收(此前对文件名也判,`git init` 前后语料会变)。
619
+ if (segs.slice(0, -1).some((s) => DEFAULT_IGNORE.has(s))) continue
614
620
  const abs = path.join(root, rel)
615
621
  // 与 walkDir 同一判据:exclude 是子树级前缀。必须在 maxDepth 之前——被排除文件不该把
616
622
  // 扫描标成 truncated(否则本轮不清理"未见到的旧条目")。
617
623
  if (policy && excludedEntryForAbs(abs, policy)) continue
618
- if (segs.length > maxDepth) {
624
+ // 文件的“目录深度”是 segs.length - 1;walkDir 的 maxDepth 也按目录层数计,
625
+ // 此前用 segs.length 会让 git 分支少收浅一层,并在同一棵树上报不同的 capped。
626
+ if (segs.length - 1 > maxDepth) {
619
627
  capped = true
620
628
  continue
621
629
  }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Codex `apply_patch` 正文里的目标路径。
3
+ *
4
+ * 这个工具没有 `file_path` / `path` 参数,路径只出现在补丁正文的文件头里:
5
+ * *** Add File: src/a.ts / *** Update File: src/b.ts / *** Delete File: src/c.ts
6
+ * *** Move to: src/d.ts(跟在 Update File 之后,是移动后的新路径)
7
+ * 正文里的增删行都带 `+` / `-` / 空格前缀,所以行首的 `*** …` 只可能是文件头。
8
+ *
9
+ * 只做机械提取:不校验补丁语法、不判断文件是否存在——调用方拿到的路径仍要走
10
+ * 自己的根归一化(项目外会被丢弃)。
11
+ *
12
+ * @param {string} input - `apply_patch` 的 `input` 参数(整段补丁文本)
13
+ * @returns {string[]} 按出现顺序去重后的路径(原样,未解析为绝对路径)
14
+ */
15
+ export function patchFilePaths(input) {
16
+ if (typeof input !== 'string' || input === '') return []
17
+ const paths = []
18
+ const seen = new Set()
19
+ for (const line of input.split(/\r?\n/)) {
20
+ const matched = /^\*\*\* (?:Add|Update|Delete) File:\s*(.+)$/.exec(line) || /^\*\*\* Move to:\s*(.+)$/.exec(line)
21
+ if (!matched) continue
22
+ const raw = matched[1].trim().replace(/^(['"`])(.*)\1$/, '$2').trim()
23
+ if (!raw || seen.has(raw)) continue
24
+ seen.add(raw)
25
+ paths.push(raw)
26
+ }
27
+ return paths
28
+ }
@@ -215,12 +215,22 @@ export function rankEntriesMergedScored(entries, queries, limit = 8) {
215
215
  // (没有 problem/solution 参数),独立打分器会把那种条目打成 0 分且无处可查。现由
216
216
  // `recall.js` 用与洞察层相同的 `insightToEntry` 适配器打分,本函数随能力一起删除。
217
217
 
218
+ const LATIN_TERM_RE = /^[a-z0-9_]+$/
219
+ const WORD_CHAR_RE = /[a-z0-9_]/
220
+
218
221
  function countOccurrences(text, token) {
219
222
  if (!token) return 0
220
223
  let count = 0
221
224
  let pos = 0
225
+ // 拉丁词项必须按词边界计数:`searchText` 不是 token 化的,用裸 indexOf 会让 `cat` 命中
226
+ // "concatenate"、`log` 命中 "dialog",与按 token 统计的 IDF 不同源(假阳性 + 分数不可比)。
227
+ // CJK bigram / 西里尔词干没有 ASCII 词边界,保持子串计数。
228
+ const bounded = LATIN_TERM_RE.test(token)
222
229
  while ((pos = text.indexOf(token, pos)) !== -1) {
223
- count++
230
+ if (!bounded
231
+ || (!WORD_CHAR_RE.test(text[pos - 1] || '') && !WORD_CHAR_RE.test(text[pos + token.length] || ''))) {
232
+ count++
233
+ }
224
234
  pos += token.length
225
235
  }
226
236
  return count
@@ -51,7 +51,9 @@ export function stepProgress(task) {
51
51
 
52
52
  /** 相对时间(中文):面板、list_tasks、/tasks 三处文案共用同一套阈值。 */
53
53
  export function timeAgo(iso) {
54
- const diff = Date.now() - new Date(iso).getTime()
54
+ const t = Date.parse(iso ?? '')
55
+ if (!Number.isFinite(t)) return '未知'
56
+ const diff = Date.now() - t
55
57
  const m = Math.floor(diff / 60000)
56
58
  if (m < 1) return '刚刚'
57
59
  if (m < 60) return `${m}分钟前`
package/src/util/text.js CHANGED
@@ -14,6 +14,8 @@ export function textOf(message) {
14
14
 
15
15
  export function truncate(text, maxChars) {
16
16
  if (typeof text !== 'string') return String(text)
17
+ // 非有限值(缺配置 / 测试桩)原样返回,而不是输出 “...[truncated at undefined chars]”。
18
+ if (!Number.isFinite(maxChars)) return text
17
19
  if (text.length <= maxChars) return text
18
20
  return text.slice(0, maxChars) + `\n\n...[truncated at ${maxChars} chars]`
19
21
  }
package/src/watch.js CHANGED
@@ -22,10 +22,19 @@ import { clearIndexFailure, recordIndexFailure } from './index-failures.js'
22
22
  export function applyWatchSettings(watchManager, config) {
23
23
  watchManager.stop()
24
24
  if (cfgValue(config, 'watch') === false) return false
25
- watchManager.start(Number(cfgValue(config, 'watchInterval')) * 1000)
25
+ watchManager.start(normalizeWatchIntervalMs(Number(cfgValue(config, 'watchInterval')) * 1000))
26
26
  return true
27
27
  }
28
28
 
29
+ /**
30
+ * 把配置里的毫秒值归一成**实际会用的**轮询间隔:非法值回落 30s,合法值下限 1s。
31
+ * 工具回报与 `start()` 必须读同一份,否则 `watchInterval: 0` 会回报 "0s"、实际 1s。
32
+ */
33
+ export function normalizeWatchIntervalMs(intervalMs) {
34
+ const raw = Number(intervalMs)
35
+ return Number.isFinite(raw) ? Math.max(raw, 1000) : 30000
36
+ }
37
+
29
38
  /**
30
39
  * 有界并发 map。同步 `statSync` 循环在 Windows(尤其 WSL 挂 `/mnt/c`)会把事件循环卡住:
31
40
  * 400 文件实测 ~0.9s、12k 文件按同一比例是几十秒,期间面板与工具调用全部停摆。
@@ -169,8 +178,7 @@ export class WatchManager {
169
178
 
170
179
  start(intervalMs = 30000) {
171
180
  // 非法值(NaN/undefined)会让定时器退化成 1ms 轮询打满事件循环,故回退默认 30s。
172
- const raw = Number(intervalMs)
173
- this._baseInterval = Number.isFinite(raw) ? Math.max(raw, 1000) : 30000
181
+ this._baseInterval = normalizeWatchIntervalMs(intervalMs)
174
182
  // 空闲退避:连续没有变化的轮次把间隔翻倍,最长 2 分钟一轮;任何变化立刻回到 base。
175
183
  // 轮询是 O(树) 的 walkDir + 逐文件 stat(本仓库一轮实测 58–87ms),常驻 15s 一轮都在磨 I/O。
176
184
  this._maxInterval = Math.max(this._baseInterval, Math.min(this._baseInterval * 8, 120000))