@yolk_vat-y/dsh-project-memory 0.6.5 → 0.6.6
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 +88 -0
- package/README.md +17 -4
- package/README.zh-CN.md +16 -4
- package/package.json +6 -4
- package/scripts/bench-edits.mjs +87 -0
- package/skills/project-memory/SKILL.md +72 -0
- package/skills/project-memory/scripts/pm-digest.mjs +138 -0
- package/src/audit.js +6 -0
- package/src/auto-inject.js +61 -15
- package/src/doc-index.js +7 -5
- package/src/doc-pipeline.js +2 -0
- package/src/index.js +8 -0
- package/src/insight-store.js +56 -6
- package/src/ops.js +226 -36
- package/src/readiness.js +60 -9
- package/src/recall.js +5 -1
- package/src/skill.js +84 -0
- package/src/store.js +123 -28
- package/src/util/flush.js +62 -0
- package/src/util/fs.js +227 -34
- package/src/util/persist.js +27 -0
- package/src/util/ru.js +201 -0
- package/src/util/search.js +20 -0
- package/src/vector-index.js +4 -0
- package/src/watch.js +34 -8
package/src/auto-inject.js
CHANGED
|
@@ -161,23 +161,34 @@ export async function createWriteCosine(config, { storeDir = null, items = [] }
|
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
/**
|
|
165
|
+
* 从一份消息列表里取"人说的话"。
|
|
166
|
+
*
|
|
167
|
+
* 只认 `role=user` **且**(`source.kind === 'user'` 或无 source 的老宿主/测试)。
|
|
168
|
+
* 其它 user 角色的消息不是人说的:`agent-message`(子代理报告 relay)、`subagent-settled`、
|
|
169
|
+
* `tool-jobs`(后台任务完成)、`time-context`、`runtime-context` 都会出现在 claimed delta 里。
|
|
170
|
+
* 实测代价:子代理报告里的"发布/渲染"曾被当成用户意图,触发 `intent:release`(1050 字符)
|
|
171
|
+
* 与 `intent:渲染`(1200 字符)两条无关 procedure。
|
|
172
|
+
*
|
|
173
|
+
* `agent/pre-step` 的 `messages` 是 claimed **delta**,不是完整历史,所以会话中段通常
|
|
174
|
+
* 根本没有真人消息 —— 调用方应回退到每会话缓存(见 `InjectionSessions.humanText`)。
|
|
175
|
+
* @param {object[]} messages
|
|
176
|
+
* @returns {string} 人类消息正文;没有则空串
|
|
177
|
+
*/
|
|
164
178
|
export function lastUserText(messages) {
|
|
165
179
|
if (!Array.isArray(messages)) return ''
|
|
166
|
-
let fallback = ''
|
|
167
180
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
168
181
|
const m = messages[i]
|
|
169
182
|
if (!m || m.role !== 'user') continue
|
|
170
183
|
const t = textOf(m)
|
|
171
184
|
if (!t.trim()) continue
|
|
172
|
-
//
|
|
173
|
-
// 上一步的注入块会变成这一步的就绪查询(自激:拿自己注入的内容再检索一遍)。
|
|
174
|
-
if (m.source && m.source.kind === 'user') return t.trim()
|
|
175
|
-
// 本插件注入的块同样是 role=user。无 source 的老宿主下若把它当兜底查询,
|
|
176
|
-
// 就成了"拿自己上一步注入的内容再检索一遍"的自激——正是 isOwnInjection 这道闸要防的。
|
|
185
|
+
// 本插件注入的块也是 role=user:绝不能再拿它当查询(自激)。
|
|
177
186
|
if (isOwnInjection(m.source)) continue
|
|
178
|
-
|
|
187
|
+
const kind = m.source && m.source.kind
|
|
188
|
+
if (kind && kind !== 'user') continue
|
|
189
|
+
return t.trim()
|
|
179
190
|
}
|
|
180
|
-
return
|
|
191
|
+
return ''
|
|
181
192
|
}
|
|
182
193
|
|
|
183
194
|
function fingerprint(text) {
|
|
@@ -495,7 +506,14 @@ export function buildInjection(opts) {
|
|
|
495
506
|
const { query, task, globalStore, cfg } = opts
|
|
496
507
|
const store = opts.store || null
|
|
497
508
|
const tags = opts.projectTagsList || []
|
|
498
|
-
|
|
509
|
+
// 就绪上下文可能**已经构建过**(injectForStep 先构建、再传给这里)。二次构建会把第一遍的
|
|
510
|
+
// `actions` 输出当成"调用方声明的动作"重新信任一遍 —— 散文里的 file-delete 会因此绕过
|
|
511
|
+
// PRE_ACTION_OPS 过滤(实测:"清理一下 README 的措辞"仍注入 1200 字符恢复 procedure)。
|
|
512
|
+
// 结构化标记:带 ops + intentOps 的上下文是构建产物,只补 tags,不再重新归一。
|
|
513
|
+
const built = opts.readiness && Array.isArray(opts.readiness.ops) && Array.isArray(opts.readiness.intentOps)
|
|
514
|
+
const ctx = built
|
|
515
|
+
? { ...opts.readiness, tags: [...new Set([...(opts.readiness.tags || []), ...tags])] }
|
|
516
|
+
: buildReadinessContext({ ...(opts.readiness || { humanText: query || '' }), tags })
|
|
499
517
|
const labels = []
|
|
500
518
|
const reasons = []
|
|
501
519
|
const dropped = []
|
|
@@ -637,6 +655,10 @@ class InjectionSessions {
|
|
|
637
655
|
// 反应窗口:本会话最近观察到的 tool/call(参数里有 git commit / npm publish / 改动的路径)。
|
|
638
656
|
// 宿主没有"工具执行前拦截"钩子,所以这是 pre-step 之外唯一能拿到的动作事实。
|
|
639
657
|
this.observed = cache(() => [])
|
|
658
|
+
// 本会话最后一条**真人**消息。`agent/pre-step` 拿到的是 claimed delta,会话中段通常没有
|
|
659
|
+
// 真人消息,于是"本步的意图"会退化成子代理报告 / job 通知 / 时间快照里的词(实测 386 步里
|
|
660
|
+
// 只有 31 步有真人 query,其余全是通知)。意图必须是会话状态,不是这一步恰好收到的文本。
|
|
661
|
+
this.humanText = cache()
|
|
640
662
|
// 本会话是否已通告"记忆根是推定的"(会话工作目录,无项目标记)。状态声明只发一次。
|
|
641
663
|
this.rootNoticed = cache(() => false)
|
|
642
664
|
this._all = Object.values(this)
|
|
@@ -647,13 +669,29 @@ class InjectionSessions {
|
|
|
647
669
|
}
|
|
648
670
|
}
|
|
649
671
|
|
|
650
|
-
/**
|
|
672
|
+
/**
|
|
673
|
+
* 记录会话里的两类事实:
|
|
674
|
+
* - `user/message`(**真人的**)→ 每会话最后一条人类消息。它是会话状态,不是本步增量;
|
|
675
|
+
* - `tool/call` → 最近 8 次调用,ops.js 从结构化参数解析 op / 写目标 / 主机。
|
|
676
|
+
*
|
|
677
|
+
* 两者都只从**事件**里来,不再把任意工具的参数拼成文本再解析(那会让 subagent 提示词里
|
|
678
|
+
* 的"删除/迁移"变成父会话的动作,实测存活 8 步)。
|
|
679
|
+
*/
|
|
651
680
|
function installCallObserver(ctx, sessions) {
|
|
652
681
|
ctx.on('session/event', (session, event) => {
|
|
653
682
|
try {
|
|
654
|
-
if (!event || event.type !== 'tool/call') return
|
|
655
683
|
const sessionId = session && session.id
|
|
656
|
-
if (!sessionId) return
|
|
684
|
+
if (!sessionId || !event) return
|
|
685
|
+
if (event.type === 'user/message') {
|
|
686
|
+
const data = event.data || {}
|
|
687
|
+
const kind = data.source && data.source.kind
|
|
688
|
+
// 通知 / relay / job / 时间快照都不是人说的;无 source 的老宿主按人话处理(与 lastUserText 同口径)。
|
|
689
|
+
if (kind && kind !== 'user') return
|
|
690
|
+
const text = textOf({ content: data.content })
|
|
691
|
+
if (text.trim()) sessions.humanText.set(sessionId, text.trim())
|
|
692
|
+
return
|
|
693
|
+
}
|
|
694
|
+
if (event.type !== 'tool/call') return
|
|
657
695
|
const data = event.data || {}
|
|
658
696
|
const calls = sessions.observed.ensure(sessionId)
|
|
659
697
|
calls.push({ name: String(data.name || ''), arguments: String(data.arguments || '') })
|
|
@@ -736,7 +774,13 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
736
774
|
const root = resolveProjectMemoryRoot(cwd, config)
|
|
737
775
|
if (!root) return null
|
|
738
776
|
|
|
739
|
-
|
|
777
|
+
// 意图是**会话状态**:先看本步 delta 里有没有新的人类消息,没有则回退到本会话最后一条。
|
|
778
|
+
// `agent/pre-step` 拿到的是 claimed delta(宿主 agent-loop 的 inbox.claim),会话中段通常
|
|
779
|
+
// 只有 tool result / 子代理报告 / job 通知,拿它们当查询就是"这步在做什么"用错了来源。
|
|
780
|
+
const deltaHuman = lastUserText(decision.messages)
|
|
781
|
+
const rememberedHuman = sessions.humanText.peek(sessionId) || ''
|
|
782
|
+
const query = deltaHuman || rememberedHuman
|
|
783
|
+
const querySource = deltaHuman ? 'delta' : rememberedHuman ? 'session' : 'none'
|
|
740
784
|
const memoryRoot = memoryRootFor(root, config.memoryDir)
|
|
741
785
|
const store = new ProjectMemoryStore(memoryRoot).load()
|
|
742
786
|
const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
|
|
@@ -744,12 +788,12 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
744
788
|
const task = boundTaskId ? store.getTask(boundTaskId) : null
|
|
745
789
|
|
|
746
790
|
// 两个窗口合并进同一个就绪上下文:人类消息(先发)+ 已观察动作(反应)。
|
|
747
|
-
// 动作平面(S1
|
|
791
|
+
// 动作平面(S1):**只**从结构化 tool/call 归一(activityFromCalls),不再把全部参数拼成
|
|
792
|
+
// actionText —— 那会把 subagent 提示词 / remember 正文 / 任意脚本里的词当成动作(实测 8 步)。
|
|
748
793
|
const observed = sessions.observed.ensure(sessionId)
|
|
749
794
|
const activity = activityFromCalls(observed)
|
|
750
795
|
const readiness = buildReadinessContext({
|
|
751
796
|
humanText: query || '',
|
|
752
|
-
actionText: observed.map((c) => `${c.name} ${c.arguments}`).join('\n'),
|
|
753
797
|
ops: activity.ops,
|
|
754
798
|
targets: activity.targets,
|
|
755
799
|
hosts: activity.hosts,
|
|
@@ -800,7 +844,9 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
|
|
|
800
844
|
root,
|
|
801
845
|
step: stepNo,
|
|
802
846
|
query: query || '',
|
|
847
|
+
querySource,
|
|
803
848
|
ops: readiness.ops,
|
|
849
|
+
opsIntent: readiness.intentOps,
|
|
804
850
|
writes: readiness.targets,
|
|
805
851
|
reasons: built.reasons,
|
|
806
852
|
candidates: built.candidates,
|
package/src/doc-index.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// 而 summary 为了注入预算被压到 300 字符 —— 一个 3000 字符的 chunk 有九成内容检索不到。
|
|
5
5
|
// 这里把「注入用的短摘要」和「检索用的词项」拆开:summary 仍然短,terms 覆盖整个 chunk。
|
|
6
6
|
//
|
|
7
|
-
// 纯规则、确定性、可重放:tokenizeRaw(拉丁词 + CJK bigram
|
|
8
|
-
import { tokenizeRaw } from './util/search.js'
|
|
7
|
+
// 纯规则、确定性、可重放:tokenizeRaw(拉丁词 + CJK bigram + 俄语词干)→ 去停用词/纯数字 → 词频排序 → 截断。
|
|
8
|
+
import { TOKENIZER_VERSION, tokenizeRaw } from './util/search.js'
|
|
9
9
|
|
|
10
10
|
export const MAX_TERMS = 160
|
|
11
11
|
export const MAX_KEYWORDS = 8
|
|
@@ -62,10 +62,12 @@ export function extractKeywords(title, text, { max = MAX_KEYWORDS } = {}) {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
/**
|
|
65
|
-
* 旧 store 的 doc 条目没有 `terms
|
|
66
|
-
*
|
|
65
|
+
* 旧 store 的 doc 条目没有 `terms`、或 `termsVersion` 落后于当前分词契约:需要一次定向回填,
|
|
66
|
+
* 否则内容哈希未变的文件会被跳过,新的检索覆盖(新增书写系统 / 词干 / 停用词)不会生效。
|
|
67
|
+
* 只对 doc 条目判断,code 条目(符号表)不需要 terms。
|
|
67
68
|
*/
|
|
68
69
|
export function docEntriesNeedBackfill(entries) {
|
|
69
70
|
if (!Array.isArray(entries) || entries.length === 0) return true
|
|
70
|
-
return entries.some((e) => e && e.type === 'doc' &&
|
|
71
|
+
return entries.some((e) => e && e.type === 'doc' &&
|
|
72
|
+
(typeof e.terms !== 'string' || e.termsVersion !== TOKENIZER_VERSION))
|
|
71
73
|
}
|
package/src/doc-pipeline.js
CHANGED
|
@@ -6,6 +6,7 @@ import { summarizeText } from './util/text.js'
|
|
|
6
6
|
import { parsePdf } from './parsers/pdfjs-parser.js'
|
|
7
7
|
import { chunkText } from './chunker.js'
|
|
8
8
|
import { extractKeywords, extractTermText } from './doc-index.js'
|
|
9
|
+
import { TOKENIZER_VERSION } from './util/search.js'
|
|
9
10
|
import { entryIdPrefix } from './util/entry-id.js'
|
|
10
11
|
|
|
11
12
|
export async function extractTextFromFile(filePath, { maxFileSizeMb = 10, maxPdfPages = 1000 } = {}) {
|
|
@@ -49,6 +50,7 @@ export async function buildDocEntries(relPath, filePath, opts = {}) {
|
|
|
49
50
|
summary: summarizeText(chunk.text),
|
|
50
51
|
keywords: extractKeywords(chunk.title, chunk.text),
|
|
51
52
|
terms: extractTermText(chunk.text),
|
|
53
|
+
termsVersion: TOKENIZER_VERSION,
|
|
52
54
|
hash,
|
|
53
55
|
}))
|
|
54
56
|
}
|
package/src/index.js
CHANGED
|
@@ -16,6 +16,8 @@ import { lessonTool } from './tools/lesson-tools.js'
|
|
|
16
16
|
import { installAutoInject } from './auto-inject.js'
|
|
17
17
|
import { rememberRoute } from './llm-route.js'
|
|
18
18
|
import { workflowCommandDefinition } from './commands/workflow.js'
|
|
19
|
+
import { setupSkill } from './skill.js'
|
|
20
|
+
import { flushDirtyStores } from './util/flush.js'
|
|
19
21
|
|
|
20
22
|
export const name = 'dsh-project-memory'
|
|
21
23
|
export const inject = ['llm', 'tools']
|
|
@@ -193,8 +195,14 @@ export function apply(ctx, config) {
|
|
|
193
195
|
setupLazyIndexing(ctx, config, watchManager)
|
|
194
196
|
}
|
|
195
197
|
|
|
198
|
+
// 卸载/退出前把还脏着的 store 同步写一次(后台重试只是兜底,不能当正确性保证)。
|
|
199
|
+
if (typeof ctx.effect === 'function') {
|
|
200
|
+
ctx.effect(() => () => flushDirtyStores({ timeoutMs: 1500 }))
|
|
201
|
+
}
|
|
196
202
|
// TaskBridge:任务实体 + 宿主 todo 同步
|
|
197
203
|
setupTaskbridge(ctx, config)
|
|
204
|
+
// 用法本身也是记忆的一部分:注册成宿主 skill(可选依赖,没有 skills 服务就静默跳过)。
|
|
205
|
+
setupSkill(ctx)
|
|
198
206
|
// 跟踪会话路由(request/header 事件),为无会话上下文的召回期可选 LLM(查询扩展 / 反思)兜底
|
|
199
207
|
ctx.on('session/event', (session, event) => {
|
|
200
208
|
if (event?.type === 'request/header') rememberRoute(session)
|
package/src/insight-store.js
CHANGED
|
@@ -11,6 +11,8 @@ import path from 'node:path'
|
|
|
11
11
|
import os from 'node:os'
|
|
12
12
|
import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
|
|
13
13
|
import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
|
|
14
|
+
import { debugPersistence } from './util/persist.js'
|
|
15
|
+
import { trackDirty, untrackDirty } from './util/flush.js'
|
|
14
16
|
import { backfillDerivedTriggers } from './readiness.js'
|
|
15
17
|
import { vectorText } from './vector-index.js'
|
|
16
18
|
import { tokenize } from './util/search.js'
|
|
@@ -534,7 +536,14 @@ export class GlobalStore {
|
|
|
534
536
|
this._dirty = false
|
|
535
537
|
this._baseIds = new Set()
|
|
536
538
|
this._deletedIds = new Set()
|
|
539
|
+
/** 本进程新建的 id:磁盘缺失时只有它们该补写,否则会把对方删掉的条目复活。 */
|
|
540
|
+
this._createdIds = new Set()
|
|
541
|
+
/** 上一次 commit 是否真的落盘(锁竞争时 false);调用方据此如实回报。 */
|
|
542
|
+
this.lastCommitOk = true
|
|
537
543
|
this._lockWarned = false
|
|
544
|
+
/** 锁竞争后的有限次延迟重试(与 ProjectMemoryStore.save 同一套节拍)。 */
|
|
545
|
+
this._retryTimer = null
|
|
546
|
+
this._retryAttempts = 0
|
|
538
547
|
}
|
|
539
548
|
|
|
540
549
|
load() {
|
|
@@ -563,20 +572,52 @@ export class GlobalStore {
|
|
|
563
572
|
this._dirty = true
|
|
564
573
|
}
|
|
565
574
|
|
|
566
|
-
/**
|
|
567
|
-
|
|
575
|
+
/** 退出/卸载路径的同步兜底(见 util/flush.js)。 */
|
|
576
|
+
flushPending(timeoutMs = 1500) {
|
|
577
|
+
return this.commit(undefined, { timeoutMs })
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** 锁竞争失败后的延迟重试:旧实现完全没有重试,一次竞争就永久丢这次写入。 */
|
|
581
|
+
_scheduleRetry() {
|
|
582
|
+
const delays = [100, 500, 2000, 6000, 12000]
|
|
583
|
+
if (this._retryTimer || this._retryAttempts >= delays.length) return
|
|
584
|
+
const delay = delays[this._retryAttempts++]
|
|
585
|
+
this._retryTimer = setTimeout(() => {
|
|
586
|
+
this._retryTimer = null
|
|
587
|
+
try {
|
|
588
|
+
this.commit(undefined, { timeoutMs: 2000 })
|
|
589
|
+
} catch (err) {
|
|
590
|
+
console.error(`[dsh-project-memory] deferred global save failed: ${err?.message || err}`)
|
|
591
|
+
}
|
|
592
|
+
}, delay)
|
|
593
|
+
this._retryTimer.unref?.()
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* 变更提交:fn(this.doc) 后加锁、合并另一进程的磁盘状态、原子落盘。
|
|
598
|
+
* @param {(doc: object, store: GlobalStore) => any} [fn]
|
|
599
|
+
* @param {{ timeoutMs?: number }} [options] 等锁上限(默认 15s:正确性靠同步等待,不靠重试)
|
|
600
|
+
*/
|
|
601
|
+
commit(fn, options = {}) {
|
|
568
602
|
const res = fn ? fn(this.doc, this) : undefined
|
|
569
603
|
if (!this._dirty && res === undefined) return res
|
|
570
604
|
// 本进程从基线里删掉的 id(removeMemory 直接 splice,没有单独的删除 API)。
|
|
571
605
|
const current = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
|
|
572
606
|
for (const id of this._baseIds) if (!current.has(id)) this._deletedIds.add(id)
|
|
573
|
-
for (const id of current)
|
|
574
|
-
|
|
607
|
+
for (const id of current) {
|
|
608
|
+
this._deletedIds.delete(id)
|
|
609
|
+
if (!this._baseIds.has(id)) this._createdIds.add(id)
|
|
610
|
+
}
|
|
611
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 15000
|
|
612
|
+
const release = acquireDirLock(path.dirname(this.file), { timeoutMs })
|
|
575
613
|
if (!release) {
|
|
614
|
+
this.lastCommitOk = false
|
|
615
|
+
trackDirty(this)
|
|
576
616
|
if (!this._lockWarned) {
|
|
577
617
|
this._lockWarned = true
|
|
578
|
-
|
|
618
|
+
debugPersistence(`[dsh-project-memory] global store ${this.file} is busy (another dsh process is writing); this write is pending.`)
|
|
579
619
|
}
|
|
620
|
+
this._scheduleRetry()
|
|
580
621
|
return res
|
|
581
622
|
}
|
|
582
623
|
try {
|
|
@@ -590,13 +631,22 @@ export class GlobalStore {
|
|
|
590
631
|
continue
|
|
591
632
|
}
|
|
592
633
|
const prev = byId.get(it.id)
|
|
593
|
-
if (!prev
|
|
634
|
+
if (!prev) {
|
|
635
|
+
// 磁盘没有:本进程新建的才补写;否则是对方删了,丢掉内存里的旧副本。
|
|
636
|
+
if (this._createdIds.has(it.id)) byId.set(it.id, it)
|
|
637
|
+
continue
|
|
638
|
+
}
|
|
639
|
+
if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
|
|
594
640
|
}
|
|
595
641
|
for (const id of this._deletedIds) byId.delete(id)
|
|
596
642
|
this.doc.items = [...byId.values()]
|
|
597
643
|
writeJsonAtomic(this.file, this.doc)
|
|
598
644
|
this._dirty = false
|
|
599
645
|
this._baseIds = new Set(this.doc.items.map((it) => it?.id).filter(Boolean))
|
|
646
|
+
this._createdIds.clear()
|
|
647
|
+
this.lastCommitOk = true
|
|
648
|
+
this._retryAttempts = 0
|
|
649
|
+
untrackDirty(this)
|
|
600
650
|
} finally {
|
|
601
651
|
release()
|
|
602
652
|
}
|
package/src/ops.js
CHANGED
|
@@ -72,38 +72,212 @@ const FETCH_TOOLS = new Set(['web_fetch', 'web_search'])
|
|
|
72
72
|
const SHELL_TOOLS = new Set(['bash', 'shell', 'pwsh', 'powershell', 'run', 'exec', 'job_run'])
|
|
73
73
|
const QUERY_TOOLS = new Set(['query_memory', 'recall'])
|
|
74
74
|
|
|
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
|
-
]
|
|
92
|
-
|
|
93
75
|
/**
|
|
94
|
-
*
|
|
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']` 的教训。
|
|
76
|
+
* 会写盘的文件类命令头。**只作用于命令头**,不再对整条命令做无锚点正则。
|
|
100
77
|
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
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 到底在做什么"的唯一可靠位置;参数、路径、引号里的词都是**提及**。
|
|
83
|
+
*/
|
|
84
|
+
const WRITE_HEADS = new Set(['rm', 'rmdir', 'unlink', 'shred', 'mv', 'cp', 'touch', 'tee', 'truncate', 'mkdir'])
|
|
85
|
+
/** 包在真命令前面的词:跳过它们再取命令头。 */
|
|
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'])
|
|
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
|
+
/**
|
|
120
|
+
* 剥掉 heredoc 正文,只留下 opener 那一行。
|
|
121
|
+
* 正文是脚本内容(可能是 python/js),不是 shell 命令——旧实现会把里面的 `mkdir`/`rm` 当动作。
|
|
122
|
+
*/
|
|
123
|
+
function stripHeredocBodies(text) {
|
|
124
|
+
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
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 简单词法切分(去引号、保转义)。只用于取命令头与参数,不追求完整 shell 语义。 */
|
|
128
|
+
function tokenizeWords(segment) {
|
|
129
|
+
const out = []
|
|
130
|
+
let cur = ''
|
|
131
|
+
let quote = null
|
|
132
|
+
for (let i = 0; i < segment.length; i++) {
|
|
133
|
+
const c = segment[i]
|
|
134
|
+
if (quote) {
|
|
135
|
+
if (c === quote) { quote = null; continue }
|
|
136
|
+
if (c === '\\' && quote === '"' && i + 1 < segment.length) { cur += segment[++i]; continue }
|
|
137
|
+
cur += c
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
if (c === "'" || c === '"' || c === '`') { quote = c; continue }
|
|
141
|
+
if (/\s/.test(c)) { if (cur) { out.push(cur); cur = '' } continue }
|
|
142
|
+
if (c === '\\' && i + 1 < segment.length) { cur += segment[++i]; continue }
|
|
143
|
+
cur += c
|
|
144
|
+
}
|
|
145
|
+
if (cur) out.push(cur)
|
|
146
|
+
return out
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 跳过环境变量赋值与 sudo/env/time 之类包装,返回真正的命令头与参数。 */
|
|
150
|
+
function commandHead(tokens) {
|
|
151
|
+
let i = 0
|
|
152
|
+
while (i < tokens.length) {
|
|
153
|
+
const t = tokens[i]
|
|
154
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t) || WRAPPERS.has(t) || t === '(') { i++; continue }
|
|
155
|
+
break
|
|
156
|
+
}
|
|
157
|
+
const raw = tokens[i] || ''
|
|
158
|
+
const head = raw.split('/').pop().toLowerCase()
|
|
159
|
+
let rest = tokens.slice(i + 1)
|
|
160
|
+
if (rest.length && rest[rest.length - 1] === ')') rest = rest.slice(0, -1)
|
|
161
|
+
return { head, rest }
|
|
162
|
+
}
|
|
163
|
+
|
|
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
|
|
166
|
+
|
|
167
|
+
/** 包管理器 / npx 之后的参数里识别动作。只有命令头是 runner 时才走这里。 */
|
|
168
|
+
function runnerOps(args) {
|
|
169
|
+
const ops = []
|
|
170
|
+
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')
|
|
172
|
+
if (args[0] === 'migrate' || args.some((a) => /^db:migrate$/.test(a))) ops.push('migrate')
|
|
173
|
+
return ops
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 命令头 → op。空数组表示"认得这个头,但它不是这些动作"。 */
|
|
177
|
+
function opsOfHead(head, rest) {
|
|
178
|
+
const sub = String(rest[0] || '').toLowerCase()
|
|
179
|
+
switch (head) {
|
|
180
|
+
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))
|
|
184
|
+
return []
|
|
185
|
+
}
|
|
186
|
+
case 'npx': case 'pnpx': case 'bunx':
|
|
187
|
+
return runnerOps(rest)
|
|
188
|
+
case 'node': case 'tsx': case 'deno':
|
|
189
|
+
return rest.some((a) => BENCH_ARG.test(a)) ? ['run-bench'] : []
|
|
190
|
+
case 'git': {
|
|
191
|
+
const gsub = firstSubcommand(rest)
|
|
192
|
+
if (gsub === 'commit' || gsub === 'add') return ['git-commit']
|
|
193
|
+
if (gsub === 'push') return ['git-push']
|
|
194
|
+
if (gsub === 'tag') return ['release']
|
|
195
|
+
if (gsub === 'rm') return ['file-delete']
|
|
196
|
+
if (gsub === 'checkout' || gsub === 'restore' || gsub === 'reset') return ['file-write']
|
|
197
|
+
return []
|
|
198
|
+
}
|
|
199
|
+
case 'rm': case 'rmdir': case 'unlink': case 'shred':
|
|
200
|
+
return ['file-delete']
|
|
201
|
+
case 'kubectl': case 'systemctl': case 'pm2': case 'vercel': case 'netlify':
|
|
202
|
+
return ['deploy']
|
|
203
|
+
case 'docker':
|
|
204
|
+
return sub === 'push' || sub === 'compose' || sub === 'stack' ? ['deploy'] : []
|
|
205
|
+
case 'migrate': case 'alembic':
|
|
206
|
+
return ['migrate']
|
|
207
|
+
case 'prisma':
|
|
208
|
+
return sub === 'migrate' || sub === 'db' ? ['migrate'] : []
|
|
209
|
+
case 'soffice': case 'libreoffice': case 'pandoc': case 'marp': case 'slidev':
|
|
210
|
+
return ['render-doc']
|
|
211
|
+
case 'bench': case 'benchmark':
|
|
212
|
+
return ['run-bench']
|
|
213
|
+
case 'curl': case 'wget':
|
|
214
|
+
return ['fetch-web']
|
|
215
|
+
default:
|
|
216
|
+
return []
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 未加引号的 `>` / `>>` 目标。引号里的 `>` 是正文(`echo "a > b"`),`<<` 不是写。 */
|
|
221
|
+
function redirectTargets(segment) {
|
|
222
|
+
const out = []
|
|
223
|
+
let quote = null
|
|
224
|
+
for (let i = 0; i < segment.length; i++) {
|
|
225
|
+
const c = segment[i]
|
|
226
|
+
if (quote) {
|
|
227
|
+
if (c === '\\' && quote === '"') { i++; continue }
|
|
228
|
+
if (c === quote) quote = null
|
|
229
|
+
continue
|
|
230
|
+
}
|
|
231
|
+
if (c === "'" || c === '"' || c === '`') { quote = c; continue }
|
|
232
|
+
if (c === '\\') { i++; continue }
|
|
233
|
+
if (c !== '>') continue
|
|
234
|
+
if (segment[i + 1] === '>') i++
|
|
235
|
+
let j = i + 1
|
|
236
|
+
while (j < segment.length && /\s/.test(segment[j])) j++
|
|
237
|
+
let tok = ''
|
|
238
|
+
while (j < segment.length && !/[\s;|&)]/.test(segment[j])) { tok += segment[j]; j++ }
|
|
239
|
+
i = Math.max(i, j - 1)
|
|
240
|
+
if (!tok) continue
|
|
241
|
+
if (tok.startsWith('&') || tok === '/dev/null' || tok.startsWith('/dev/stdout') || tok.startsWith('/dev/stderr')) continue
|
|
242
|
+
if (/^\d+$/.test(tok)) continue
|
|
243
|
+
out.push(tok)
|
|
244
|
+
}
|
|
245
|
+
return out
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** 这个段落在写盘吗?写盘命令头、`sed -i`、重定向都算。 */
|
|
249
|
+
function isWriteSegment(head, rest, redirects) {
|
|
250
|
+
if (redirects.length) return true
|
|
251
|
+
if (WRITE_HEADS.has(head)) return true
|
|
252
|
+
if (head === 'sed' && rest.includes('-i')) return true
|
|
253
|
+
if (head === 'git' && String(rest[0] || '').toLowerCase() === 'rm') return true
|
|
254
|
+
return false
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* git 的子命令要跳过全局 flag(`git -C repo commit` 不能被读成 `-C`)。
|
|
259
|
+
* @param {string[]} args
|
|
260
|
+
* @returns {string} 小写子命令;没有则空串
|
|
103
261
|
*/
|
|
104
|
-
|
|
105
|
-
|
|
262
|
+
function firstSubcommand(args) {
|
|
263
|
+
const takesValue = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path'])
|
|
264
|
+
for (let i = 0; i < args.length; i++) {
|
|
265
|
+
const arg = args[i]
|
|
266
|
+
if (arg.startsWith('-')) {
|
|
267
|
+
if (takesValue.has(arg)) i++
|
|
268
|
+
continue
|
|
269
|
+
}
|
|
270
|
+
return arg.toLowerCase()
|
|
271
|
+
}
|
|
272
|
+
return ''
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 合并去重(保持顺序)。 */
|
|
276
|
+
function pushUnique(list, value) {
|
|
277
|
+
if (!list.includes(value)) list.push(value)
|
|
278
|
+
}
|
|
106
279
|
|
|
280
|
+
/** WSL 路径或 Windows 壳的签名:只用于 hosts,不参与动作判定。 */
|
|
107
281
|
const WSL_HINT_RE = /\/mnt\/[a-z]\//i
|
|
108
282
|
|
|
109
283
|
function safeJson(text) {
|
|
@@ -129,21 +303,37 @@ function argsFields(argsText) {
|
|
|
129
303
|
}
|
|
130
304
|
}
|
|
131
305
|
|
|
132
|
-
/** bash
|
|
133
|
-
|
|
134
|
-
const
|
|
306
|
+
/** 内部的递归实现:`bash -c` 会再解析一层。 */
|
|
307
|
+
function classifyCommand(command, depth) {
|
|
308
|
+
const raw = String(command || '')
|
|
135
309
|
const ops = []
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
310
|
+
const targets = []
|
|
311
|
+
for (const segment of unquotedSegments(stripHeredocBodies(raw))) {
|
|
312
|
+
const { head, rest } = commandHead(tokenizeWords(segment))
|
|
313
|
+
if (SHELLS.has(head) && depth < 2) {
|
|
314
|
+
const ci = rest.indexOf('-c')
|
|
315
|
+
if (ci >= 0 && rest[ci + 1]) {
|
|
316
|
+
const inner = classifyCommand(rest.slice(ci + 1).join(' '), depth + 1)
|
|
317
|
+
for (const op of inner.ops) if (op !== 'shell-run') pushUnique(ops, op)
|
|
318
|
+
for (const t of inner.targets) pushUnique(targets, t)
|
|
319
|
+
}
|
|
320
|
+
} else {
|
|
321
|
+
for (const op of opsOfHead(head, rest)) pushUnique(ops, op)
|
|
322
|
+
}
|
|
323
|
+
const redirects = redirectTargets(segment)
|
|
324
|
+
if (isWriteSegment(head, rest, redirects)) {
|
|
325
|
+
for (const t of extractPathTokens(segment)) pushUnique(targets, t)
|
|
139
326
|
}
|
|
140
327
|
}
|
|
141
328
|
if (!ops.length) ops.push('shell-run')
|
|
142
|
-
const
|
|
143
|
-
const hosts = WSL_HINT_RE.test(cmd) || /\b(powershell|pwsh|cmd)\.exe\b/i.test(cmd) ? ['wsl'] : []
|
|
329
|
+
const hosts = WSL_HINT_RE.test(raw) || /\b(powershell|pwsh|cmd)\.exe\b/i.test(raw) ? ['wsl'] : []
|
|
144
330
|
return { ops, targets, hosts }
|
|
145
331
|
}
|
|
146
332
|
|
|
333
|
+
export function classifyShellCommand(command) {
|
|
334
|
+
return classifyCommand(command, 0)
|
|
335
|
+
}
|
|
336
|
+
|
|
147
337
|
/**
|
|
148
338
|
* 一次工具调用 → { ops, targets, hosts }。
|
|
149
339
|
* @param {string} name 工具名
|