@yolk_vat-y/dsh-project-memory 0.6.5 → 0.6.7

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
@@ -1,13 +1,8 @@
1
1
  // 动作平面:把"这一步在做什么"从工具调用解析成有限的 op + 写目标 + 主机环境。
2
- //
3
- // 为什么不能继续用文本匹配:语料(路径、命令、被读文件正文)里的字符串可以冒充动作。
4
- // 实测病征是 `keyword:rm` 命中 `dcterms`、`keyword:pptx` 命中一个文件扩展名。
2
+ // 不能用文本匹配:语料(路径、命令、被读文件正文)里的字符串可以冒充动作。
5
3
  // op 与 target 是低维、可枚举、可审计的:不随文本长度变化,也不会被正文污染。
6
- //
7
- // 分工:ops.js 只负责"把调用读成什么动作",不负责决定注入什么(那是 readiness/auto-inject)。
8
- // 刻意不 import readiness:readiness 要 import 本模块的 op 闭集,反向依赖会造成循环。
9
- // 路径 token 的规则因此收在 util/path-token.js —— 它谁也不依赖,两个模块都能 import
10
- // (原先这里就地抄了一份,注释还写着"与 readiness.extractPaths 同规则",实际已漂移)。
4
+ // 只读"是什么动作",不决定注入什么(那是 readiness/auto-inject);刻意不 import 它,避免循环。
5
+ // 路径 token 规则收在 util/path-token.js —— 它无依赖,两个模块共用。
11
6
 
12
7
  import { extractPathTokens } from './util/path-token.js'
13
8
 
@@ -32,19 +27,18 @@ export const OP_IDS = [
32
27
  ]
33
28
 
34
29
  /**
35
- * 兜底 op:它们描述的是"发生了某类操作",信息量低、假阳性高。
36
- * 允许写进 `when.ops`,但自检会 warn——兜底 op 只该命中兜底级记忆。
30
+ * 兜底 op:信息量低、假阳性高。允许写进 `when.ops`,但自检会 warn——只该命中兜底级记忆。
37
31
  */
38
32
  export const FALLBACK_OPS = new Set(['shell-run', 'file-write', 'query-memory'])
39
33
 
40
34
  /**
41
- * 弱 op:日常动作。它本身不构成边界(每天都在提交),所以当条目**已经有更精确的 writes**
42
- * 时,迁移会把弱 op 丢掉——留着它只会把"改这个文件时"扩大成"任何一次提交时"。
43
- * 实测:`git-commit` 让一条"别删内部文档"的教训在发版场景里被注入。
35
+ * 弱 op:日常动作,本身不构成边界。条目**已有更精确的 writes** 时迁移会丢掉弱 op,
36
+ * 留着只会把"改这个文件时"扩大成"任何一次提交时"。实测 `git-commit` 让一条"别删内部文档"
37
+ * 的教训在发版场景里被注入。
44
38
  */
45
39
  export const WEAK_OPS = new Set([...FALLBACK_OPS, 'git-commit', 'git-push'])
46
40
 
47
- /** 旧 action id → op。旧值里有一批从来没进过 ACTION_LEXICON 的死值,这里给它们一个归宿。 */
41
+ /** 旧 action id → op;没有对应动作的映射为 null。 */
48
42
  export const LEGACY_ACTION_ALIAS = {
49
43
  'git-add': 'git-commit',
50
44
  'npm-pack': 'npm-publish',
@@ -72,38 +66,259 @@ const FETCH_TOOLS = new Set(['web_fetch', 'web_search'])
72
66
  const SHELL_TOOLS = new Set(['bash', 'shell', 'pwsh', 'powershell', 'run', 'exec', 'job_run'])
73
67
  const QUERY_TOOLS = new Set(['query_memory', 'recall'])
74
68
 
75
- /** bash 命令 → op。顺序有意义:先具体后兜底。 */
76
- const SHELL_OP_RULES = [
77
- [/\bnpm\s+(publish|pack)\b/, 'npm-publish'],
78
- [/\bnpm\s+version\b/, 'release'],
79
- [/\bgit\s+tag\b/, 'release'],
80
- [/\bgit\s+push\b/, 'git-push'],
81
- [/\bgit\s+(commit|add)\b/, 'git-commit'],
82
- [/\bgit\s+(checkout|restore|reset)\b/, 'file-write'],
83
- // `\brm\b` 而不是 `rm\s+-[rf]`:后者被 `\b` 卡在 'rm -rf' 的 r 后面(f 还是词字符),永远匹配不上。
84
- [/\b(rm|git\s+rm|unlink|rmdir|shred)\b/, 'file-delete'],
85
- [/\b(kubectl|docker\s+push|systemctl\s+restart|pm2\s+(deploy|restart)|vercel|netlify\s+deploy)\b/, 'deploy'],
86
- [/\b(migrate|alembic|prisma\s+migrate|db:migrate)\b/, 'migrate'],
87
- // 注意:只认"渲染器",不认 .pptx 扩展名——否则给 pptx 改个时间戳也会命中"做 PPT"
88
- [/(pptxgenjs|soffice|libreoffice|render\.sh|marp|pandoc|slidev)/, 'render-doc'],
89
- [/(bench\.mjs|\bbench(mark)?\b)/, 'run-bench'],
90
- [/\b(curl|wget|web_fetch)\b/, 'fetch-web'],
91
- ]
69
+ /**
70
+ * 会写盘的文件类命令头。**只作用于命令头**,不对整条命令做无锚点正则:
71
+ * 参数、路径、引号里的词都只是**提及**(`find … bench …` 的目录名、`grep -rn "migrate" docs`)。
72
+ * 命令头才是"这个 shell 到底在做什么"的唯一可靠位置。
73
+ */
74
+ const WRITE_HEADS = new Set(['rm', 'rmdir', 'unlink', 'shred', 'mv', 'cp', 'touch', 'tee', 'truncate', 'mkdir'])
75
+ /**
76
+ * Windows / PowerShell 的写盘命令。与 POSIX 同名命令并列而不是另开分支:`isWriteSegment()` 与
77
+ * `opsOfHead()` 都按命令头查表,多一组名字就够了。缺了它们,Windows 上的 `del a.ts` /
78
+ * `copy a b` / `Set-Content a.ts` 会全部退化成兜底 op `shell-run`,`writes` 也抽不出来。
79
+ */
80
+ const WINDOWS_WRITE_HEADS = new Set([
81
+ 'del', 'erase', 'rd', 'move', 'ren', 'rename', 'copy', 'xcopy', 'robocopy', 'md',
82
+ 'remove-item', 'clear-content', 'new-item', 'set-content', 'add-content', 'out-file',
83
+ 'copy-item', 'move-item', 'rename-item',
84
+ ])
85
+ /** 包在真命令前面的词:跳过它们再取命令头。 */
86
+ const WRAPPERS = new Set(['sudo', 'env', 'command', 'builtin', 'exec', 'time', 'nohup', 'nice', 'stdbuf'])
87
+ /** 递归解析 `bash -c "…"` / `pwsh -Command "…"` / `cmd /c …` 的壳;深度上限防套娃。 */
88
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'pwsh', 'powershell', 'cmd'])
89
+ /** 分段:按未加引号的 `\n ; && || | &` 切。引号里的分隔符是正文,不是命令边界。 */
90
+ function unquotedSegments(text) {
91
+ const out = []
92
+ let cur = ''
93
+ let quote = null
94
+ for (let i = 0; i < text.length; i++) {
95
+ const c = text[i]
96
+ if (quote) {
97
+ cur += c
98
+ if (c === '\\' && quote === '"' && i + 1 < text.length) { cur += text[++i]; continue }
99
+ if (c === quote) quote = null
100
+ continue
101
+ }
102
+ if (c === "'" || c === '"' || c === '`') { quote = c; cur += c; continue }
103
+ // `#` 只有在词首才是注释:URL 的 fragment、`#!` 之类不能当注释切掉。
104
+ if (c === '#' && (i === 0 || /\s/.test(text[i - 1]))) {
105
+ while (i < text.length && text[i] !== '\n') i++
106
+ out.push(cur)
107
+ cur = ''
108
+ continue
109
+ }
110
+ if (c === '\n' || c === ';') { out.push(cur); cur = ''; continue }
111
+ if ((c === '&' || c === '|') && text[i + 1] === c) { out.push(cur); cur = ''; i++; continue }
112
+ if (c === '|' || c === '&') { out.push(cur); cur = ''; continue }
113
+ cur += c
114
+ }
115
+ out.push(cur)
116
+ return out.map((s) => s.trim()).filter(Boolean)
117
+ }
118
+
119
+ /** 剥掉 heredoc 正文,只留 opener 那一行:正文是脚本内容,不是 shell 命令。 */
120
+ function stripHeredocBodies(text) {
121
+ return text.replace(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\2(?=\s*(?:$|\n))/g, (m) => `${m.split('\n')[0]}\n`)
122
+ }
123
+
124
+ /** 简单词法切分(去引号、保转义)。只用于取命令头与参数,不追求完整 shell 语义。 */
125
+ function tokenizeWords(segment) {
126
+ const out = []
127
+ let cur = ''
128
+ let quote = null
129
+ for (let i = 0; i < segment.length; i++) {
130
+ const c = segment[i]
131
+ if (quote) {
132
+ if (c === quote) { quote = null; continue }
133
+ // 双引号里的 `\"` 是转义;但 Windows 路径 `"C:\Program Files\nodejs\npm.cmd"` 里的 `\`
134
+ // 是分隔符,吞掉它命令头就变成 `c:program files…`,整个动作面失配。
135
+ if (c === '\\' && quote === '"' && i + 1 < segment.length && /["\\]/.test(segment[i + 1])) {
136
+ cur += segment[++i]
137
+ continue
138
+ }
139
+ cur += c
140
+ continue
141
+ }
142
+ if (c === "'" || c === '"' || c === '`') { quote = c; continue }
143
+ if (/\s/.test(c)) { if (cur) { out.push(cur); cur = '' } continue }
144
+ if (c === '\\' && i + 1 < segment.length) {
145
+ // POSIX 的 `\ ` 是转义空格,Windows 的 `\` 是路径分隔符,两种都要能吃:只有"被转义的
146
+ // 确实是分隔语义字符"时才吞掉反斜杠,否则按字面量保留(`src\util\fs.js` 不能被压成
147
+ // `srcutilfs.js`,否则写目标与命令头都抽不出来)。
148
+ const next = segment[i + 1]
149
+ if (/[\s"'`\\|&;<>()$#]/.test(next)) { cur += next; i++; continue }
150
+ cur += c
151
+ continue
152
+ }
153
+ cur += c
154
+ }
155
+ if (cur) out.push(cur)
156
+ return out
157
+ }
158
+
159
+ /** 跳过环境变量赋值与 sudo/env/time 之类包装,返回真正的命令头与参数。 */
160
+ function commandHead(tokens) {
161
+ let i = 0
162
+ while (i < tokens.length) {
163
+ const t = tokens[i]
164
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || WRAPPERS.has(t) || t === '(') { i++; continue }
165
+ break
166
+ }
167
+ const raw = tokens[i] || ''
168
+ // 目录(两种分隔符)+ Windows 可执行后缀都要剥:`C:\Program Files\nodejs\npm.cmd` → `npm`。
169
+ // 只 `split('/')` 会让 Windows 上的绝对路径命令头整个失配,`.cmd`/`.exe` 同理。
170
+ const head = raw.split(/[\\/]/).pop().toLowerCase().replace(/\.(exe|cmd|bat|com|ps1)$/, '')
171
+ let rest = tokens.slice(i + 1)
172
+ if (rest.length && rest[rest.length - 1] === ')') rest = rest.slice(0, -1)
173
+ return { head, rest }
174
+ }
175
+
176
+ // 路径两侧的分隔符都算:Windows 上 `node scripts\bench.mjs` 与 `pnpm exec marp\cli` 是常态。
177
+ const BENCH_ARG = /(^|[\\/])bench(mark)?([\\/]|\.(mjs|js|ts|cjs|mts|json)$)/i
178
+ const RENDER_ARG = /(^|[\\/])(pptxgenjs|soffice|libreoffice|pandoc|marp|slidev)(\b|[\\/])/i
179
+ /** npm script 名(`bench` / `bench:peak` / `benchmark`):`npm run bench` 是文档里的跑法。 */
180
+ const BENCH_SCRIPT = /^(bench|benchmark)(:[\w.-]+)?$/i
181
+ /** 包管理器里带值的全局 flag(`npm --prefix x …`)。 */
182
+ const PM_VALUE_FLAGS = new Set(['-C', '--prefix', '--cwd', '-w', '--workspace', '--filter', '-F', '--dir'])
183
+
184
+ /** 跳过全局 flag,返回第一个子命令及其后的参数。 */
185
+ function packageSubcommand(args) {
186
+ for (let i = 0; i < args.length; i++) {
187
+ if (args[i].startsWith('-')) {
188
+ if (PM_VALUE_FLAGS.has(args[i])) i++
189
+ continue
190
+ }
191
+ return { sub: args[i].toLowerCase(), rest: args.slice(i + 1) }
192
+ }
193
+ return { sub: '', rest: [] }
194
+ }
195
+
196
+ /** 包管理器 / npx 之后的参数里识别动作。只有命令头是 runner 时才走这里。 */
197
+ function runnerOps(args) {
198
+ const ops = []
199
+ if (args.some((a) => RENDER_ARG.test(a))) ops.push('render-doc')
200
+ if (args.some((a) => BENCH_ARG.test(a) || BENCH_SCRIPT.test(a))) ops.push('run-bench')
201
+ if (args[0] === 'migrate' || args.some((a) => /^db:migrate$/.test(a))) ops.push('migrate')
202
+ return ops
203
+ }
204
+
205
+ /** 命令头 → op。空数组表示"认得这个头,但它不是这些动作"。 */
206
+ function opsOfHead(head, rest) {
207
+ const sub = String(rest[0] || '').toLowerCase()
208
+ switch (head) {
209
+ case 'npm': case 'pnpm': case 'yarn': case 'bun': {
210
+ const { sub: name, rest: after } = packageSubcommand(rest)
211
+ if (name === 'publish' || name === 'pack') return ['npm-publish']
212
+ if (name === 'version') return ['release']
213
+ if (name === 'run' || name === 'exec' || name === 'dlx' || name === 'x') return runnerOps(after)
214
+ // `yarn bench` / `bun bench` 这类"直接按脚本名跑"的形态
215
+ if (name && BENCH_SCRIPT.test(name)) return ['run-bench']
216
+ return []
217
+ }
218
+ case 'npx': case 'pnpx': case 'bunx':
219
+ return runnerOps(rest)
220
+ case 'node': case 'tsx': case 'deno':
221
+ return rest.some((a) => BENCH_ARG.test(a)) ? ['run-bench'] : []
222
+ case 'git': {
223
+ const gsub = firstSubcommand(rest)
224
+ if (gsub === 'commit' || gsub === 'add') return ['git-commit']
225
+ if (gsub === 'push') return ['git-push']
226
+ if (gsub === 'tag') return ['release']
227
+ if (gsub === 'rm') return ['file-delete']
228
+ if (gsub === 'checkout' || gsub === 'restore' || gsub === 'reset') return ['file-write']
229
+ return []
230
+ }
231
+ case 'rm': case 'rmdir': case 'unlink': case 'shred':
232
+ return ['file-delete']
233
+ case 'kubectl': case 'systemctl': case 'pm2': case 'vercel': case 'netlify':
234
+ return ['deploy']
235
+ case 'docker':
236
+ return sub === 'push' || sub === 'compose' || sub === 'stack' ? ['deploy'] : []
237
+ case 'migrate': case 'alembic':
238
+ return ['migrate']
239
+ case 'prisma':
240
+ return sub === 'migrate' || sub === 'db' ? ['migrate'] : []
241
+ case 'soffice': case 'libreoffice': case 'pandoc': case 'marp': case 'slidev':
242
+ return ['render-doc']
243
+ case 'bench': case 'benchmark':
244
+ return ['run-bench']
245
+ case 'curl': case 'wget':
246
+ return ['fetch-web']
247
+ // Windows / PowerShell 的写盘命令:与上面的 POSIX 名字同等对待。
248
+ case 'del': case 'erase': case 'rd':
249
+ case 'remove-item': case 'clear-content':
250
+ return ['file-delete']
251
+ case 'copy': case 'move': case 'ren': case 'rename': case 'xcopy': case 'robocopy':
252
+ case 'new-item': case 'set-content': case 'add-content': case 'out-file':
253
+ case 'copy-item': case 'move-item': case 'rename-item':
254
+ return ['file-write']
255
+ default:
256
+ return []
257
+ }
258
+ }
259
+
260
+ /** 未加引号的 `>` / `>>` 目标。引号里的 `>` 是正文(`echo "a > b"`),`<<` 不是写。 */
261
+ function redirectTargets(segment) {
262
+ const out = []
263
+ let quote = null
264
+ for (let i = 0; i < segment.length; i++) {
265
+ const c = segment[i]
266
+ if (quote) {
267
+ if (c === '\\' && quote === '"') { i++; continue }
268
+ if (c === quote) quote = null
269
+ continue
270
+ }
271
+ if (c === "'" || c === '"' || c === '`') { quote = c; continue }
272
+ if (c === '\\') { i++; continue }
273
+ if (c !== '>') continue
274
+ if (segment[i + 1] === '>') i++
275
+ let j = i + 1
276
+ while (j < segment.length && /\s/.test(segment[j])) j++
277
+ let tok = ''
278
+ while (j < segment.length && !/[\s;|&)]/.test(segment[j])) { tok += segment[j]; j++ }
279
+ i = Math.max(i, j - 1)
280
+ if (!tok) continue
281
+ // `nul` 是 Windows 的 /dev/null:`2>nul` 不是写文件。
282
+ if (tok.startsWith('&') || /^nul:?$/i.test(tok) || tok === '/dev/null' || tok.startsWith('/dev/stdout') || tok.startsWith('/dev/stderr')) continue
283
+ if (/^\d+$/.test(tok)) continue
284
+ out.push(tok)
285
+ }
286
+ return out
287
+ }
288
+
289
+ /** 这个段落在写盘吗?写盘命令头、`sed -i`、重定向都算。 */
290
+ function isWriteSegment(head, rest, redirects) {
291
+ if (redirects.length) return true
292
+ if (WRITE_HEADS.has(head) || WINDOWS_WRITE_HEADS.has(head)) return true
293
+ if (head === 'sed' && rest.includes('-i')) return true
294
+ if (head === 'git' && String(rest[0] || '').toLowerCase() === 'rm') return true
295
+ return false
296
+ }
92
297
 
93
298
  /**
94
- * 会改动文件系统的 shell 动作:只有这些命令的路径才算"写目标"。
95
- *
96
- * 重定向这一支要排除"丢弃输出",否则 `2>/dev/null`、`2>&1`、`>/dev/null` 这些
97
- * **纯读命令的惯用写法**会被当成写盘:实测 `ls .agents 2>/dev/null | head` 抽出
98
- * targets=['.agents']、`cat package.json 2>&1` 抽出 ['package.json'] —— 写目标正是
99
- * `when.writes` 的匹配面,于是"读/列目录"会误触发一条 `writes:['package.json']` 的教训。
100
- *
101
- * 规则:`>` / `>>` / `2>` 后面的目标若是 `&`(合并 fd)或 `/dev/null`(丢弃),不算写;
102
- * `> file`、`2> file`、`1>> file` 仍算写。
299
+ * git 的子命令要跳过全局 flag(`git -C repo commit` 不能被读成 `-C`)。
300
+ * @param {string[]} args
301
+ * @returns {string} 小写子命令;没有则空串
103
302
  */
104
- const SHELL_WRITE_RE =
105
- /\b(rm|rmdir|unlink|shred|mv|cp|touch|tee|truncate|mkdir)\b|(?:^|[^>])[0-9]?>>?\s*(?!&|\/dev\/null(?:\b|$))\S|\bsed\s+-i\b/
303
+ function firstSubcommand(args) {
304
+ const takesValue = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path'])
305
+ for (let i = 0; i < args.length; i++) {
306
+ const arg = args[i]
307
+ if (arg.startsWith('-')) {
308
+ if (takesValue.has(arg)) i++
309
+ continue
310
+ }
311
+ return arg.toLowerCase()
312
+ }
313
+ return ''
314
+ }
315
+
316
+ /** 合并去重(保持顺序)。 */
317
+ function pushUnique(list, value) {
318
+ if (!list.includes(value)) list.push(value)
319
+ }
106
320
 
321
+ /** WSL 路径或 Windows 壳的签名:只用于 hosts,不参与动作判定。 */
107
322
  const WSL_HINT_RE = /\/mnt\/[a-z]\//i
108
323
 
109
324
  function safeJson(text) {
@@ -129,21 +344,44 @@ function argsFields(argsText) {
129
344
  }
130
345
  }
131
346
 
132
- /** bash 命令 → { ops, targets, hosts }。 */
133
- export function classifyShellCommand(command) {
134
- const cmd = String(command || '')
347
+ /** 内部的递归实现:`bash -c` 会再解析一层。 */
348
+ function classifyCommand(command, depth) {
349
+ const raw = String(command || '')
135
350
  const ops = []
136
- if (cmd) {
137
- for (const [re, op] of SHELL_OP_RULES) {
138
- if (re.test(cmd) && !ops.includes(op)) ops.push(op)
351
+ const targets = []
352
+ for (const segment of unquotedSegments(stripHeredocBodies(raw))) {
353
+ const { head, rest } = commandHead(tokenizeWords(segment))
354
+ if (SHELLS.has(head) && depth < 2) {
355
+ // POSIX 的 `-c` / `-lc` / `-ec`;PowerShell 的 `-Command`;cmd 的 `/c`。
356
+ const ci = rest.findIndex((a) => /^-[A-Za-z]{0,4}c$/.test(a) || /^-command$/i.test(a) || /^\/c$/i.test(a))
357
+ if (ci >= 0 && rest[ci + 1]) {
358
+ const inner = classifyCommand(rest.slice(ci + 1).join(' '), depth + 1)
359
+ for (const op of inner.ops) if (op !== 'shell-run') pushUnique(ops, op)
360
+ for (const t of inner.targets) pushUnique(targets, t)
361
+ }
362
+ } else {
363
+ for (const op of opsOfHead(head, rest)) pushUnique(ops, op)
364
+ }
365
+ const redirects = redirectTargets(segment)
366
+ if (isWriteSegment(head, rest, redirects)) {
367
+ for (const t of extractPathTokens(segment)) pushUnique(targets, t)
139
368
  }
140
369
  }
141
370
  if (!ops.length) ops.push('shell-run')
142
- const targets = SHELL_WRITE_RE.test(cmd) ? extractPathTokens(cmd) : []
143
- const hosts = WSL_HINT_RE.test(cmd) || /\b(powershell|pwsh|cmd)\.exe\b/i.test(cmd) ? ['wsl'] : []
371
+ // 主机面:`/mnt/c/…` 是 WSL 的路径签名;`pwsh.exe` / `powershell.exe` / `cmd.exe` 是**原生
372
+ // Windows** 的壳签名——旧实现把它也标成 `wsl`,于是 `guard.hosts: ['wsl']` 的条目在原生
373
+ // Windows 上会被放行(它本该只在 WSL 里生效)。壳名后面必须跟一个选项(`-Command` / `/c`),
374
+ // 否则 `grep cmd README.md` 这种"正文里提到 cmd"也会被当成壳签名——`hosts` 只用于收窄,误判的
375
+ // 代价是让本该被挡住的条目放行。
376
+ const nativeShell = /\b(powershell|pwsh|cmd)(\.exe)?\b\s*(?:-\S|\/c\b)/i
377
+ const hosts = WSL_HINT_RE.test(raw) ? ['wsl'] : nativeShell.test(raw) ? ['windows'] : []
144
378
  return { ops, targets, hosts }
145
379
  }
146
380
 
381
+ export function classifyShellCommand(command) {
382
+ return classifyCommand(command, 0)
383
+ }
384
+
147
385
  /**
148
386
  * 一次工具调用 → { ops, targets, hosts }。
149
387
  * @param {string} name 工具名
@@ -197,10 +435,8 @@ export function activityFromText(text) {
197
435
  // 先按"工具调用"解析(`edit {"file_path":"..."}`):结构化参数比正则猜命令可靠得多。
198
436
  const call = /^\s*([A-Za-z_][\w-]*)\s+(\{[\s\S]*\})\s*$/.exec(line)
199
437
  const r = call ? classifyToolCall(call[1], call[2]) : classifyShellCommand(line)
200
- // 纯文本行里没有 shell 动作时不要退化成 shell-run(那是噪音源)。但**只丢这个 op**:
201
- // 行里的写目标/主机是具体事实(要靠路径 token、/mnt/ 这类签名才抽得出,泛泛的散文产不出来),
202
- // 一起丢掉会让 `bash {"command":"echo x >> .gitignore"}` 这种 shell-run-only 的写意图
203
- // 到不了 when.writes —— 实测它连结构化工具调用行的写目标都会被静默吞掉。
438
+ // 纯文本行里没有 shell 动作时不要退化成 shell-run(噪音源)。但**只丢这个 op**:
439
+ // 行里的写目标/主机是具体事实,一起丢会让 shell-run-only 的写意图到不了 when.writes。
204
440
  const noiseOp = r.ops.length === 1 && r.ops[0] === 'shell-run' && !/\b\w+\s+-/.test(line)
205
441
  if (!noiseOp) for (const op of r.ops) ops.add(op)
206
442
  for (const t of r.targets) targets.add(t)
@@ -3,7 +3,7 @@
3
3
  import { readFileSync, statSync } from 'node:fs'
4
4
  import path from 'node:path'
5
5
 
6
- const cache = new Map() // root -> { tags: string[], mtimeMs: number }
6
+ const cache = new Map() // root -> { tags: string[], stamp: string }
7
7
 
8
8
  function tryRead(file) {
9
9
  try {
@@ -13,6 +13,19 @@ function tryRead(file) {
13
13
  }
14
14
  }
15
15
 
16
+ /** 缓存键:三份清单的 mtime 拼串;缺失用 `-`,这样没有 package.json 的项目也能命中缓存。 */
17
+ function manifestStamp(root) {
18
+ const parts = []
19
+ for (const name of ['package.json', 'go.mod', 'Cargo.toml']) {
20
+ try {
21
+ parts.push(`${name}:${statSync(path.join(root, name)).mtimeMs}`)
22
+ } catch {
23
+ parts.push(`${name}:-`)
24
+ }
25
+ }
26
+ return parts.join('|')
27
+ }
28
+
16
29
  function depsOf(manifest, fields) {
17
30
  const tags = new Set()
18
31
  for (const f of fields) {
@@ -41,20 +54,12 @@ function depsOf(manifest, fields) {
41
54
  */
42
55
  export function projectTags(root) {
43
56
  if (!root) return []
44
- try {
45
- const cached = cache.get(root)
46
- const pkgPath = path.join(root, 'package.json')
47
- const marker = pkgPath
48
- const mtime = statSync(marker).mtimeMs
49
- if (cached && cached.mtimeMs === mtime) return cached.tags
50
- const tags = collectTags(root)
51
- cache.set(root, { tags, mtimeMs: mtime })
52
- return tags
53
- } catch {
54
- const tags = collectTags(root)
55
- cache.set(root, { tags, mtimeMs: 0 })
56
- return tags
57
- }
57
+ const stamp = manifestStamp(root)
58
+ const cached = cache.get(root)
59
+ if (cached && cached.stamp === stamp) return cached.tags
60
+ const tags = collectTags(root)
61
+ cache.set(root, { tags, stamp })
62
+ return tags
58
63
  }
59
64
 
60
65
  function collectTags(root) {