@yolk_vat-y/dsh-project-memory 0.6.6 → 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',
@@ -73,19 +67,25 @@ const SHELL_TOOLS = new Set(['bash', 'shell', 'pwsh', 'powershell', 'run', 'exec
73
67
  const QUERY_TOOLS = new Set(['query_memory', 'recall'])
74
68
 
75
69
  /**
76
- * 会写盘的文件类命令头。**只作用于命令头**,不再对整条命令做无锚点正则。
77
- *
78
- * 为什么改:旧实现对整条命令跑 `/\b(bench|migrate|rm|删除)\b/`,于是
79
- * `find src client test scripts bench docs -type f` 里的目录名 `bench` → `run-bench`(实测注入
80
- * 了 4 条基准 procedure、1777 字符);`grep -rn "migrate" docs` → `migrate`;子代理提示词里的
81
- * "删除/迁移" → `file-delete`/`migrate`(实测父会话连吃 8 步)。
82
- * 命令头是"这个 shell 到底在做什么"的唯一可靠位置;参数、路径、引号里的词都是**提及**。
70
+ * 会写盘的文件类命令头。**只作用于命令头**,不对整条命令做无锚点正则:
71
+ * 参数、路径、引号里的词都只是**提及**(`find … bench …` 的目录名、`grep -rn "migrate" docs`)。
72
+ * 命令头才是"这个 shell 到底在做什么"的唯一可靠位置。
83
73
  */
84
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
85
  /** 包在真命令前面的词:跳过它们再取命令头。 */
86
86
  const WRAPPERS = new Set(['sudo', 'env', 'command', 'builtin', 'exec', 'time', 'nohup', 'nice', 'stdbuf'])
87
- /** 递归解析 `bash -c "…"` 的壳;深度上限防 `bash -c 'bash -c …'`。 */
88
- const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh'])
87
+ /** 递归解析 `bash -c "…"` / `pwsh -Command "…"` / `cmd /c …` 的壳;深度上限防套娃。 */
88
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh', 'pwsh', 'powershell', 'cmd'])
89
89
  /** 分段:按未加引号的 `\n ; && || | &` 切。引号里的分隔符是正文,不是命令边界。 */
90
90
  function unquotedSegments(text) {
91
91
  const out = []
@@ -116,10 +116,7 @@ function unquotedSegments(text) {
116
116
  return out.map((s) => s.trim()).filter(Boolean)
117
117
  }
118
118
 
119
- /**
120
- * 剥掉 heredoc 正文,只留下 opener 那一行。
121
- * 正文是脚本内容(可能是 python/js),不是 shell 命令——旧实现会把里面的 `mkdir`/`rm` 当动作。
122
- */
119
+ /** 剥掉 heredoc 正文,只留 opener 那一行:正文是脚本内容,不是 shell 命令。 */
123
120
  function stripHeredocBodies(text) {
124
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`)
125
122
  }
@@ -133,13 +130,26 @@ function tokenizeWords(segment) {
133
130
  const c = segment[i]
134
131
  if (quote) {
135
132
  if (c === quote) { quote = null; continue }
136
- if (c === '\\' && quote === '"' && i + 1 < segment.length) { cur += segment[++i]; 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
+ }
137
139
  cur += c
138
140
  continue
139
141
  }
140
142
  if (c === "'" || c === '"' || c === '`') { quote = c; continue }
141
143
  if (/\s/.test(c)) { if (cur) { out.push(cur); cur = '' } continue }
142
- if (c === '\\' && i + 1 < segment.length) { cur += segment[++i]; 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
+ }
143
153
  cur += c
144
154
  }
145
155
  if (cur) out.push(cur)
@@ -155,20 +165,39 @@ function commandHead(tokens) {
155
165
  break
156
166
  }
157
167
  const raw = tokens[i] || ''
158
- const head = raw.split('/').pop().toLowerCase()
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)$/, '')
159
171
  let rest = tokens.slice(i + 1)
160
172
  if (rest.length && rest[rest.length - 1] === ')') rest = rest.slice(0, -1)
161
173
  return { head, rest }
162
174
  }
163
175
 
164
- const BENCH_ARG = /(^|\/)bench(mark)?(\/|\.(mjs|js|ts|cjs|mts|json)$)/i
165
- const RENDER_ARG = /(^|\/)(pptxgenjs|soffice|libreoffice|pandoc|marp|slidev)(\b|\/)/i
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
+ }
166
195
 
167
196
  /** 包管理器 / npx 之后的参数里识别动作。只有命令头是 runner 时才走这里。 */
168
197
  function runnerOps(args) {
169
198
  const ops = []
170
199
  if (args.some((a) => RENDER_ARG.test(a))) ops.push('render-doc')
171
- if (args.some((a) => BENCH_ARG.test(a))) ops.push('run-bench')
200
+ if (args.some((a) => BENCH_ARG.test(a) || BENCH_SCRIPT.test(a))) ops.push('run-bench')
172
201
  if (args[0] === 'migrate' || args.some((a) => /^db:migrate$/.test(a))) ops.push('migrate')
173
202
  return ops
174
203
  }
@@ -178,9 +207,12 @@ function opsOfHead(head, rest) {
178
207
  const sub = String(rest[0] || '').toLowerCase()
179
208
  switch (head) {
180
209
  case 'npm': case 'pnpm': case 'yarn': case 'bun': {
181
- if (sub === 'publish' || sub === 'pack') return ['npm-publish']
182
- if (sub === 'version') return ['release']
183
- if (sub === 'run' || sub === 'exec' || sub === 'dlx' || sub === 'x') return runnerOps(rest.slice(1))
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']
184
216
  return []
185
217
  }
186
218
  case 'npx': case 'pnpx': case 'bunx':
@@ -212,6 +244,14 @@ function opsOfHead(head, rest) {
212
244
  return ['run-bench']
213
245
  case 'curl': case 'wget':
214
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']
215
255
  default:
216
256
  return []
217
257
  }
@@ -238,7 +278,8 @@ function redirectTargets(segment) {
238
278
  while (j < segment.length && !/[\s;|&)]/.test(segment[j])) { tok += segment[j]; j++ }
239
279
  i = Math.max(i, j - 1)
240
280
  if (!tok) continue
241
- if (tok.startsWith('&') || tok === '/dev/null' || tok.startsWith('/dev/stdout') || tok.startsWith('/dev/stderr')) 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
242
283
  if (/^\d+$/.test(tok)) continue
243
284
  out.push(tok)
244
285
  }
@@ -248,7 +289,7 @@ function redirectTargets(segment) {
248
289
  /** 这个段落在写盘吗?写盘命令头、`sed -i`、重定向都算。 */
249
290
  function isWriteSegment(head, rest, redirects) {
250
291
  if (redirects.length) return true
251
- if (WRITE_HEADS.has(head)) return true
292
+ if (WRITE_HEADS.has(head) || WINDOWS_WRITE_HEADS.has(head)) return true
252
293
  if (head === 'sed' && rest.includes('-i')) return true
253
294
  if (head === 'git' && String(rest[0] || '').toLowerCase() === 'rm') return true
254
295
  return false
@@ -311,7 +352,8 @@ function classifyCommand(command, depth) {
311
352
  for (const segment of unquotedSegments(stripHeredocBodies(raw))) {
312
353
  const { head, rest } = commandHead(tokenizeWords(segment))
313
354
  if (SHELLS.has(head) && depth < 2) {
314
- const ci = rest.indexOf('-c')
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))
315
357
  if (ci >= 0 && rest[ci + 1]) {
316
358
  const inner = classifyCommand(rest.slice(ci + 1).join(' '), depth + 1)
317
359
  for (const op of inner.ops) if (op !== 'shell-run') pushUnique(ops, op)
@@ -326,7 +368,13 @@ function classifyCommand(command, depth) {
326
368
  }
327
369
  }
328
370
  if (!ops.length) ops.push('shell-run')
329
- const hosts = WSL_HINT_RE.test(raw) || /\b(powershell|pwsh|cmd)\.exe\b/i.test(raw) ? ['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'] : []
330
378
  return { ops, targets, hosts }
331
379
  }
332
380
 
@@ -387,10 +435,8 @@ export function activityFromText(text) {
387
435
  // 先按"工具调用"解析(`edit {"file_path":"..."}`):结构化参数比正则猜命令可靠得多。
388
436
  const call = /^\s*([A-Za-z_][\w-]*)\s+(\{[\s\S]*\})\s*$/.exec(line)
389
437
  const r = call ? classifyToolCall(call[1], call[2]) : classifyShellCommand(line)
390
- // 纯文本行里没有 shell 动作时不要退化成 shell-run(那是噪音源)。但**只丢这个 op**:
391
- // 行里的写目标/主机是具体事实(要靠路径 token、/mnt/ 这类签名才抽得出,泛泛的散文产不出来),
392
- // 一起丢掉会让 `bash {"command":"echo x >> .gitignore"}` 这种 shell-run-only 的写意图
393
- // 到不了 when.writes —— 实测它连结构化工具调用行的写目标都会被静默吞掉。
438
+ // 纯文本行里没有 shell 动作时不要退化成 shell-run(噪音源)。但**只丢这个 op**:
439
+ // 行里的写目标/主机是具体事实,一起丢会让 shell-run-only 的写意图到不了 when.writes。
394
440
  const noiseOp = r.ops.length === 1 && r.ops[0] === 'shell-run' && !/\b\w+\s+-/.test(line)
395
441
  if (!noiseOp) for (const op of r.ops) ops.add(op)
396
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) {