@yolk_vat-y/dsh-project-memory 0.5.13 → 0.5.15

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.
@@ -4,7 +4,7 @@ import { statSync } from 'node:fs'
4
4
  import { assertIndexRoot, assertSafeRoot, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey, walkDir } from '../util/fs.js'
5
5
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from '../index-pipeline.js'
6
6
  import { ProjectMemoryStore } from '../store.js'
7
- import { onFileIndexed, isTypeScriptFile } from '../enhancer.js'
7
+ import { onFileIndexed, isTypeScriptFile, enhanceQueueStats } from '../enhancer.js'
8
8
 
9
9
  /**
10
10
  * 每批提交的文件数。旧实现把整棵树的 updates 攒到最后一次性 commit:一次全量扫描的
@@ -38,7 +38,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
38
38
  batch = []
39
39
  }
40
40
 
41
- const { files, truncated, skipped: nestedRoots } = walkDir(root, {
41
+ const { files, truncated, capped, skipped: nestedRoots, unreadable } = walkDir(root, {
42
42
  ...scanLimits(config),
43
43
  nestedStoreName: memoryDirName(config),
44
44
  })
@@ -78,7 +78,8 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
78
78
  }
79
79
 
80
80
  // 收尾:写完最后一批 + 清理本轮未见到的旧条目。
81
- // 截断时**不做 unseen 清理**:没扫到的文件不等于被删了。
81
+ // 截断时**不做 unseen 清理**:没扫到的文件不等于被删了(`truncated` 同时覆盖"读不到的
82
+ // 目录"——那种情况下清理会静默删掉派生索引,见 src/util/fs.js walkDir)。
82
83
  const { removed } = commitFileUpdates(store, {
83
84
  updates: batch,
84
85
  unseen: truncated ? null : seen,
@@ -88,7 +89,13 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
88
89
  `Indexed project: ${root}\n` +
89
90
  `docs indexed: ${indexed}, code symbols updated: ${updated}, unchanged skipped: ${skipped}, removed: ${removed}\n` +
90
91
  `memory store: ${stats.files} files, ${stats.entries} entries, ${stats.experience} experience notes`
91
- if (truncated) {
92
+ if (unreadable.length) {
93
+ const rels = unreadable.map((p) => storeKey(relativePath(root, p)))
94
+ report +=
95
+ `\ncould not read ${unreadable.length} director${unreadable.length === 1 ? 'y' : 'ies'} (permissions?): ${rels.join(', ')}` +
96
+ '\n(scan incomplete → nothing is treated as deleted: previously indexed files under them are kept as-is; fix permissions and re-run)'
97
+ }
98
+ if (capped) {
92
99
  const { maxFiles, maxDepth } = scanLimits(config)
93
100
  report +=
94
101
  `\nscan truncated at the safety limit (maxFiles=${maxFiles}, maxDepth=${maxDepth}): only part of the tree was indexed.` +
@@ -106,9 +113,16 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
106
113
  }
107
114
 
108
115
  // Trigger TS enhancement for code files (TS/JS only), now that the base entries are on disk.
116
+ const dropsBefore = enhanceQueueStats().dropped
109
117
  for (const [rel, filePath] of tsFiles) {
110
118
  onFileIndexed(store, rel, filePath, config, root)
111
119
  }
120
+ const dropped = enhanceQueueStats().dropped - dropsBefore
121
+ if (dropped) {
122
+ report +=
123
+ `\n${dropped} file(s) skipped TS enhancement (queue cap reached, lowest priority dropped first)` +
124
+ ': their L1 regex symbols are unaffected; they are re-queued on the next index or change.'
125
+ }
112
126
 
113
127
  return report
114
128
  }
@@ -125,7 +139,7 @@ export function indexRepoTool(ctx, config) {
125
139
  root: {
126
140
  type: 'string',
127
141
  required: true,
128
- description: 'Absolute path to the project root to index.',
142
+ description: '要索引的项目根目录(绝对路径)。',
129
143
  },
130
144
  reindex: {
131
145
  type: 'boolean',
@@ -8,17 +8,19 @@ import { INSIGHT_KINDS, INSIGHT_SCOPES } from '../insight-store.js'
8
8
  import { sessionIdOf } from '../util/task-view.js'
9
9
 
10
10
  export function lessonTool(config) {
11
- const kindDesc = `insight 语义:lesson(曾踩坑/纠偏, pattern→fix) | decision(权衡选型, choice→reason) | procedure(多步指南, steps) | experience(problem→solution,v0.4 兼容)。默认 lesson。所有 kind 都可带 trigger:命中即在动手前确定性注入。`
11
+ // 描述预算:这两段以前同时出现在「工具描述」和「参数描述」里,等于付两遍钱。
12
+ // 现在只在参数上写一次 —— 语义一条没少,只是不再重复。
13
+ const kindDesc = 'lesson(踩坑/纠偏, 用 pattern+fix) | decision(选型, choice+reason) | procedure(步骤, steps) | experience(problem→solution, v0.4 兼容);默认 lesson。'
12
14
  const scopeDesc =
13
- '作用域:task(任务私有,随任务归档,不进共享注入) | project(项目资产) | global(个人能力库,跨项目,建议配 trigger 关键词以便将来技能命中)。' +
15
+ 'task(任务私有,随任务归档) | project(项目资产) | global(个人能力库,跨项目);默认 project。' +
14
16
  '解析顺序:显式 scope > task_id > 当前绑定任务 > project。'
15
17
  return defineTool({
16
18
  name: 'save_lesson',
17
19
  description:
18
- 'Save a lesson/decision/procedure/experience into the tiered memory (single insight entity). ' +
19
- 'Call it when the task hit a real pitfall, got corrected, or made a deliberate choice worth remembering — not for routine work. ' +
20
- 'Similar entries auto-merge (bidirectional token overlap >= 0.7) or reinforce (0.65~0.7, accumulating task hits); ' +
21
- 'when the same insight is hit by 2+ tasks it auto-promotes task -> project, 3+ tasks project -> global. ' + kindDesc + ' ' + scopeDesc,
20
+ '把一条教训 / 决策 / 流程写进分层记忆(单条 insight)。新的经验优先用它,而不是 remember。' +
21
+ '在踩到坑、被纠正、做了值得记住的取舍时调用;日常琐事不要写。' +
22
+ '近重复按词重叠 ≥0.7 合并、0.65~0.7 强化;同一 insight 被 2+ 任务命中自动 task→project、3+ →global。' +
23
+ 'kind / scope / trigger 的语义见对应参数。',
22
24
  parameters: {
23
25
  title: { type: 'string', description: 'One-line title (lesson: the failure pattern; decision: the topic; procedure: the name).' },
24
26
  kind: { type: 'string', enum: INSIGHT_KINDS, description: kindDesc },
@@ -53,23 +55,25 @@ export function lessonTool(config) {
53
55
  },
54
56
  description: '收窄条件:全部满足才注入。',
55
57
  },
56
- prevents: { type: 'string', description: '准入条件:不知道这条,这一步会做错什么。写不出来 → 不该进自动注入。' },
57
- keywords: { type: 'array', items: { type: 'string' }, description: '【旧字段】降级为 intents 与被动召回排序。' },
58
+ prevents: { type: 'string', description: '准入条件:不知道这条,这一步会做错什么;写不出来就不该自动注入。' },
59
+ // 旧字段:只为兼容历史条目与旧调用而保留 schema 形状,描述不再占 prompt 预算。
60
+ // 语义(keywords→intents 与召回排序、actions→when.ops、paths→when.writes、scope→画像 tag)
61
+ // 见 README「save_lesson」与 autoContext.legacyScope。
62
+ keywords: { type: 'array', items: { type: 'string' } },
58
63
  symbols: { type: 'array', items: { type: 'string' } },
59
- actions: { type: 'array', items: { type: 'string' }, description: '【旧字段】映射为 when.ops;死值丢弃并计入自检。' },
60
- paths: { type: 'array', items: { type: 'string' }, description: '【旧字段】具体文件映射为 when.writes;扩展名/泛名 glob 丢弃。' },
61
- scope: { type: 'array', items: { type: 'string' }, description: '【旧字段】默认忽略(值不在项目画像 tag 空间里)。' },
64
+ actions: { type: 'array', items: { type: 'string' } },
65
+ paths: { type: 'array', items: { type: 'string' } },
66
+ scope: { type: 'array', items: { type: 'string' } },
62
67
  },
63
68
  description:
64
- 'authored trigger:命中即在**动手前**确定性注入。' +
65
- 'when = 唯一触发面(ops / writes / intents 取或);guard 只能收窄;prevents 是准入条件。' +
66
- '没有 when 的条目不会自动推送,只出现在记忆目录里供按需拉取。',
69
+ 'authored trigger:命中即在动手前确定性注入。when 是唯一触发面(ops / writes / intents 取或),' +
70
+ 'guard 只能收窄,没有 when 的条目不会自动推送。',
67
71
  },
68
72
  task_id: { type: 'string', description: '目标任务 id(scope 缺省时优先于绑定任务)' },
69
73
  files: { type: 'array', items: { type: 'string' }, description: '关联文件(项目相对路径)' },
70
74
  symbols: { type: 'array', items: { type: 'string' }, description: '关联符号' },
71
75
  confidence: { type: 'number', description: '置信 0..1(默认 0.8)' },
72
- root: { type: 'string', description: 'Project root. Defaults to current working directory.' },
76
+ root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
73
77
  },
74
78
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
75
79
  async execute(args, exec) {
@@ -46,7 +46,7 @@ export function queryMemoryTool(ctx, config) {
46
46
  },
47
47
  root: {
48
48
  type: 'string',
49
- description: 'Project root of the memory store to search. Defaults to the current working directory.',
49
+ description: '搜索用的项目根目录,默认当前工作目录。',
50
50
  },
51
51
  type: {
52
52
  type: 'string',
@@ -6,9 +6,11 @@ export function rememberTool(config) {
6
6
  return defineTool({
7
7
  name: 'remember',
8
8
  description:
9
- 'Save an experience note (problem -> solution) into project memory, e.g. a bug you just fixed or a decision made. ' +
10
- 'Retrieved later only when search_experience / query_memory matches the problem, never auto-injected. ' +
11
- 'If a note with a similar problem exists, it is superseded instead of duplicated.',
9
+ 'Save an experience note (problem -> solution) into project memory, e.g. a bug you just fixed. ' +
10
+ 'Retrieved later only when query_memory matches the problem, never auto-injected. ' +
11
+ 'A note for a similar problem is superseded instead of duplicated. ' +
12
+ 'This writes the standalone experience file: for lessons / decisions / procedures prefer save_lesson ' +
13
+ '(the tiered insight store) — query_memory searches both.',
12
14
  parameters: {
13
15
  problem: {
14
16
  type: 'string',
@@ -22,7 +24,7 @@ export function rememberTool(config) {
22
24
  },
23
25
  root: {
24
26
  type: 'string',
25
- description: 'Project root of the memory store. Defaults to the current working directory.',
27
+ description: '项目根目录,默认当前工作目录。',
26
28
  },
27
29
  source_file: {
28
30
  type: 'string',
@@ -14,7 +14,7 @@ export function statsTool(config) {
14
14
  parameters: {
15
15
  root: {
16
16
  type: 'string',
17
- description: 'Project root of the memory store. Defaults to the current working directory.',
17
+ description: '项目根目录,默认当前工作目录。',
18
18
  },
19
19
  },
20
20
  output: {
@@ -19,9 +19,9 @@ export function listTasksTool(config) {
19
19
  return defineTool({
20
20
  name: 'list_tasks',
21
21
  description:
22
- 'List all task records in this project (archived included, marked). Call this first in a new session or before continuing work, to see what tasks exist and pick one with select_task.',
22
+ '列出本项目的任务记录(含归档,带标记)。新会话或续接工作前先看它,再用 select_task 选一个。',
23
23
  parameters: {
24
- root: { type: 'string', description: 'Project root. Defaults to current working directory.' },
24
+ root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
25
25
  },
26
26
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
27
27
  async execute(args, exec) {
@@ -44,11 +44,12 @@ export function selectTaskTool(config, host) {
44
44
  return defineTool({
45
45
  name: 'select_task',
46
46
  description:
47
- 'Bind the current session to a task record so its todo list and read files sync into it. When starting NEW work, call select_task(title="任务名") FIRST, then maintain your plan with todo_write — you choose the task title (short, no need to restate the user message). taskId: exact id from list_tasks (auto-unarchives; pass title too to rename). title: exact match only; multiple matches return candidates; no match creates a new task. Returns a task card (title, steps, files) to rebuild the session todo from. Call list_tasks first in a new session.',
47
+ '把会话绑定到一个任务:此后 todo 清单与读过的文件都同步进该任务。开始新工作前先调它(title 自取,短的就行,不用复述用户原话),再用 todo_write 维护计划。' +
48
+ 'taskId:list_tasks 里的精确 id(会自动解归档;同时给 title 则改名)。title:完全匹配,多个同名返回候选,无匹配则新建。返回任务卡(title/steps/files)用于重建会话清单。',
48
49
  parameters: {
49
50
  taskId: { type: 'string', description: 'Exact task id, e.g. tsk_ab12cd34_...' },
50
51
  title: { type: 'string', description: 'Exact task title; creates a new task when absent' },
51
- root: { type: 'string', description: 'Project root. Defaults to current working directory.' },
52
+ root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
52
53
  },
53
54
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
54
55
  async execute(args, exec) {
@@ -149,13 +150,14 @@ export function showTaskPanelTool(config) {
149
150
  'Show the task panel in the UI. Call this when the user asks to see the task list or when you want to display the task panel to the user.',
150
151
  parameters: {},
151
152
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
152
- async execute(_args, exec) {
153
- const ctx = exec?.ctx
154
- if (!ctx) return '无法获取上下文'
155
- // 通过 BroadcastChannel 通知客户端打开面板
156
- try {
157
- ctx.events?.emit?.('dsh:task-panel:show', {})
158
- } catch { /* ignore */ }
153
+ async execute() {
154
+ // 开面板的动作在**客户端**:这个工具名被 src/client/ShowTaskPanelNode.tsx 认领,
155
+ // 结果节点一渲染就由浏览器侧调 `taskUIStore.open()`。
156
+ //
157
+ // 宿主进程没有触碰面板状态的通道 —— 面板的 closed/minimized 是浏览器侧 UI store,
158
+ // 而 `ToolRunContext` 只有 `deferContext()` / `concludeTurn()` 两个自有成员
159
+ // (packages/core/tools/src/index.ts:418),**没有 `ctx`**。旧实现读 `exec.ctx` 再
160
+ // `emit('dsh:task-panel:show')`,于是每次都返回「无法获取上下文」,面板从未打开过。
159
161
  return '已请求打开任务面板。'
160
162
  },
161
163
  })
@@ -167,7 +169,7 @@ export function archiveTaskTool(config, host) {
167
169
  description: 'Archive a task: hide from default views, exclude from capacity, stop syncing. Restore by selecting it again.',
168
170
  parameters: {
169
171
  taskId: { type: 'string', required: true, description: 'Task id to archive (from list_tasks / select_task)' },
170
- root: { type: 'string', description: 'Project root. Defaults to current working directory.' },
172
+ root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
171
173
  },
172
174
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
173
175
  async execute(args, exec) {
@@ -9,12 +9,12 @@ export function watchRepoTool(watchManager, config) {
9
9
  description:
10
10
  'Start silent auto-refresh for a project: the plugin polls the root (configurable interval), ' +
11
11
  'detects changed/new docs and code files via mtime+content-hash, and re-indexes only those silently. ' +
12
- 'No GUI, no manual re-index needed after this. Stop by reloading the plugin or calling with watch=false.',
12
+ 'No manual re-index needed after this. Call again with watch=false to stop.',
13
13
  parameters: {
14
14
  root: {
15
15
  type: 'string',
16
16
  required: true,
17
- description: 'Absolute path to the project root to watch.',
17
+ description: '要监听的项目根目录(绝对路径)。',
18
18
  },
19
19
  watch: {
20
20
  type: 'boolean',
@@ -0,0 +1,32 @@
1
+ // entry id 的「路径前缀」编码:**必须是单射**(不同路径 → 不同前缀)。
2
+ //
3
+ // 为什么值得单独一个模块:同一个规则曾在三处各写一份(doc-pipeline 的 relativeId、
4
+ // symbols.js 的 buildSymbol、enhancer.js 的 applyEnhancedSymbols),三份都是
5
+ // `replace(/[\\/:\s]/g, '_')`。于是 `a b.md` 与 `a_b.md`(以及 `a/b.md`、`a:b.md`、
6
+ // `a\b.md`)得到同一个前缀,`${prefix}#0` 就撞成同一个 id。
7
+ //
8
+ // 撞 id 不是「不好看」,它会让检索**静默少结果**:`rankEntriesStreaming` 按 id 合并
9
+ // 多查询命中(src/util/search.js),两条不同文件的条目会被合成一条、低分的那条被丢掉。
10
+ //
11
+ // 编码规则:
12
+ // - `/` → `_`(最常见的那种分隔符,保持 id 可读:`src/foo.js` → `src_foo.js`);
13
+ // - 其余风险字符(`\` `:` 各类空白 `_` `%` `#`)→ `%` + 该字符码点的十六进制。
14
+ //
15
+ // 单射理由:输出里的 `%` 只可能来自转义(源里的 `%` 一定被转成 `%25`),而每个风险字符
16
+ // 的转义串互不相同、也不同于 `_`(`/` 专属);其余字符原样输出,且原样字符里不可能出现
17
+ // 上面这些风险字符。所以解码唯一。
18
+ //
19
+ // 注意「所有分隔符都变成 `_`」是**不够**的:那正是旧实现的错(`a b.md` 与 `a/b.md` 仍然
20
+ // 同 id)。每种分隔符必须有各自的输出。
21
+ //
22
+ // 后缀(`#<chunkIndex>` / `#<line>`)只由整数构成,因此前缀单射 ⇒ 完整 id 单射。
23
+
24
+ const RISKY = /[\\/:\s_%#]/g
25
+
26
+ /** 把相对路径编码成 entry id 的路径前缀(单射、基本可读)。 */
27
+ export function entryIdPrefix(relPath) {
28
+ return String(relPath).replace(RISKY, (ch) => {
29
+ if (ch === '/') return '_'
30
+ return `%${ch.codePointAt(0).toString(16).toUpperCase().padStart(2, '0')}`
31
+ })
32
+ }
package/src/util/fs.js CHANGED
@@ -1,9 +1,41 @@
1
- import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
1
+ import {
2
+ accessSync, constants, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync,
3
+ unlinkSync, writeFileSync,
4
+ } from 'node:fs'
2
5
  import { readFile } from 'node:fs/promises'
3
6
  import { createHash } from 'node:crypto'
4
7
  import os from 'node:os'
5
8
  import path from 'node:path'
6
9
 
10
+ /**
11
+ * 原子写 JSON:先写同目录的 `<file>.<pid>.tmp`,再 rename 覆盖目标。
12
+ *
13
+ * 两点语义,别再各写一份副本:
14
+ * - 先建父目录(global insight 文件首次写入时父目录可能不存在)。
15
+ * - 失败时删掉自己的 `.tmp`,不重试 rename:同样的参数重试没有意义,而 `.tmp` 留下只有
16
+ * `cleanStaleTmp()` 会清,它扫不到 `~/.config/dsh-project-memory/`。
17
+ *
18
+ * 崩溃(kill -9 / 断电)走不到 catch,那种残留由 `cleanStaleTmp()` 兜底。
19
+ * @param {string} file - 目标文件绝对路径。
20
+ * @param {unknown} data - 要序列化的 JSON 值。
21
+ * @throws 序列化失败或写盘/rename 失败时原样抛出(调用方决定回退策略)。
22
+ */
23
+ export function writeJsonAtomic(file, data) {
24
+ mkdirSync(path.dirname(file), { recursive: true })
25
+ const tmp = `${file}.${process.pid}.tmp`
26
+ try {
27
+ writeFileSync(tmp, JSON.stringify(data))
28
+ renameSync(tmp, file)
29
+ } catch (err) {
30
+ try {
31
+ unlinkSync(tmp)
32
+ } catch {
33
+ // tmp 已不在(rename 其实成功了)或不可删;两种都无需处理
34
+ }
35
+ throw err
36
+ }
37
+ }
38
+
7
39
  export function assertReadableFile(filePath, maxFileSizeMb) {
8
40
  if (typeof filePath !== 'string' || !filePath) {
9
41
  throw new Error('file_path must be a non-empty string')
@@ -123,12 +155,19 @@ export function scanLimits(config) {
123
155
  }
124
156
 
125
157
  /**
126
- * 遍历目录,返回 `{ files, truncated }`。
158
+ * 遍历目录,返回 `{ files, truncated, capped, skipped, unreadable }`。
127
159
  *
128
160
  * 与旧版的两点区别都是 OOM 的直接修复:
129
161
  * - **有上限**:`maxFiles` / `maxDepth` 封顶,超限只做截断标记,不再一路吃内存;
130
162
  * - `truncated` 让调用方区分「这棵树扫完了」和「只扫了一部分」——后者绝不能拿
131
163
  * 本轮未见到的文件去删旧条目(见 index-repo/watch 的 unseen 用法)。
164
+ *
165
+ * `truncated` 现在有**两个来源**,必须分开报告:
166
+ * - `capped`:撞到 `maxFiles` / `maxDepth`;
167
+ * - `unreadable`:某个目录 `readdirSync` 失败(EACCES/EPERM…)。
168
+ * 旧实现把读失败当"这个目录不存在"直接 `continue` —— 于是那棵子树里的文件既不在 `seen` 里、
169
+ * 又不置 `truncated`,调用方就会把它们当"已删除"清掉(派生索引静默丢失,且每次索引都白清一遍)。
170
+ * 读不到 ≠ 不存在:置 `truncated` 是最保守的处置。
132
171
  */
133
172
  /**
134
173
  * 一个目录是否**自带 store**(即它自己已经是一个被索引过的项目根)。
@@ -186,7 +225,9 @@ export function walkDir(root, opts = {}) {
186
225
  const nestedStoreName = opts.nestedStoreName || null
187
226
  const out = []
188
227
  const skipped = []
228
+ const unreadable = []
189
229
  const stack = [[root, 0]]
230
+ let capped = false
190
231
  let truncated = false
191
232
  let hitFileCap = false
192
233
  while (stack.length) {
@@ -195,6 +236,10 @@ export function walkDir(root, opts = {}) {
195
236
  try {
196
237
  entries = readdirSync(dir, { withFileTypes: true })
197
238
  } catch {
239
+ // 读不到 ≠ 不存在。旧实现直接 continue,于是这片子树被当成"已删除"(调用方拿
240
+ // seen 去清 unseen),而且失败是静默的。置 truncated 让调用方跳过清理。
241
+ unreadable.push(dir)
242
+ truncated = true
198
243
  continue
199
244
  }
200
245
  for (const entry of entries) {
@@ -208,12 +253,14 @@ export function walkDir(root, opts = {}) {
208
253
  }
209
254
  if (depth + 1 > maxDepth) {
210
255
  truncated = true
256
+ capped = true
211
257
  continue
212
258
  }
213
259
  stack.push([full, depth + 1])
214
260
  } else {
215
261
  if (out.length >= maxFiles) {
216
262
  truncated = true
263
+ capped = true
217
264
  hitFileCap = true
218
265
  break
219
266
  }
@@ -224,7 +271,8 @@ export function walkDir(root, opts = {}) {
224
271
  }
225
272
  out.sort()
226
273
  skipped.sort()
227
- return { files: out, truncated, skipped }
274
+ unreadable.sort()
275
+ return { files: out, truncated, capped, skipped, unreadable }
228
276
  }
229
277
 
230
278
  export function isSupportedDoc(ext) {
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 路径 token 抽取(纯函数、零依赖,readiness 与 ops 共用)。
3
+ *
4
+ * 为什么会有这个模块:同一套规则原先在 `readiness.js`(抽人类消息/工具参数里的路径)与
5
+ * `ops.js`(抽 shell 命令的写目标)里各抄了一份,而 `ops.js` 那份的注释写着
6
+ * 「与 readiness.extractPaths 同规则」—— 其实不是:它只抄了「带扩展名的路径」,
7
+ * 漏掉了「点开头的裸文件名」(`.gitignore` / `.npmrc` / `.env`)。
8
+ *
9
+ * 后果不是文案问题:`ops.targets` 正是 `when.writes` 的匹配面,于是
10
+ * `rm -f .gitignore` 在 ops 侧抽不出写目标(实测 targets=[]),一条明确写了
11
+ * `writes: ['.gitignore']` 的教训被静默漏召 —— 注释还在替这份漂移担保。
12
+ * 收敛到这里,只保留一个事实,两个调用方拿到的是同一份结果。
13
+ *
14
+ * 规则(两类 token,先「带扩展名」后「点开头」,各自按出现顺序去重):
15
+ * 1. 带扩展名的路径:`src/util/fs.js`、`README.md`、`.env.bak`(点算普通字符);
16
+ * 2. 点开头的裸文件名:只认 token 起始处(行首 / 空白 / 引号 / 左括号之后)的 `.xxx`
17
+ * —— `src/.env` 这类中缀点文件名没有扩展名可依,与普通点号无法区分,不在规则内;
18
+ * 调用方若已知道完整路径,应直接并入,而不是指望从文本里猜。
19
+ *
20
+ * 只导出函数、不导出正则:全局正则一旦被 `.test()`/`.exec()` 用过就带 `lastIndex` 状态,
21
+ * 共享出去等于把「顺序敏感」的坑一起共享。`matchAll` 内部克隆正则,这里无状态。
22
+ * @module dsh-project-memory/util/path-token
23
+ */
24
+
25
+ const PATH_TOKEN = /(?:[A-Za-z0-9_.@-]+\/)*[A-Za-z0-9_.@-]+\.[A-Za-z][A-Za-z0-9]{0,7}\b/g
26
+ const DOTFILE_TOKEN = /(?:^|[\s"'`(])(\.[A-Za-z0-9_-]{2,})/g
27
+
28
+ /**
29
+ * 文本 → 路径 token(去重、顺序确定、无副作用)。
30
+ * @param {unknown} text - 工具调用参数、人类消息或 shell 命令。
31
+ * @returns {string[]} 去重后的路径 token;空/缺失输入返回 `[]`。
32
+ */
33
+ export function extractPathTokens(text) {
34
+ const s = String(text || '')
35
+ if (!s) return []
36
+ const out = new Set()
37
+ for (const m of s.matchAll(PATH_TOKEN)) out.add(m[0])
38
+ for (const m of s.matchAll(DOTFILE_TOKEN)) out.add(m[1])
39
+ return [...out]
40
+ }
package/src/watch.js CHANGED
@@ -13,6 +13,8 @@ export class WatchManager {
13
13
  this.timer = null
14
14
  this._polling = false
15
15
  this._truncationWarned = new Set()
16
+ /** 已就「读不到的目录」告警过的根:同上,只提示一次。 */
17
+ this._unreadableWarned = new Set()
16
18
  /** 已就「跳过了嵌套项目根」告警过的根:同上,只提示一次。 */
17
19
  this._nestedStoreWarned = new Set()
18
20
  }
@@ -165,7 +167,7 @@ export class WatchManager {
165
167
  // 本轮用的 store:命中缓存即 O(1),被逐出则重新读盘。整个 pollRoot 期间共用同一个实例。
166
168
  const store = this.storeFor(root)
167
169
 
168
- const { files, truncated, skipped: nestedRoots } = walkDir(root, {
170
+ const { files, truncated, capped, skipped: nestedRoots, unreadable } = walkDir(root, {
169
171
  ...scanLimits(this.config),
170
172
  nestedStoreName: memoryDirName(this.config),
171
173
  })
@@ -178,7 +180,16 @@ export class WatchManager {
178
180
  'their content is refreshed by their own root, and any duplicate copy previously indexed here is being removed.',
179
181
  )
180
182
  }
181
- if (truncated && !this._truncationWarned.has(root)) {
183
+ if (unreadable.length && !this._unreadableWarned.has(root)) {
184
+ // 读不到 ≠ 已删除:本轮跳过快照清理(见下方 unseen),既有条目原样保留。只提示一次。
185
+ this._unreadableWarned.add(root)
186
+ const rels = unreadable.map((p) => storeKey(relativePath(root, p)))
187
+ console.error(
188
+ `[dsh-project-memory] watch of ${root} could not read ${unreadable.length} director${unreadable.length === 1 ? 'y' : 'ies'} ` +
189
+ `(${rels.join(', ')}); they are skipped and nothing under them is treated as deleted.`,
190
+ )
191
+ }
192
+ if (capped && !this._truncationWarned.has(root)) {
182
193
  // 只提示一次:这是一条**永久**的降级说明,不是每轮都要刷屏的故障。
183
194
  this._truncationWarned.add(root)
184
195
  const { maxFiles, maxDepth } = scanLimits(this.config)
@@ -237,7 +248,8 @@ export class WatchManager {
237
248
 
238
249
  // 单事务写盘;CAS 失败的条目本轮不落快照,下一轮自然重试。
239
250
  // 截断时**不传 unseen**:没扫到的文件不等于被删了,否则一份被上限截掉的树每轮都会
240
- // 把自己的记忆删掉一半(先删再下轮重新索引,纯粹的抖动)。
251
+ // 把自己的记忆删掉一半(先删再下轮重新索引,纯粹的抖动)。`truncated` 同样覆盖
252
+ // "有目录读不到"(EACCES)这一路。
241
253
  const { stale, removed } = commitFileUpdates(store, {
242
254
  updates,
243
255
  unseen: truncated ? null : seen,