@yolk_vat-y/dsh-project-memory 0.6.6 → 0.6.8
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/CHANGELOG.md +131 -0
- package/README.md +25 -36
- package/README.zh-CN.md +26 -37
- package/client/client.js +109 -132
- package/client/client.js.map +1 -1
- package/package.json +2 -2
- package/src/audit.js +33 -66
- package/src/auto-inject.js +133 -228
- package/src/chunker.js +1 -1
- package/src/client/paging.js +22 -50
- package/src/client/slash.ts +12 -48
- package/src/enhancer.js +45 -92
- package/src/index-pipeline.js +40 -17
- package/src/index.js +43 -73
- package/src/insight-store.js +79 -126
- package/src/lazy.js +193 -43
- package/src/ops.js +90 -44
- package/src/project-profile.js +20 -15
- package/src/readiness.js +120 -124
- package/src/recall.js +53 -136
- package/src/skill.js +3 -1
- package/src/store.js +239 -218
- package/src/tools/index-doc.js +15 -1
- package/src/tools/index-repo.js +7 -3
- package/src/tools/lesson-tools.js +2 -2
- package/src/util/fs.js +244 -217
- package/src/util/path-token.js +8 -3
- package/src/util/ru.js +3 -2
- package/src/util/search.js +15 -3
- package/src/vector-index.js +104 -108
- package/src/watch.js +48 -58
package/src/lazy.js
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import path from 'node:path'
|
|
2
2
|
import { statSync } from 'node:fs'
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
ROOT_SOURCES,
|
|
5
|
+
excludedEntryForPath,
|
|
6
|
+
findProjectRoot,
|
|
7
|
+
findProjectRootWithSource,
|
|
8
|
+
isGitIgnored,
|
|
9
|
+
isGitIgnoredBatch,
|
|
10
|
+
memoryRootFor,
|
|
11
|
+
relativePath,
|
|
12
|
+
rootRejection,
|
|
13
|
+
storeKey,
|
|
14
|
+
} from './util/fs.js'
|
|
4
15
|
import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
|
|
5
16
|
import { ProjectMemoryStore } from './store.js'
|
|
6
17
|
import { onFileObserved } from './enhancer.js'
|
|
@@ -9,45 +20,184 @@ import { sessionWorkingDir } from './util/session-dir.js'
|
|
|
9
20
|
// 根推导策略已收敛到 util/fs.js(唯一实现)。这里重新导出,保持既有 import 路径可用。
|
|
10
21
|
export { findProjectRoot }
|
|
11
22
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
23
|
+
/**
|
|
24
|
+
* 懒索引的成本结构(9p 代理实测,原生 NTFS 同序只是常数小):
|
|
25
|
+
* `findProjectRoot`(逐层 readdir)18–45ms、`git check-ignore`(起进程)30ms、
|
|
26
|
+
* 整读 + sha256 4ms、save 35ms。前两项**每个文件各付一次**,与文件内容变没变无关。
|
|
27
|
+
*
|
|
28
|
+
* 所以这里做三件事,且都不改变语义:
|
|
29
|
+
* ① 根按目录缓存(5s 上限):一次 flush 里的文件通常同目录,别每个文件走一遍祖先;
|
|
30
|
+
* ② mtime + size 未变 → 不读盘、不问 git(`record.mtimeMs` 由写入侧记下);
|
|
31
|
+
* ③ 一次 flush 只 commit 一次、只起一次 `git check-ignore`。
|
|
32
|
+
* 根缓存只存**由标记推出**的根:`session` 兜底是"这一带还没有标记"的推断,钉 5s 会让
|
|
33
|
+
* `git init` / `npm init` 建出来的项目先落进会话根的 store(真根出现后就是一份重复条目)。
|
|
34
|
+
* 代价只是无标记目录仍按次走一遍祖先(与加缓存之前一致),有标记的项目热路径不受影响。
|
|
35
|
+
* 已有标记的根仍缓存 5s:在它的子目录里 5s 内嵌套新建项目,文件可能先落进父根的 store,
|
|
36
|
+
* 下一次解析就换根、父 store 里的副本留给扫描清理——这是缓存换热路径的必要取舍。
|
|
37
|
+
*/
|
|
38
|
+
const ROOT_CACHE_TTL_MS = 5000
|
|
39
|
+
const ROOT_CACHE_MAX = 4096
|
|
40
|
+
const rootCaches = new WeakMap()
|
|
41
|
+
|
|
42
|
+
function rootCacheFor(config) {
|
|
43
|
+
let cache = rootCaches.get(config)
|
|
44
|
+
if (!cache) {
|
|
45
|
+
cache = new Map()
|
|
46
|
+
rootCaches.set(config, cache)
|
|
47
|
+
}
|
|
48
|
+
return cache
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 清空根缓存(测试 / 诊断;不传 config 表示全清)。 */
|
|
52
|
+
export function clearRootCache(config) {
|
|
53
|
+
if (config) rootCaches.delete(config)
|
|
54
|
+
else rootCaches.clear()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function cachedProjectRoot(config, filePath, watchManager, sessionRoot) {
|
|
58
|
+
const cache = rootCacheFor(config)
|
|
59
|
+
const dir = path.dirname(filePath)
|
|
19
60
|
const extraRoots = watchManager ? [...watchManager.roots.keys()] : []
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
61
|
+
// 会话工作目录 / watch 根集合变了,答案就可能变:都进 key,不做过期以外的失效。
|
|
62
|
+
const key = `${sessionRoot || ''}\u0000${extraRoots.join('\u0001')}\u0000${dir}`
|
|
63
|
+
const hit = cache.get(key)
|
|
64
|
+
const now = Date.now()
|
|
65
|
+
if (hit && now - hit.at < ROOT_CACHE_TTL_MS) return hit.root
|
|
66
|
+
const { root, source } = findProjectRootWithSource(filePath, { extraRoots, sessionRoot, config })
|
|
67
|
+
if (!root) return null
|
|
68
|
+
// 会话根兜底不进缓存:它是"没找到标记"的推断,而"后来才建出标记"正是唯一能让它失效的事件。
|
|
69
|
+
if (source === ROOT_SOURCES.SESSION) return root
|
|
70
|
+
if (cache.size >= ROOT_CACHE_MAX) cache.clear()
|
|
71
|
+
cache.set(key, { root, at: now })
|
|
72
|
+
return root
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 一批"观察到的文件" → 每个 store 一次 commit。
|
|
77
|
+
*
|
|
78
|
+
* @param {object} config 插件配置
|
|
79
|
+
* @param {{filePath: string, sessionRoot: string|null, watchManager?: object|null}[]} items
|
|
80
|
+
* @returns {Promise<Map<string, boolean>>} filePath → 是否真的写入了条目(未变更 / 被排除 / 失败都是 false)
|
|
81
|
+
*/
|
|
82
|
+
export async function indexObservedBatch(config, items, watchManager = null) {
|
|
83
|
+
const results = new Map()
|
|
84
|
+
/** 需要进一步判定(可能真变了)的候选;未变更的文件在这一步就被排除了。 */
|
|
85
|
+
const candidates = []
|
|
86
|
+
|
|
87
|
+
for (const item of items) {
|
|
88
|
+
const { filePath, sessionRoot } = item
|
|
89
|
+
try {
|
|
90
|
+
const kind = fileKind(path.extname(filePath).toLowerCase())
|
|
91
|
+
if (!kind) {
|
|
92
|
+
results.set(filePath, false)
|
|
93
|
+
continue
|
|
94
|
+
}
|
|
95
|
+
// roots.exclude 是子树级否定:被排除的文件连根都不推导,直接不落任何记忆。
|
|
96
|
+
if (excludedEntryForPath(filePath, config)) {
|
|
97
|
+
results.set(filePath, false)
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
const root = cachedProjectRoot(config, filePath, watchManager, sessionRoot)
|
|
101
|
+
if (!root || rootRejection(root, config)) {
|
|
102
|
+
results.set(filePath, false)
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
|
|
106
|
+
const rel = storeKey(relativePath(root, filePath))
|
|
107
|
+
const record = store.fileRecord(rel)
|
|
108
|
+
const st = statSync(filePath)
|
|
109
|
+
// 快路径:mtime + size 都没动 → 连 git 都不用问。这是"重复读同一个文件"的主路径。
|
|
110
|
+
// doc 不走这条捷径:旧 store 的 terms 回填条件要看 entries,交给 planFileIndex 判。
|
|
111
|
+
if (kind === 'code' && record && typeof record.mtimeMs === 'number' && record.mtimeMs === st.mtimeMs && record.size === st.size) {
|
|
112
|
+
results.set(filePath, false)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
candidates.push({ store, root, rel, filePath, kind, record, size: st.size, mtimeMs: st.mtimeMs, gitRel: relativePath(root, filePath) })
|
|
116
|
+
results.set(filePath, false)
|
|
117
|
+
} catch {
|
|
118
|
+
results.set(filePath, false)
|
|
119
|
+
}
|
|
37
120
|
}
|
|
38
|
-
if (plan.key === UNCHANGED || plan.key === OVERSIZE) return false
|
|
39
121
|
|
|
40
|
-
if (
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
122
|
+
if (candidates.length === 0) return results
|
|
123
|
+
|
|
124
|
+
// 按根分组:同一个 flush 里同根的文件共用一次 check-ignore 子进程。
|
|
125
|
+
const byRoot = new Map()
|
|
126
|
+
for (const cand of candidates) {
|
|
127
|
+
let list = byRoot.get(cand.root)
|
|
128
|
+
if (!list) {
|
|
129
|
+
list = []
|
|
130
|
+
byRoot.set(cand.root, list)
|
|
131
|
+
}
|
|
132
|
+
list.push(cand)
|
|
44
133
|
}
|
|
45
134
|
|
|
46
|
-
|
|
47
|
-
|
|
135
|
+
for (const [root, list] of byRoot) {
|
|
136
|
+
// gitignore 只管"**新条目**进不进语料":已经有记录的条目(这次是内容变了要刷新)
|
|
137
|
+
// 不再逐次问 git —— 那是一次进程启动(9p 30ms / 原生 Windows 15–40ms),
|
|
138
|
+
// 而"文件被加进 .gitignore"由 index_repo / watch 的清理路径负责,不该在读路径上判。
|
|
139
|
+
const fresh = list.filter((c) => !c.record)
|
|
140
|
+
let ignored = new Set()
|
|
141
|
+
if (fresh.length > 0) {
|
|
142
|
+
try {
|
|
143
|
+
ignored = isGitIgnoredBatch(root, fresh.map((c) => c.gitRel))
|
|
144
|
+
} catch {
|
|
145
|
+
ignored = new Set()
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const kept = ignored.size === 0 ? list : list.filter((c) => !ignored.has(c.gitRel))
|
|
149
|
+
if (kept.length === 0) continue
|
|
150
|
+
|
|
151
|
+
const store = kept[0].store
|
|
152
|
+
const updates = []
|
|
153
|
+
let refreshed = false
|
|
154
|
+
for (const cand of kept) {
|
|
155
|
+
try {
|
|
156
|
+
const plan = await planFileIndex({
|
|
157
|
+
rel: cand.rel,
|
|
158
|
+
filePath: cand.filePath,
|
|
159
|
+
kind: cand.kind,
|
|
160
|
+
config,
|
|
161
|
+
record: cand.record,
|
|
162
|
+
existingEntries: store.entries[cand.rel],
|
|
163
|
+
size: cand.size,
|
|
164
|
+
mtimeMs: cand.mtimeMs,
|
|
165
|
+
})
|
|
166
|
+
if (plan.key === UNCHANGED) {
|
|
167
|
+
// 内容没变、只有 mtime 变了:把新 mtime 记回去,否则下次还要整读一遍。
|
|
168
|
+
if (typeof plan.mtimeMs === 'number' && store.refreshMtime(cand.rel, plan.mtimeMs)) refreshed = true
|
|
169
|
+
continue
|
|
170
|
+
}
|
|
171
|
+
if (plan.key === OVERSIZE) continue
|
|
172
|
+
updates.push(toFileUpdate(cand.rel, plan, cand.record))
|
|
173
|
+
if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
|
|
174
|
+
results.set(cand.filePath, plan.key !== DROP)
|
|
175
|
+
} catch {
|
|
176
|
+
// 单文件读盘 / 解析失败不影响同批其它文件。
|
|
177
|
+
results.set(cand.filePath, false)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (watchManager && watchManager.addRoot(root)) {
|
|
182
|
+
// 只有真正新登记的根才持久化:addRoot 拒绝的根(不安全/不存在)不再被无条件
|
|
183
|
+
// addWatch 记进 watch.json —— 那样会造出一个每次启动都复活的"僵尸根"。
|
|
184
|
+
store.addWatch(root)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
if (updates.length > 0) commitFileUpdates(store, { updates })
|
|
189
|
+
else if (refreshed) store.commit(() => {})
|
|
190
|
+
} catch (err) {
|
|
191
|
+
console.error(`[dsh-project-memory] lazy index commit failed for ${root}: ${err.message}`)
|
|
192
|
+
}
|
|
48
193
|
}
|
|
49
|
-
|
|
50
|
-
return
|
|
194
|
+
|
|
195
|
+
return results
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function indexFile(ctx, config, filePath, watchManager = null, sessionRoot = null) {
|
|
199
|
+
const results = await indexObservedBatch(config, [{ filePath, sessionRoot }], watchManager)
|
|
200
|
+
return results.get(filePath) === true
|
|
51
201
|
}
|
|
52
202
|
|
|
53
203
|
export function codeFirst(paths) {
|
|
@@ -64,15 +214,15 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
|
|
|
64
214
|
|
|
65
215
|
const flush = async () => {
|
|
66
216
|
timer = null
|
|
67
|
-
const batch = codeFirst([...pending.keys()])
|
|
68
|
-
|
|
217
|
+
const batch = codeFirst([...pending.keys()]).map((filePath) => ({
|
|
218
|
+
filePath,
|
|
219
|
+
sessionRoot: pending.get(filePath) || null,
|
|
220
|
+
}))
|
|
69
221
|
pending.clear()
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
console.error(`[dsh-project-memory] lazy index failed for ${filePath}: ${err.message}`)
|
|
75
|
-
}
|
|
222
|
+
try {
|
|
223
|
+
await indexObservedBatch(config, batch, watchManager)
|
|
224
|
+
} catch (err) {
|
|
225
|
+
console.error(`[dsh-project-memory] lazy index batch failed: ${err.message}`)
|
|
76
226
|
}
|
|
77
227
|
}
|
|
78
228
|
|
|
@@ -97,4 +247,4 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
|
|
|
97
247
|
ctx.effect(() => () => {
|
|
98
248
|
if (timer) clearTimeout(timer)
|
|
99
249
|
})
|
|
100
|
-
}
|
|
250
|
+
}
|
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
|
-
//
|
|
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
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
|
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
|
-
*
|
|
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 "…"`
|
|
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
|
-
|
|
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) {
|
|
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
|
-
|
|
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
|
-
|
|
165
|
-
const
|
|
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
|
-
|
|
182
|
-
if (
|
|
183
|
-
if (
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
391
|
-
//
|
|
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)
|
package/src/project-profile.js
CHANGED
|
@@ -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[],
|
|
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
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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) {
|