dsh-lean-router 2.2.4 → 2.2.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/cordis.patch.yml +29 -2
- package/docs/changelog.en.md +24 -1
- package/docs/changelog.md +24 -1
- package/lib/lean/history-downgrade.js +345 -0
- package/lib/lean/persona-text.js +5 -1
- package/package.json +2 -1
- package/presets/base/frag-lean.patch.yml +17 -1
- package/presets/base/frag-preset.patch.yml +12 -1
- package/test/history-downgrade.test.mjs +379 -0
- package/test/integration-preset.test.mjs +2 -2
- package/test/lean-frag.test.mjs +1 -1
- package/test/lean-modules.test.mjs +23 -0
package/cordis.patch.yml
CHANGED
|
@@ -93,9 +93,13 @@
|
|
|
93
93
|
|
|
94
94
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
95
95
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
96
|
-
6. Output budget.
|
|
96
|
+
6. Output budget. Pipe or redirect long output
|
|
97
97
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
98
98
|
Never print a dump you could grep.
|
|
99
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
100
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
101
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
102
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
99
103
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
100
104
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
101
105
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -282,6 +286,13 @@
|
|
|
282
286
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
283
287
|
config:
|
|
284
288
|
enabled: true
|
|
289
|
+
# 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
|
|
290
|
+
# 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
|
|
291
|
+
# 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
|
|
292
|
+
- id: lean-history-downgrade
|
|
293
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
294
|
+
config:
|
|
295
|
+
enabled: true
|
|
285
296
|
|
|
286
297
|
# ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
|
|
287
298
|
|
|
@@ -463,6 +474,11 @@
|
|
|
463
474
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
464
475
|
config:
|
|
465
476
|
enabled: true
|
|
477
|
+
# 旧工具结果降级(balance 档同挂):见 lean 档同名行说明。
|
|
478
|
+
- id: lean-history-downgrade
|
|
479
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
480
|
+
config:
|
|
481
|
+
enabled: true
|
|
466
482
|
|
|
467
483
|
# ============ 新增行:交付门(加料件)============
|
|
468
484
|
# 默认关闭(enabled: false):它会执行工作区里的验收脚本,要用户显式打开
|
|
@@ -616,9 +632,13 @@
|
|
|
616
632
|
|
|
617
633
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
618
634
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
619
|
-
6. Output budget.
|
|
635
|
+
6. Output budget. Pipe or redirect long output
|
|
620
636
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
621
637
|
Never print a dump you could grep.
|
|
638
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
639
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
640
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
641
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
622
642
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
623
643
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
624
644
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -809,6 +829,13 @@
|
|
|
809
829
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
810
830
|
config:
|
|
811
831
|
enabled: true
|
|
832
|
+
# 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
|
|
833
|
+
# 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
|
|
834
|
+
# 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
|
|
835
|
+
- id: lean-history-downgrade
|
|
836
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
837
|
+
config:
|
|
838
|
+
enabled: true
|
|
812
839
|
|
|
813
840
|
# ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
|
|
814
841
|
|
package/docs/changelog.en.md
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.
|
|
3
|
+
> English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.6).
|
|
4
|
+
|
|
5
|
+
## 2.2.6 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Old tool-result downgrade**: new `lean-history-downgrade` plugin. On `agent/pre-step` (before history is finalized) it inspects the model-visible tool results and, once the number of un-downgraded ones strictly exceeds 32, downgrades them in one batch while always keeping the 6 most recent intact; error results and already-downgraded results are skipped. Rewrites go through `session.append` with `surfaceOp: replace`, so the original events stay in the log and remain replayable, paired with a `compaction/prune` record. The plugin is fail-safe end to end: the hook body is wrapped in try/catch, failures only warn once and never block a step; missing `surface` capabilities are skipped silently; nothing throws at construction; `DSH_LEAN_ROUTER_DOWNGRADE=0` disables it entirely.
|
|
10
|
+
- **Why 32/6**: recomputed against the measured ~155k-token prefix per turn and the cache price gap, 16/6 amortizes to roughly 30k tokens saved per turn (19%) while 32/6 yields about 52k (34%), so 32/6 was chosen. A real Session test downgraded 33 of 39 results (each 12000 chars), saving 391,974 characters in one batch with surface length and order unchanged, and a second run changed nothing.
|
|
11
|
+
|
|
12
|
+
### Tests
|
|
13
|
+
|
|
14
|
+
- 23 new cases (9 pure-function, 14 plugin); the full suite is 263 tests, 262 passing, 0 failing, 1 skipped, with `verify` passing.
|
|
15
|
+
|
|
16
|
+
## 2.2.5 (2026-11-29)
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- **Concrete parallel-call guidance**: the generic "Batch independent calls into one step" line in persona rule 6 proved ineffective in practice — across 22165 assistant messages in the corpus, 91.65% carried a single tool call and only 4.68% carried two or more (10.88% under the lean-router preset). It is replaced by a 306-character block: independent `read`/`grep`/`glob`/`read_image` calls in one message really do overlap; `pwsh`/`edit`/`write` are serialized within a batch but still cost only one round trip; and a masked tool name must never be batched, because it rejects the whole batch and no sibling call runs.
|
|
21
|
+
- **No façade tool added**: tool calls are already a first-class batch primitive in the host (array input, default concurrency cap 10, results written back in model order) and nothing in this repo restricts parallelism, so this release changes guidance text only.
|
|
22
|
+
- persona suffix grows from 3862 to 4130 characters (+268), still inside the 4200-character ceiling.
|
|
23
|
+
|
|
24
|
+
### Tests
|
|
25
|
+
|
|
26
|
+
- 12 new assertions (four read-only tool names, three write-oriented names, masked-name whole-batch rejection, block ≤320 characters, suffix ≤4200); the full suite is 240 tests, 239 passing, 0 failing, 1 skipped.
|
|
4
27
|
|
|
5
28
|
## 2.2.4 (2026-11-29)
|
|
6
29
|
|
package/docs/changelog.md
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
# 变更记录(changelog)
|
|
2
2
|
|
|
3
|
-
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.
|
|
3
|
+
> 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.6)。
|
|
4
|
+
|
|
5
|
+
## 2.2.6 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
- **旧工具结果降级**:新增 `lean-history-downgrade` 插件,在 `agent/pre-step`(历史定稿前)检查模型可见的工具结果——未降级条数严格超过 32 条时批量降级,最近 6 条永远保留原样,错误结果与已降级结果跳过。改写走 `session.append` 的 `surfaceOp: replace`,原始事件保留在日志里可重放,并配套写一条 `compaction/prune`。插件全链路失败安全:钩子体整体 try/catch,异常只 warn 一次、绝不阻断 step;缺少 `surface` 相关能力时静默跳过;构造期不抛任何异常;`DSH_LEAN_ROUTER_DOWNGRADE=0` 可整体关闭。
|
|
10
|
+
- **为什么是 32/6**:按实测前缀约 155k token/轮与缓存价差重算,16/6 摊销后净省约 30k/轮(19%),32/6 约 52k/轮(34%),因此取 32/6。真实 Session 复测:39 条 × 12000 字符 → 选中并降级 33 条,本批省 391,974 字符,surface 长度与顺序不变,二次运行零变更。
|
|
11
|
+
|
|
12
|
+
### 测试
|
|
13
|
+
|
|
14
|
+
- 新增 23 项(纯函数 9 项、插件 14 项);全量 263 项、262 通过、0 失败、1 skip,verify 全 PASS。
|
|
15
|
+
|
|
16
|
+
## 2.2.5 (2026-11-29)
|
|
17
|
+
|
|
18
|
+
### 变更
|
|
19
|
+
|
|
20
|
+
- **并行调用引导具体化**:persona 第 6 条里那句泛泛的 "Batch independent calls into one step" 实测无效——全语料 22165 条 assistant 消息中 91.65% 只携带一个工具调用,带两个及以上的仅 4.68%(lean-router 预设下 10.88%)。现改为一段 306 字符的具体引导:只读工具 `read`/`grep`/`glob`/`read_image` 的独立调用放进同一条消息可以真正重叠执行;`pwsh`/`edit`/`write` 同批虽被串行,但仍只花一次往返;不要把被遮挡的工具名混进同一批,否则整批被拒、兄弟调用都不执行。
|
|
21
|
+
- **不新增 façade 工具**:宿主侧 tool-calls 本身就是批量原语(数组入参、默认并发上限 10、结果按模型顺序写回),仓库侧没有任何代码限制并行,因此这一版只改引导文本。
|
|
22
|
+
- persona suffix 3862 → 4130 字符(+268),仍在 4200 字符上限内。
|
|
23
|
+
|
|
24
|
+
### 测试
|
|
25
|
+
|
|
26
|
+
- 新增 12 条断言(四个只读工具名、三个写向工具名、遮挡整批拒绝、并行块 ≤320 字符、suffix ≤4200);全量 240 项、239 通过、0 失败、1 skip。
|
|
4
27
|
|
|
5
28
|
## 2.2.4 (2026-11-29)
|
|
6
29
|
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
// dsh-lean-router · lib/lean/history-downgrade.js —— 加料件 · 旧工具结果降级(改写「模型可见的历史」)
|
|
2
|
+
//
|
|
3
|
+
// 目标:会话变长后,早期工具结果(几万字符的读文件/命令输出)仍在 prefix 里,每轮都要为它们付
|
|
4
|
+
// prompt token;把它们换成一行占位符,模型需要时可以重新读/重跑。批与批之间前缀保持稳定:
|
|
5
|
+
// 只有「未降级的工具结果 > DOWNGRADE_TRIGGER」才动一次,且永远保留最近 DOWNGRADE_KEEP 条原样。
|
|
6
|
+
//
|
|
7
|
+
// 机制(照抄宿主 @deepseek-ai/dsh-compaction-tool-result-pruner 的写法,证据:
|
|
8
|
+
// .agent-master/pruner-index.md L137-191 pruneSession):
|
|
9
|
+
// 1. agent/pre-step 是 waterfall(dsh-agent/lib/types/runtime-types.d.ts L333-340):
|
|
10
|
+
// `(payload: { agent, messages, turn, step, signal, modelSelection }, next) => Promise<PreStepDecision>`,
|
|
11
|
+
// 每个 step 一次、历史定稿前;所以在这里改写 surface 会进入本次请求的 model-visible 历史。
|
|
12
|
+
// 2. 先 `session.append('compaction/prune', { shadowedRange, shadowedSeqs, shadowedTokenCount })`
|
|
13
|
+
// 记影子价格(事件 data 形状见宿主 SessionEventMap:
|
|
14
|
+
// `{ shadowedRange: { start, end }, shadowedSeqs: SessionSeq[], shadowedTokenCount: number }`;
|
|
15
|
+
// 本仓抽取稿 pruner-index.md L159-166 同形)。
|
|
16
|
+
// 3. 再 `session.append('tool/result', { ...event.data, message: 裁剪后的 message },
|
|
17
|
+
// { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] })`
|
|
18
|
+
// 覆盖旧节点。原事件留在 append-only 日志里,replacement 通过 sourceEventSeqs 引用它,可重放。
|
|
19
|
+
// 4. tool/result 的 data 形状:`{ turn, step, message, error?, meta? }`
|
|
20
|
+
// (dsh-session/lib/types/types.d.ts L382-396);append 校验只要求 data 是对象,且
|
|
21
|
+
// `error` 存在时 `message.isError === true`(dsh-session/lib/index.js L272-277)——
|
|
22
|
+
// 本模块跳过 isError 结果,因此不会触碰这条约束。
|
|
23
|
+
//
|
|
24
|
+
// 失败安全(本文件最重要的一条):钩子体全部包在 try/catch 里,异常只 warn 一次、绝不 throw、
|
|
25
|
+
// 绝不 return 会阻断 step 的东西;读不到 session.surface / eventAt / deriveEventMessage / append
|
|
26
|
+
// 任何一个依赖就静默跳过(feature-detect),不改任何行为。
|
|
27
|
+
//
|
|
28
|
+
// 不静态 import 宿主包(仓库约定,见 lib/lean/delivery-gate.js L8-10):
|
|
29
|
+
// - message 不需要 freezeMessage(它只是 deepFreeze(structuredClone(x)),dsh-llm/lib/index.js L30-32),
|
|
30
|
+
// session.append 自己会快照/冻结事件 data;这里用普通对象重建 message 即可。
|
|
31
|
+
// - tokenMeter 通过 `ctx.reflect.get('tokenMeter')` 可选读取;未提供时返回 undefined 而不是抛
|
|
32
|
+
// (cordis/lib/index.js L1347-1356),拿不到就跳过 compaction/prune 记录(不写假 token 数),
|
|
33
|
+
// 但替换照做 —— 模型可见历史变短这件事不依赖计价事件。
|
|
34
|
+
|
|
35
|
+
/** 未降级的工具结果超过这个条数才触发一次批量降级(严格大于)。 */
|
|
36
|
+
export const DOWNGRADE_TRIGGER = 32;
|
|
37
|
+
|
|
38
|
+
/** 无论阈值如何,最近这么多条工具结果永远保持原样(给模型留当前工作上下文)。 */
|
|
39
|
+
export const DOWNGRADE_KEEP = 6;
|
|
40
|
+
|
|
41
|
+
/** 已降级占位符的识别标记;占位符文本一定包含它,用于批与批之间跳过已处理的节点。 */
|
|
42
|
+
export const DOWNGRADE_MARK = '[... tool result downgraded to save context';
|
|
43
|
+
|
|
44
|
+
/** 插件名(preset 行 id / name 同源)。 */
|
|
45
|
+
export const name = 'lean-history-downgrade';
|
|
46
|
+
|
|
47
|
+
const TAG = '[lean-history-downgrade]';
|
|
48
|
+
|
|
49
|
+
/** 环境变量关闭开关:=0 时不注册钩子。 */
|
|
50
|
+
const ENV_OFF = 'DSH_LEAN_ROUTER_DOWNGRADE';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 模块级 warn 去重:钩子每 step 都会跑,同一个故障不该每 step 刷一行日志。
|
|
54
|
+
* 测试可用 `__internals.resetWarning()` 复位。
|
|
55
|
+
*/
|
|
56
|
+
let warnedOnce = false;
|
|
57
|
+
|
|
58
|
+
function describeError(error) {
|
|
59
|
+
if (error && typeof error.message === 'string') return error.message;
|
|
60
|
+
return String(error);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function warnOnce(ctx, message) {
|
|
64
|
+
if (warnedOnce) return;
|
|
65
|
+
warnedOnce = true;
|
|
66
|
+
const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined;
|
|
67
|
+
if (!logger || typeof logger.warn !== 'function') return;
|
|
68
|
+
try {
|
|
69
|
+
logger.warn(TAG + ' ' + message);
|
|
70
|
+
} catch {
|
|
71
|
+
// A logger must never break the step.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 按 Unicode 码点计数(与宿主 pruner 同口径,不拆代理对)。 */
|
|
76
|
+
function codePointLength(text) {
|
|
77
|
+
return Array.from(text).length;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 占位符文本:一行,说明省掉了多少字符、以及怎么拿回原文。
|
|
82
|
+
* @param elidedChars - 被省掉的字符数(码点)。
|
|
83
|
+
* @returns 单行占位符。
|
|
84
|
+
*/
|
|
85
|
+
export function downgradeText(elidedChars) {
|
|
86
|
+
const chars = Number.isFinite(elidedChars) && elidedChars > 0 ? Math.floor(elidedChars) : 0;
|
|
87
|
+
return '[... tool result downgraded to save context: ' + chars
|
|
88
|
+
+ ' chars elided; re-run the tool or read the relevant slice if needed ...]';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* tool-result message 的文本字符总量(非 text 块不计;与宿主 measureContent 同口径)。
|
|
93
|
+
* @param message - { content: ContentBlock[] } 形态的消息。
|
|
94
|
+
* @returns 文本码点数。
|
|
95
|
+
*/
|
|
96
|
+
export function messageChars(message) {
|
|
97
|
+
if (!message || !Array.isArray(message.content)) return 0;
|
|
98
|
+
let chars = 0;
|
|
99
|
+
for (const block of message.content) {
|
|
100
|
+
if (block && block.type === 'text' && typeof block.text === 'string') {
|
|
101
|
+
chars += codePointLength(block.text);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return chars;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 该 message 是否已经是降级占位符。
|
|
109
|
+
* @param message - { content: ContentBlock[] } 形态的消息。
|
|
110
|
+
* @returns true 表示已经降级过(跳过,避免重复改写)。
|
|
111
|
+
*/
|
|
112
|
+
export function isDowngradedMessage(message) {
|
|
113
|
+
if (!message || !Array.isArray(message.content)) return false;
|
|
114
|
+
for (const block of message.content) {
|
|
115
|
+
if (block && block.type === 'text' && typeof block.text === 'string'
|
|
116
|
+
&& block.text.includes(DOWNGRADE_MARK)) {
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 选项归一化:非法值静默回落到默认(纯函数,构造期绝不抛)。 */
|
|
124
|
+
function nonNegativeInt(value, fallback) {
|
|
125
|
+
return Number.isInteger(value) && value >= 0 ? value : fallback;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isResultLike(result) {
|
|
129
|
+
return !!result && typeof result === 'object' && Number.isSafeInteger(result.seq) && result.seq >= 0;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 选出本次要降级的工具结果 seq(纯函数,可脱离宿主单测)。
|
|
134
|
+
*
|
|
135
|
+
* 规则(顺序固定):
|
|
136
|
+
* 1. 按 seq 升序;最后 keep 条(默认 6)永不降级 —— 这是「最近工作上下文」窗口。
|
|
137
|
+
* 2. keep 窗口之外,跳过 isError === true(错误结果保持原样)与 alreadyDowngraded === true
|
|
138
|
+
* (已降级的 surface 上已经变短,再动就是无谓改写)。
|
|
139
|
+
* 3. 剩下的「可降级条数」严格大于 trigger(默认 32)才触发;否则返回空数组。
|
|
140
|
+
* 4. 触发时返回窗口外全部尚未降级的 seq —— 一次批量降完,下一批要重新攒够阈值,
|
|
141
|
+
* 批与批之间前缀不变。
|
|
142
|
+
*
|
|
143
|
+
* @param results - [{ seq, chars?, isError?, alreadyDowngraded? }],顺序任意。
|
|
144
|
+
* @param options - { trigger?, keep? } 覆盖默认阈值/保留条数。
|
|
145
|
+
* @returns 按 seq 升序的待降级 seq 数组;不触发时为空数组。
|
|
146
|
+
*/
|
|
147
|
+
export function selectDowngradeTargets(results, options) {
|
|
148
|
+
const list = Array.isArray(results) ? results.filter(isResultLike) : [];
|
|
149
|
+
if (list.length === 0) return [];
|
|
150
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
151
|
+
const trigger = nonNegativeInt(opts.trigger, DOWNGRADE_TRIGGER);
|
|
152
|
+
const keep = nonNegativeInt(opts.keep, DOWNGRADE_KEEP);
|
|
153
|
+
const sorted = [...list].sort((a, b) => a.seq - b.seq);
|
|
154
|
+
const keepStart = Math.max(0, sorted.length - keep);
|
|
155
|
+
const targets = [];
|
|
156
|
+
for (let index = 0; index < sorted.length; index++) {
|
|
157
|
+
if (index >= keepStart) break;
|
|
158
|
+
const result = sorted[index];
|
|
159
|
+
if (result.isError === true) continue;
|
|
160
|
+
if (result.alreadyDowngraded === true) continue;
|
|
161
|
+
targets.push(result.seq);
|
|
162
|
+
}
|
|
163
|
+
return targets.length > trigger ? targets : [];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 依赖探测:改历史需要的四件套齐了才动,缺任何一件静默跳过。
|
|
168
|
+
* @param session - payload.agent.session。
|
|
169
|
+
* @returns true 表示可以安全改写。
|
|
170
|
+
*/
|
|
171
|
+
export function isSupportedSession(session) {
|
|
172
|
+
if (!session || typeof session !== 'object') return false;
|
|
173
|
+
const surface = session.surface;
|
|
174
|
+
return !!surface && Array.isArray(surface.nodes)
|
|
175
|
+
&& typeof session.eventAt === 'function'
|
|
176
|
+
&& typeof session.append === 'function'
|
|
177
|
+
&& typeof session.deriveEventMessage === 'function';
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 从当前 surface 收集工具结果(按 model-visible 顺序),只读。
|
|
182
|
+
* @param session - 已通过 isSupportedSession 的会话。
|
|
183
|
+
* @returns [{ seq, chars, isError, alreadyDowngraded, event, message }]
|
|
184
|
+
*/
|
|
185
|
+
export function collectToolResults(session) {
|
|
186
|
+
const results = [];
|
|
187
|
+
for (const seq of [...session.surface.nodes]) {
|
|
188
|
+
const event = session.eventAt(seq);
|
|
189
|
+
if (!event || event.type !== 'tool/result') continue;
|
|
190
|
+
const message = session.deriveEventMessage(event);
|
|
191
|
+
if (!message) continue;
|
|
192
|
+
results.push({
|
|
193
|
+
seq,
|
|
194
|
+
chars: messageChars(message),
|
|
195
|
+
isError: message.isError === true,
|
|
196
|
+
alreadyDowngraded: isDowngradedMessage(message),
|
|
197
|
+
event,
|
|
198
|
+
message,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return results;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 可选读取 tokenMeter:cordis 的 reflect.get 在服务未提供时返回 undefined(不抛),
|
|
206
|
+
* 因此不需要 inject 声明,也不会因为缺服务让插件不加载。
|
|
207
|
+
*/
|
|
208
|
+
function readTokenMeter(ctx) {
|
|
209
|
+
try {
|
|
210
|
+
const reflect = ctx && typeof ctx === 'object' ? ctx.reflect : undefined;
|
|
211
|
+
if (!reflect || typeof reflect.get !== 'function') return null;
|
|
212
|
+
const meter = reflect.get('tokenMeter');
|
|
213
|
+
return meter && typeof meter.estimateMessage === 'function' ? meter : null;
|
|
214
|
+
} catch {
|
|
215
|
+
return null;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 影子价格:拿不到 token 计量就返回 null(宁可不记,也不写假数字)。 */
|
|
220
|
+
function estimateShadowTokens(meter, message) {
|
|
221
|
+
if (!meter) return null;
|
|
222
|
+
try {
|
|
223
|
+
const value = meter.estimateMessage(message);
|
|
224
|
+
return Number.isFinite(value) && value >= 0 ? Math.round(value) : null;
|
|
225
|
+
} catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* 执行一次降级 pass(每 step 最多一批)。
|
|
232
|
+
*
|
|
233
|
+
* 只在上面的阈值满足时写日志;每个目标先记 compaction/prune 影子价格,再 append 替换事件。
|
|
234
|
+
* @param session - payload.agent.session。
|
|
235
|
+
* @param ctx - 插件上下文(可选 logger / reflect)。
|
|
236
|
+
* @param options - { trigger?, keep? }。
|
|
237
|
+
* @returns null(依赖不全,静默跳过)或 { targets, downgraded, charsRemoved }。
|
|
238
|
+
*/
|
|
239
|
+
export function downgradeSession(session, ctx, options) {
|
|
240
|
+
if (!isSupportedSession(session)) return null;
|
|
241
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
242
|
+
const results = collectToolResults(session);
|
|
243
|
+
const targets = selectDowngradeTargets(results, opts);
|
|
244
|
+
const report = { targets, downgraded: [], charsRemoved: 0 };
|
|
245
|
+
if (targets.length === 0) return report;
|
|
246
|
+
const bySeq = new Map(results.map((result) => [result.seq, result]));
|
|
247
|
+
const meter = readTokenMeter(ctx);
|
|
248
|
+
for (const seq of targets) {
|
|
249
|
+
const result = bySeq.get(seq);
|
|
250
|
+
if (!result || !result.event) continue;
|
|
251
|
+
const elided = result.chars;
|
|
252
|
+
const placeholder = downgradeText(elided);
|
|
253
|
+
const placeholderChars = codePointLength(placeholder);
|
|
254
|
+
// 占位符不比方短就毫无收益,跳过(不制造「降级后更长」的历史)。
|
|
255
|
+
if (elided <= 0 || placeholderChars >= elided) continue;
|
|
256
|
+
const message = { ...result.message, content: [{ type: 'text', text: placeholder }] };
|
|
257
|
+
const shadowTokens = estimateShadowTokens(meter, result.message);
|
|
258
|
+
if (shadowTokens !== null) {
|
|
259
|
+
session.append('compaction/prune', {
|
|
260
|
+
shadowedRange: { start: seq, end: seq },
|
|
261
|
+
shadowedSeqs: [seq],
|
|
262
|
+
shadowedTokenCount: shadowTokens,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
session.append('tool/result', { ...result.event.data, message }, {
|
|
266
|
+
surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq },
|
|
267
|
+
sourceEventSeqs: [seq],
|
|
268
|
+
});
|
|
269
|
+
report.downgraded.push(seq);
|
|
270
|
+
report.charsRemoved += elided - placeholderChars;
|
|
271
|
+
}
|
|
272
|
+
return report;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 插件配置归一化:只认 `{ enabled?, trigger?, keep? }`;非法值回落默认,绝不抛。
|
|
277
|
+
*/
|
|
278
|
+
export function resolveConfig(config) {
|
|
279
|
+
const source = config && typeof config === 'object' ? config : {};
|
|
280
|
+
return {
|
|
281
|
+
enabled: source.enabled !== false,
|
|
282
|
+
trigger: nonNegativeInt(source.trigger, DOWNGRADE_TRIGGER),
|
|
283
|
+
keep: nonNegativeInt(source.keep, DOWNGRADE_KEEP),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* waterfall 体:任何异常都只 warn 一次,然后照常 `next()`,绝不阻断 step。
|
|
289
|
+
* @param ctx - 插件上下文(可选 logger / reflect)。
|
|
290
|
+
* @param payload - agent/pre-step payload。
|
|
291
|
+
* @param next - waterfall 的下一段(宿主提供)。
|
|
292
|
+
* @param options - { trigger?, keep? },来自 apply 已归一化的配置。
|
|
293
|
+
* @returns next() 的 PreStepDecision;next 不可调用时返回 undefined(不改决策)。
|
|
294
|
+
*/
|
|
295
|
+
export async function handlePreStep(ctx, payload, next, options) {
|
|
296
|
+
try {
|
|
297
|
+
const agent = payload && typeof payload === 'object' ? payload.agent : undefined;
|
|
298
|
+
const session = agent && typeof agent === 'object' ? agent.session : undefined;
|
|
299
|
+
if (session) downgradeSession(session, ctx, options);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
warnOnce(ctx, 'history downgrade skipped this step: ' + describeError(error));
|
|
302
|
+
}
|
|
303
|
+
if (typeof next === 'function') return next();
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 插件入口(形态与 lib/lean/usage-ledger.js 的 apply 一致):
|
|
309
|
+
* DSH_LEAN_ROUTER_DOWNGRADE=0 或 config.enabled === false 时不注册;构造期不抛任何异常。
|
|
310
|
+
*/
|
|
311
|
+
export function apply(ctx, config) {
|
|
312
|
+
const resolved = resolveConfig(config);
|
|
313
|
+
if (!resolved.enabled) return;
|
|
314
|
+
// 环境变量读取也防御:非 Node 宿主(无 process)不得在构造期抛。
|
|
315
|
+
const env = typeof process === 'object' && process ? process.env : undefined;
|
|
316
|
+
if (env && env[ENV_OFF] === '0') return;
|
|
317
|
+
const context = ctx && typeof ctx === 'object' ? ctx : {};
|
|
318
|
+
if (typeof context.on !== 'function') {
|
|
319
|
+
warnOnce(context, 'ctx.on is unavailable; ' + name + ' not registered');
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
// 配置闭包进 handler,绝不往 ctx 上写字段(会污染宿主上下文,也可能破坏服务代理)。
|
|
323
|
+
const handlerConfig = { trigger: resolved.trigger, keep: resolved.keep };
|
|
324
|
+
try {
|
|
325
|
+
context.on('agent/pre-step', (payload, next) => handlePreStep(context, payload, next, handlerConfig));
|
|
326
|
+
} catch (error) {
|
|
327
|
+
warnOnce(context, 'could not register agent/pre-step: ' + describeError(error));
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 默认导出(插件行兼容形态,与命名导出同体)。 */
|
|
332
|
+
export default { name, apply };
|
|
333
|
+
|
|
334
|
+
/** 测试与集成内用的内部实现出口。 */
|
|
335
|
+
export const __internals = {
|
|
336
|
+
TAG,
|
|
337
|
+
ENV_OFF,
|
|
338
|
+
probeTokenMeter: readTokenMeter,
|
|
339
|
+
resetWarning() {
|
|
340
|
+
warnedOnce = false;
|
|
341
|
+
},
|
|
342
|
+
isWarningLatched() {
|
|
343
|
+
return warnedOnce;
|
|
344
|
+
},
|
|
345
|
+
};
|
package/lib/lean/persona-text.js
CHANGED
|
@@ -56,9 +56,13 @@ export const LEAN_PERSONA_SUFFIX = [
|
|
|
56
56
|
'',
|
|
57
57
|
'5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file',
|
|
58
58
|
' (no cat/head/tail/sed -n/find/ls -R). Piping a command\'s own output through head is fine.',
|
|
59
|
-
'6. Output budget.
|
|
59
|
+
'6. Output budget. Pipe or redirect long output',
|
|
60
60
|
' (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\\out.log in cmd, /tmp/out.log on POSIX).',
|
|
61
61
|
' Never print a dump you could grep.',
|
|
62
|
+
'PARALLEL CALLS (tool calls sent together run concurrently)',
|
|
63
|
+
' read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.',
|
|
64
|
+
' pwsh/edit/write run serially, yet batched they still cost one round trip.',
|
|
65
|
+
' Never batch a masked tool name: it rejects the whole batch, siblings never run.',
|
|
62
66
|
'7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE',
|
|
63
67
|
' run_code program; a single call may still go through a one-line program so its noise stays out',
|
|
64
68
|
' of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-lean-router",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.6",
|
|
4
4
|
"description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"./router": "./lib/router.js",
|
|
11
11
|
"./toolface": "./lib/toolface/index.js",
|
|
12
12
|
"./lean/delivery-gate": "./lib/lean/delivery-gate.js",
|
|
13
|
+
"./lean/history-downgrade": "./lib/lean/history-downgrade.js",
|
|
13
14
|
"./lean/tool-concurrency": "./lib/lean/tool-concurrency.js",
|
|
14
15
|
"./lean/usage-ledger": "./lib/lean/usage-ledger.js",
|
|
15
16
|
"./token-ledger": "./lib/token-ledger/index.js",
|
|
@@ -46,9 +46,13 @@
|
|
|
46
46
|
|
|
47
47
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
48
48
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
49
|
-
6. Output budget.
|
|
49
|
+
6. Output budget. Pipe or redirect long output
|
|
50
50
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
51
51
|
Never print a dump you could grep.
|
|
52
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
53
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
54
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
55
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
52
56
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
53
57
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
54
58
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -235,6 +239,13 @@
|
|
|
235
239
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
236
240
|
config:
|
|
237
241
|
enabled: true
|
|
242
|
+
# 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
|
|
243
|
+
# 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
|
|
244
|
+
# 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
|
|
245
|
+
- id: lean-history-downgrade
|
|
246
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
247
|
+
config:
|
|
248
|
+
enabled: true
|
|
238
249
|
|
|
239
250
|
# ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
|
|
240
251
|
|
|
@@ -416,6 +427,11 @@
|
|
|
416
427
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
417
428
|
config:
|
|
418
429
|
enabled: true
|
|
430
|
+
# 旧工具结果降级(balance 档同挂):见 lean 档同名行说明。
|
|
431
|
+
- id: lean-history-downgrade
|
|
432
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
433
|
+
config:
|
|
434
|
+
enabled: true
|
|
419
435
|
|
|
420
436
|
# ============ 新增行:交付门(加料件)============
|
|
421
437
|
# 默认关闭(enabled: false):它会执行工作区里的验收脚本,要用户显式打开
|
|
@@ -36,9 +36,13 @@
|
|
|
36
36
|
|
|
37
37
|
5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
|
|
38
38
|
(no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
|
|
39
|
-
6. Output budget.
|
|
39
|
+
6. Output budget. Pipe or redirect long output
|
|
40
40
|
(| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
|
|
41
41
|
Never print a dump you could grep.
|
|
42
|
+
PARALLEL CALLS (tool calls sent together run concurrently)
|
|
43
|
+
read-only read/grep/glob/read_image: independent calls in ONE message overlap truly.
|
|
44
|
+
pwsh/edit/write run serially, yet batched they still cost one round trip.
|
|
45
|
+
Never batch a masked tool name: it rejects the whole batch, siblings never run.
|
|
42
46
|
7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
|
|
43
47
|
run_code program; a single call may still go through a one-line program so its noise stays out
|
|
44
48
|
of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
|
|
@@ -229,6 +233,13 @@
|
|
|
229
233
|
name: 'dsh-lean-router/lean/usage-ledger'
|
|
230
234
|
config:
|
|
231
235
|
enabled: true
|
|
236
|
+
# 旧工具结果降级:agent/pre-step(waterfall,历史定稿前)把未降级 tool/result 攒到 >32 条时
|
|
237
|
+
# 批量换成一行占位符,最近 6 条永远保留原样;DSH_LEAN_ROUTER_DOWNGRADE=0 可关。
|
|
238
|
+
# 失败安全:钩子体全包 try/catch,异常只 warn 一次、绝不阻断 step;实现 = lib/lean/history-downgrade.js。
|
|
239
|
+
- id: lean-history-downgrade
|
|
240
|
+
name: 'dsh-lean-router/lean/history-downgrade'
|
|
241
|
+
config:
|
|
242
|
+
enabled: true
|
|
232
243
|
|
|
233
244
|
# ============ 新增行:preset-lean-router-balance(balance 档 3 条;上游双预设形态,flash-lean-ptc-v3-balance 同构)============
|
|
234
245
|
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// test/history-downgrade.test.mjs —— 旧工具结果降级的纯函数判据 + 插件失败安全回归。
|
|
2
|
+
//
|
|
3
|
+
// 分两层:
|
|
4
|
+
// 1. 纯函数(selectDowngradeTargets / downgradeText / messageChars / isDowngradedMessage):
|
|
5
|
+
// 不依赖宿主,直接断言阈值、保留窗口、error 与已降级跳过、参数覆盖。
|
|
6
|
+
// 2. 插件(apply / handlePreStep):假 ctx(on 收集 handler、logger.warn 打点)与假 session
|
|
7
|
+
// (surface/eventAt/deriveEventMessage/append 四件套)验证:
|
|
8
|
+
// 正常路径写 compaction/prune + tool/result 替换;append 抛异常时钩子不抛、只 warn 一次;
|
|
9
|
+
// 缺 surface/eventAt/deriveEventMessage/append 任何一件时静默跳过。
|
|
10
|
+
import test from 'node:test';
|
|
11
|
+
import assert from 'node:assert/strict';
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
DOWNGRADE_KEEP,
|
|
15
|
+
DOWNGRADE_MARK,
|
|
16
|
+
DOWNGRADE_TRIGGER,
|
|
17
|
+
__internals,
|
|
18
|
+
apply,
|
|
19
|
+
collectToolResults,
|
|
20
|
+
downgradeSession,
|
|
21
|
+
downgradeText,
|
|
22
|
+
handlePreStep,
|
|
23
|
+
isDowngradedMessage,
|
|
24
|
+
isSupportedSession,
|
|
25
|
+
messageChars,
|
|
26
|
+
name,
|
|
27
|
+
resolveConfig,
|
|
28
|
+
selectDowngradeTargets,
|
|
29
|
+
} from '../lib/lean/history-downgrade.js';
|
|
30
|
+
|
|
31
|
+
/** 构造 n 条形状合法的工具结果(默认全部可降级)。 */
|
|
32
|
+
function makeResults(n) {
|
|
33
|
+
return Array.from({ length: n }, (_, i) => ({
|
|
34
|
+
seq: i + 1,
|
|
35
|
+
chars: 1000,
|
|
36
|
+
isError: false,
|
|
37
|
+
alreadyDowngraded: false,
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 假 ctx:on 收集 handler、logger.warn 落数组、reflect 可选提供 tokenMeter。 */
|
|
42
|
+
function makeCtx({ withMeter = true } = {}) {
|
|
43
|
+
const handlers = new Map();
|
|
44
|
+
const warnings = [];
|
|
45
|
+
const ctx = {
|
|
46
|
+
logger: {
|
|
47
|
+
warn(message) {
|
|
48
|
+
warnings.push(message);
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
on(type, handler) {
|
|
52
|
+
handlers.set(type, handler);
|
|
53
|
+
return () => handlers.delete(type);
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
if (withMeter) {
|
|
57
|
+
ctx.reflect = {
|
|
58
|
+
get(service) {
|
|
59
|
+
if (service !== 'tokenMeter') return undefined;
|
|
60
|
+
return { estimateMessage: () => 123 };
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return { ctx, handlers, warnings };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 假 session:surface 节点 = 1..count,每条 tool/result 带 chars 个 'x'。 */
|
|
68
|
+
function makeSession({ count = 40, chars = 1000, appendThrows = false, withSurface = true } = {}) {
|
|
69
|
+
const events = new Map();
|
|
70
|
+
for (let seq = 1; seq <= count; seq++) {
|
|
71
|
+
events.set(seq, {
|
|
72
|
+
type: 'tool/result',
|
|
73
|
+
seq,
|
|
74
|
+
data: {
|
|
75
|
+
turn: 1,
|
|
76
|
+
step: 1,
|
|
77
|
+
message: {
|
|
78
|
+
id: 'm' + seq,
|
|
79
|
+
role: 'tool',
|
|
80
|
+
toolCallId: 'c' + seq,
|
|
81
|
+
source: { kind: 'tool', callId: 'c' + seq },
|
|
82
|
+
content: [{ type: 'text', text: 'x'.repeat(chars) }],
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const appends = [];
|
|
88
|
+
const session = {
|
|
89
|
+
surface: withSurface ? { nodes: [...events.keys()], replaceGeneration: 0, contentGeneration: 0 } : undefined,
|
|
90
|
+
eventAt(seq) {
|
|
91
|
+
return events.get(seq);
|
|
92
|
+
},
|
|
93
|
+
deriveEventMessage(event) {
|
|
94
|
+
return event ? event.data.message : null;
|
|
95
|
+
},
|
|
96
|
+
append(type, data, opts) {
|
|
97
|
+
if (appendThrows) throw new Error('session closed');
|
|
98
|
+
appends.push({ type, data, opts });
|
|
99
|
+
return { type, data, seq: 1000 + appends.length };
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
return { session, appends, events };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 改写某条结果的消息(用于构造 isError / 已降级样本)。 */
|
|
106
|
+
function patchMessage(events, seq, patch) {
|
|
107
|
+
const event = events.get(seq);
|
|
108
|
+
event.data = { ...event.data, message: { ...event.data.message, ...patch } };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const ENTER = { kind: 'enter', messages: [] };
|
|
112
|
+
|
|
113
|
+
// ============================ 纯函数 ============================
|
|
114
|
+
|
|
115
|
+
test('常量口径:触发阈值 32、保留 6 条、占位符含可识别标记', () => {
|
|
116
|
+
assert.equal(DOWNGRADE_TRIGGER, 32);
|
|
117
|
+
assert.equal(DOWNGRADE_KEEP, 6);
|
|
118
|
+
const text = downgradeText(12345);
|
|
119
|
+
assert.ok(text.includes(DOWNGRADE_MARK), '占位符必须包含 DOWNGRADE_MARK');
|
|
120
|
+
assert.ok(text.includes('12345 chars elided'), '占位符报出省掉的字符数');
|
|
121
|
+
assert.ok(text.startsWith('[... tool result downgraded to save context: 12345'), '文本:' + text);
|
|
122
|
+
assert.ok(downgradeText(-1).includes('0 chars elided'), '非法字符数回落 0');
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('不触发:可降级条数恰好等于 trigger(32)时返回空数组', () => {
|
|
126
|
+
// 38 条 = 32 条窗口外 + 6 条保留 → 可降级 32,不满足「严格大于」。
|
|
127
|
+
assert.deepEqual(selectDowngradeTargets(makeResults(38)), []);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test('触发:39 条时返回窗口外全部 seq(1..33),最近 6 条不动', () => {
|
|
131
|
+
const targets = selectDowngradeTargets(makeResults(39));
|
|
132
|
+
assert.equal(targets.length, 33);
|
|
133
|
+
assert.deepEqual(targets, Array.from({ length: 33 }, (_, i) => i + 1));
|
|
134
|
+
assert.ok(Math.max(...targets) === 33, 'seq 34..39(最近 6 条)永不降级');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('排序无关:乱序输入仍按 seq 升序返回,保留窗口按最大 seq 计算', () => {
|
|
138
|
+
const shuffled = makeResults(39).reverse();
|
|
139
|
+
assert.deepEqual(selectDowngradeTargets(shuffled), Array.from({ length: 33 }, (_, i) => i + 1));
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('跳过 isError:错误结果保持原样,且不计入可降级条数', () => {
|
|
143
|
+
const results = makeResults(41);
|
|
144
|
+
results[4].isError = true; // seq 5
|
|
145
|
+
results[6].isError = true; // seq 7
|
|
146
|
+
const targets = selectDowngradeTargets(results);
|
|
147
|
+
// 41 - 6 = 35 条窗口外;跳过 2 条 error → 33 条可降级 > 32,触发。
|
|
148
|
+
assert.equal(targets.length, 33);
|
|
149
|
+
assert.ok(!targets.includes(5) && !targets.includes(7), 'error 结果不得进入目标集合');
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test('跳过已降级:alreadyDowngraded 不再改写,也不计入可降级条数', () => {
|
|
153
|
+
const results = makeResults(41);
|
|
154
|
+
results[1].alreadyDowngraded = true; // seq 2
|
|
155
|
+
results[8].alreadyDowngraded = true; // seq 9
|
|
156
|
+
const targets = selectDowngradeTargets(results);
|
|
157
|
+
assert.equal(targets.length, 33);
|
|
158
|
+
assert.ok(!targets.includes(2) && !targets.includes(9), '已降级节点不得重复改写');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('参数覆盖:trigger / keep 可调,keep=0 时全部进入候选', () => {
|
|
162
|
+
assert.deepEqual(selectDowngradeTargets(makeResults(4), { trigger: 2, keep: 1 }), [1, 2, 3]);
|
|
163
|
+
assert.deepEqual(selectDowngradeTargets(makeResults(3), { trigger: 2, keep: 1 }), [], '等于阈值不触发');
|
|
164
|
+
assert.deepEqual(selectDowngradeTargets(makeResults(3), { trigger: 0, keep: 0 }), [1, 2, 3]);
|
|
165
|
+
assert.deepEqual(selectDowngradeTargets(makeResults(2), { trigger: 2, keep: 0 }), [], '可降级条数等于 trigger 时不触发');
|
|
166
|
+
// 非法选项静默回落默认,不抛。
|
|
167
|
+
assert.deepEqual(selectDowngradeTargets(makeResults(3), { trigger: 'x', keep: -1 }), []);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('空输入与非数组输入返回空数组', () => {
|
|
171
|
+
assert.deepEqual(selectDowngradeTargets([]), []);
|
|
172
|
+
assert.deepEqual(selectDowngradeTargets(null), []);
|
|
173
|
+
assert.deepEqual(selectDowngradeTargets([{ seq: 'x' }, null, {}]), []);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test('messageChars / isDowngradedMessage:只数 text 块,占位符可识别', () => {
|
|
177
|
+
assert.equal(messageChars({ content: [{ type: 'text', text: 'abc' }, { type: 'image' }] }), 3);
|
|
178
|
+
assert.equal(messageChars({ content: [{ type: 'text', text: '😀' }] }), 1, '按码点计数,不拆代理对');
|
|
179
|
+
assert.equal(messageChars(null), 0);
|
|
180
|
+
assert.equal(isDowngradedMessage({ content: [{ type: 'text', text: downgradeText(10) }] }), true);
|
|
181
|
+
assert.equal(isDowngradedMessage({ content: [{ type: 'text', text: 'original result' }] }), false);
|
|
182
|
+
assert.equal(isDowngradedMessage({ content: [] }), false);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// ============================ 插件 ============================
|
|
186
|
+
|
|
187
|
+
test('插件形状:name / 默认导出 / 注册 agent/pre-step', () => {
|
|
188
|
+
__internals.resetWarning();
|
|
189
|
+
const { ctx, handlers } = makeCtx();
|
|
190
|
+
assert.equal(name, 'lean-history-downgrade');
|
|
191
|
+
apply(ctx, {});
|
|
192
|
+
assert.ok(handlers.has('agent/pre-step'), '必须挂到 agent/pre-step');
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test('正常路径:阈值满足时先记 compaction/prune 再 append 替换,最近 6 条原样', async () => {
|
|
196
|
+
__internals.resetWarning();
|
|
197
|
+
const { ctx, handlers, warnings } = makeCtx();
|
|
198
|
+
const { session, appends } = makeSession({ count: 40 });
|
|
199
|
+
apply(ctx, {});
|
|
200
|
+
const handler = handlers.get('agent/pre-step');
|
|
201
|
+
const decision = await handler({ agent: { session }, messages: [], turn: 1, step: 1 }, async () => ENTER);
|
|
202
|
+
|
|
203
|
+
assert.deepEqual(decision, ENTER, 'next() 的决策原样返回');
|
|
204
|
+
assert.equal(warnings.length, 0);
|
|
205
|
+
|
|
206
|
+
const prunes = appends.filter((a) => a.type === 'compaction/prune');
|
|
207
|
+
const replacements = appends.filter((a) => a.type === 'tool/result');
|
|
208
|
+
assert.equal(replacements.length, 34, '40 条 - 保留 6 条 = 34 条被降级');
|
|
209
|
+
assert.equal(prunes.length, 34, '每条替换都紧邻一条影子价格记录');
|
|
210
|
+
|
|
211
|
+
// 第一条:prune 紧接 replacement(协议要求「immediately precedes」)。
|
|
212
|
+
assert.equal(appends[0].type, 'compaction/prune');
|
|
213
|
+
assert.equal(appends[1].type, 'tool/result');
|
|
214
|
+
assert.deepEqual(appends[0].data.shadowedRange, { start: 1, end: 1 });
|
|
215
|
+
assert.deepEqual(appends[0].data.shadowedSeqs, [1]);
|
|
216
|
+
assert.equal(appends[0].data.shadowedTokenCount, 123);
|
|
217
|
+
|
|
218
|
+
const first = appends[1];
|
|
219
|
+
assert.deepEqual(first.opts.surfaceOp, { op: 'replace', startSeq: 1, endSeq: 1 });
|
|
220
|
+
assert.deepEqual(first.opts.sourceEventSeqs, [1]);
|
|
221
|
+
assert.equal(first.data.turn, 1, '原 data 除 message 外原样保留');
|
|
222
|
+
assert.equal(first.data.message.role, 'tool');
|
|
223
|
+
assert.equal(first.data.message.toolCallId, 'c1', 'tool 身份不变');
|
|
224
|
+
assert.ok(first.data.message.content[0].text.includes(DOWNGRADE_MARK));
|
|
225
|
+
assert.ok(first.data.message.content[0].text.includes('1000 chars elided'));
|
|
226
|
+
assert.equal(first.data.message.content.length, 1, '降级后只剩一行占位符');
|
|
227
|
+
|
|
228
|
+
// 最近 6 条(seq 35..40)从未被替换。
|
|
229
|
+
const replaced = replacements.map((a) => a.opts.surfaceOp.startSeq);
|
|
230
|
+
assert.ok(!replaced.some((seq) => seq > 34), 'seq 35..40 必须保持原样');
|
|
231
|
+
assert.deepEqual(replaced, Array.from({ length: 34 }, (_, i) => i + 1));
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
test('无 tokenMeter 时跳过 compaction/prune,但替换照做(不写假 token 数)', async () => {
|
|
235
|
+
__internals.resetWarning();
|
|
236
|
+
const { ctx, handlers } = makeCtx({ withMeter: false });
|
|
237
|
+
const { session, appends } = makeSession({ count: 40 });
|
|
238
|
+
apply(ctx, {});
|
|
239
|
+
await handlers.get('agent/pre-step')({ agent: { session } }, async () => ENTER);
|
|
240
|
+
assert.equal(appends.filter((a) => a.type === 'compaction/prune').length, 0);
|
|
241
|
+
assert.equal(appends.filter((a) => a.type === 'tool/result').length, 34);
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test('不触发时一个事件都不写(日志前缀稳定)', async () => {
|
|
245
|
+
__internals.resetWarning();
|
|
246
|
+
const { ctx, handlers } = makeCtx();
|
|
247
|
+
const { session, appends } = makeSession({ count: 38 });
|
|
248
|
+
apply(ctx, {});
|
|
249
|
+
await handlers.get('agent/pre-step')({ agent: { session } }, async () => ENTER);
|
|
250
|
+
assert.equal(appends.length, 0);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test('已降级的节点不再改写(批与批之间不会被重复处理)', async () => {
|
|
254
|
+
__internals.resetWarning();
|
|
255
|
+
const { ctx, handlers } = makeCtx();
|
|
256
|
+
const { session, appends, events } = makeSession({ count: 41 });
|
|
257
|
+
patchMessage(events, 2, { content: [{ type: 'text', text: downgradeText(10) }] });
|
|
258
|
+
patchMessage(events, 9, { content: [{ type: 'text', text: downgradeText(10) }] });
|
|
259
|
+
apply(ctx, {});
|
|
260
|
+
await handlers.get('agent/pre-step')({ agent: { session } }, async () => ENTER);
|
|
261
|
+
const replaced = appends.filter((a) => a.type === 'tool/result').map((a) => a.opts.surfaceOp.startSeq);
|
|
262
|
+
assert.equal(replaced.length, 33);
|
|
263
|
+
assert.ok(!replaced.includes(2) && !replaced.includes(9), '已降级节点被跳过');
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
test('isError 结果保持原样', async () => {
|
|
267
|
+
__internals.resetWarning();
|
|
268
|
+
const { ctx, handlers } = makeCtx();
|
|
269
|
+
const { session, appends, events } = makeSession({ count: 41 });
|
|
270
|
+
patchMessage(events, 5, { isError: true });
|
|
271
|
+
patchMessage(events, 7, { isError: true });
|
|
272
|
+
apply(ctx, {});
|
|
273
|
+
await handlers.get('agent/pre-step')({ agent: { session } }, async () => ENTER);
|
|
274
|
+
const replaced = appends.filter((a) => a.type === 'tool/result').map((a) => a.opts.surfaceOp.startSeq);
|
|
275
|
+
assert.equal(replaced.length, 33);
|
|
276
|
+
assert.ok(!replaced.includes(5) && !replaced.includes(7));
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
test('失败安全:append 抛异常时钩子不抛、next 照常执行、只 warn 一次', async () => {
|
|
280
|
+
__internals.resetWarning();
|
|
281
|
+
const { ctx, handlers, warnings } = makeCtx();
|
|
282
|
+
const { session } = makeSession({ count: 40, appendThrows: true });
|
|
283
|
+
apply(ctx, {});
|
|
284
|
+
const handler = handlers.get('agent/pre-step');
|
|
285
|
+
const first = await handler({ agent: { session } }, async () => ENTER);
|
|
286
|
+
assert.deepEqual(first, ENTER, '异常后仍返回 next() 的决策');
|
|
287
|
+
assert.equal(warnings.length, 1, '只 warn 一次');
|
|
288
|
+
assert.ok(warnings[0].includes('[lean-history-downgrade]'), '日志带模块前缀:' + warnings[0]);
|
|
289
|
+
|
|
290
|
+
const second = await handler({ agent: { session } }, async () => ENTER);
|
|
291
|
+
assert.deepEqual(second, ENTER);
|
|
292
|
+
assert.equal(warnings.length, 1, '模块级去重:第二步不再刷日志');
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
test('feature-detect:缺 surface / eventAt / deriveEventMessage / append 任一都静默跳过', async () => {
|
|
296
|
+
__internals.resetWarning();
|
|
297
|
+
const cases = [
|
|
298
|
+
{ name: 'surface', mutate: (s) => { s.surface = undefined; } },
|
|
299
|
+
{ name: 'surface.nodes', mutate: (s) => { s.surface = {}; } },
|
|
300
|
+
{ name: 'eventAt', mutate: (s) => { delete s.eventAt; } },
|
|
301
|
+
{ name: 'deriveEventMessage', mutate: (s) => { delete s.deriveEventMessage; } },
|
|
302
|
+
{ name: 'append', mutate: (s) => { delete s.append; } },
|
|
303
|
+
];
|
|
304
|
+
for (const item of cases) {
|
|
305
|
+
const { ctx, warnings } = makeCtx();
|
|
306
|
+
const { session, appends } = makeSession({ count: 40 });
|
|
307
|
+
item.mutate(session);
|
|
308
|
+
const decision = await handlePreStep(ctx, { agent: { session } }, async () => ENTER);
|
|
309
|
+
assert.deepEqual(decision, ENTER, item.name + ':仍返回 next() 决策');
|
|
310
|
+
assert.equal(appends.length, 0, item.name + ':不写任何事件');
|
|
311
|
+
assert.equal(warnings.length, 0, item.name + ':静默跳过,不 warn');
|
|
312
|
+
}
|
|
313
|
+
assert.equal(isSupportedSession(null), false);
|
|
314
|
+
assert.equal(isSupportedSession({}), false);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
test('环境变量开关:DSH_LEAN_ROUTER_DOWNGRADE=0 时不注册钩子', () => {
|
|
318
|
+
__internals.resetWarning();
|
|
319
|
+
const previous = process.env.DSH_LEAN_ROUTER_DOWNGRADE;
|
|
320
|
+
process.env.DSH_LEAN_ROUTER_DOWNGRADE = '0';
|
|
321
|
+
try {
|
|
322
|
+
const { ctx, handlers } = makeCtx();
|
|
323
|
+
apply(ctx, {});
|
|
324
|
+
assert.equal(handlers.size, 0);
|
|
325
|
+
} finally {
|
|
326
|
+
if (previous === undefined) delete process.env.DSH_LEAN_ROUTER_DOWNGRADE;
|
|
327
|
+
else process.env.DSH_LEAN_ROUTER_DOWNGRADE = previous;
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
test('config.enabled=false 时不注册;构造期绝不抛(含怪配置与缺 ctx)', () => {
|
|
332
|
+
__internals.resetWarning();
|
|
333
|
+
const { ctx, handlers } = makeCtx();
|
|
334
|
+
apply(ctx, { enabled: false });
|
|
335
|
+
assert.equal(handlers.size, 0);
|
|
336
|
+
|
|
337
|
+
assert.doesNotThrow(() => apply(undefined, undefined));
|
|
338
|
+
assert.doesNotThrow(() => apply({}, { trigger: 'x', keep: -3 }));
|
|
339
|
+
assert.doesNotThrow(() => apply({ logger: { warn() { throw new Error('logger boom'); } }, on() { throw new Error('on boom'); } }, {}));
|
|
340
|
+
assert.deepEqual(resolveConfig({ trigger: 4, keep: 2 }), { enabled: true, trigger: 4, keep: 2 });
|
|
341
|
+
assert.deepEqual(resolveConfig(null), { enabled: true, trigger: DOWNGRADE_TRIGGER, keep: DOWNGRADE_KEEP });
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
test('配置项透传:apply 的 trigger/keep 覆盖默认阈值', async () => {
|
|
345
|
+
__internals.resetWarning();
|
|
346
|
+
const { ctx, handlers } = makeCtx();
|
|
347
|
+
const { session, appends } = makeSession({ count: 4 });
|
|
348
|
+
apply(ctx, { trigger: 2, keep: 1 });
|
|
349
|
+
await handlers.get('agent/pre-step')({ agent: { session } }, async () => ENTER);
|
|
350
|
+
const replaced = appends.filter((a) => a.type === 'tool/result').map((a) => a.opts.surfaceOp.startSeq);
|
|
351
|
+
assert.deepEqual(replaced, [1, 2, 3], 'trigger=2 / keep=1 时降级 seq 1..3');
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
test('payload 异常/缺参不抛:无 agent、next 缺失都安全', async () => {
|
|
355
|
+
__internals.resetWarning();
|
|
356
|
+
const { ctx } = makeCtx();
|
|
357
|
+
assert.equal(await handlePreStep(ctx, undefined, async () => ENTER), ENTER);
|
|
358
|
+
assert.equal(await handlePreStep(ctx, { agent: {} }, async () => ENTER), ENTER);
|
|
359
|
+
assert.equal(await handlePreStep(ctx, { agent: { session: null } }, async () => ENTER), ENTER);
|
|
360
|
+
assert.equal(await handlePreStep(ctx, {}, undefined), undefined, 'next 缺失时返回 undefined,不改决策');
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
test('collectToolResults 只收 surface 上的 tool/result(其它事件忽略)', () => {
|
|
364
|
+
const { session, events } = makeSession({ count: 3 });
|
|
365
|
+
events.set(4, { type: 'assistant/message', seq: 4, data: { message: { role: 'assistant', content: [] } } });
|
|
366
|
+
session.surface = { nodes: [1, 2, 4, 3] };
|
|
367
|
+
const results = collectToolResults(session);
|
|
368
|
+
assert.deepEqual(results.map((r) => r.seq), [1, 2, 3]);
|
|
369
|
+
assert.equal(results[0].chars, 1000);
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
test('downgradeSession 返回值:charsRemoved 是「省掉的字符数」净额', () => {
|
|
373
|
+
const { ctx } = makeCtx();
|
|
374
|
+
const { session } = makeSession({ count: 40 });
|
|
375
|
+
const report = downgradeSession(session, ctx);
|
|
376
|
+
assert.equal(report.downgraded.length, 34);
|
|
377
|
+
const perNode = 1000 - Array.from(downgradeText(1000)).length;
|
|
378
|
+
assert.equal(report.charsRemoved, perNode * 34);
|
|
379
|
+
});
|
|
@@ -26,9 +26,9 @@ function suffixBlock(text) {
|
|
|
26
26
|
return out.join('\n');
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
test('frag-preset 是 preset 行唯一生效 owner:
|
|
29
|
+
test('frag-preset 是 preset 行唯一生效 owner:22 行并集、无重复、toolface 收尾', () => {
|
|
30
30
|
const ids = frag.split(/\r?\n/).filter(l => /^ - id: /.test(l)).map(l => /^ - id: (.+)$/.exec(l)[1].trim());
|
|
31
|
-
assert.equal(ids.length,
|
|
31
|
+
assert.equal(ids.length, 22, '并集行数 = 覆写块 21 + toolface(2.0.0 移除 skill-lean-router;2.2.0 加 lean-usage-ledger;2.2.5 加 lean-history-downgrade;ptc-runtime 属宿主层,不进 preset)');
|
|
32
32
|
assert.equal(new Set(ids).size, ids.length, '无重复 id');
|
|
33
33
|
assert.equal(ids[ids.length - 1], 'toolface', 'toolface 最后(遮蔽面与 preset 同行生效)');
|
|
34
34
|
assert.ok(!ids.includes('ptc-runtime'), 'ptc-runtime 由宿主 dsh-base 挂载,放进 preset 会让整条 preset 激活失败(1.0.3 事故回归)');
|
package/test/lean-frag.test.mjs
CHANGED
|
@@ -123,7 +123,7 @@ test('(宿主 yaml 可用时)合并后整文件可解析且行形态符合
|
|
|
123
123
|
const doc = yaml.parse(base + (frag.endsWith('\n') ? frag : frag + '\n'), { schema: 'core' });
|
|
124
124
|
assert.equal(doc.length, 6, '合并后顶层 6 项:base insert + 裸覆写 + balance + delivery-gate + concurrency + usage-ledger');
|
|
125
125
|
const override = doc.find((d) => d.id === 'preset-lean-router');
|
|
126
|
-
assert.equal(override.config.plugins.length,
|
|
126
|
+
assert.equal(override.config.plugins.length, 21);
|
|
127
127
|
const deleg = override.config.plugins.find((p) => p.id === 'delegation');
|
|
128
128
|
assert.deepEqual(deleg.config.filter((c) => c.disabled === true).map((c) => c.id), ['tool-subagent-codex', 'tool-subagent-claude-code', 'workflow-ptc', 'tool-workflow', 'tool-ralph']);
|
|
129
129
|
const balance = doc.find((d) => d.insert && d.insert[0] && d.insert[0].id === 'preset-lean-router-balance');
|
|
@@ -50,6 +50,29 @@ test('persona-text.js 独立加载:lean 13 条 + 2 软门 + 自检题钩子 +
|
|
|
50
50
|
assert.equal(m.PERSONA_PREFIX, 'You are a coding agent powered by the {{model}} model.');
|
|
51
51
|
});
|
|
52
52
|
|
|
53
|
+
test('persona 并行调用引导:只读并发 + 写向同批省往返 + 遮挡整批拒绝(块 <=320,suffix <=4200)', async () => {
|
|
54
|
+
const m = await mod('persona-text.js');
|
|
55
|
+
const s = m.LEAN_PERSONA_SUFFIX;
|
|
56
|
+
// 事实 1:只读工具可真正重叠执行(tool-concurrency.js 给 glob/grep 打了 isConcurrencySafe)
|
|
57
|
+
for (const t of ['read', 'grep', 'glob', 'read_image']) {
|
|
58
|
+
assert.ok(s.includes(t), '并行引导缺只读工具名:' + t);
|
|
59
|
+
}
|
|
60
|
+
// 事实 2:写向/独占工具同批仍只算一次往返
|
|
61
|
+
for (const t of ['pwsh', 'edit', 'write']) {
|
|
62
|
+
assert.ok(s.includes(t), '并行引导缺写向工具名:' + t);
|
|
63
|
+
}
|
|
64
|
+
// 事实 3:混入被遮挡(masked)名字会让整批被拒、兄弟调用不执行
|
|
65
|
+
assert.ok(s.includes('masked'), '需提醒不要在同批混入被遮挡(masked)工具名');
|
|
66
|
+
// 体积上界:引导块本身极度精简,且 suffix 总长受控
|
|
67
|
+
const start = s.indexOf('PARALLEL CALLS');
|
|
68
|
+
assert.ok(start >= 0, '需有并行调用引导块');
|
|
69
|
+
const end = s.indexOf('7. Programmatic tool mode');
|
|
70
|
+
assert.ok(end > start, '并行引导块须位于规则 6 与规则 7 之间');
|
|
71
|
+
const block = s.slice(start, end).replace(/\n+$/, '');
|
|
72
|
+
assert.ok(block.length <= 320, '并行引导块须 <=320 字符,实为 ' + block.length);
|
|
73
|
+
assert.ok(s.length <= 4200, 'persona suffix 总长须 <=4200,实为 ' + s.length);
|
|
74
|
+
});
|
|
75
|
+
|
|
53
76
|
test('plan-mode.js 独立加载:v1 政策段原文要点', async () => {
|
|
54
77
|
const m = await mod('plan-mode.js');
|
|
55
78
|
for (const needle of ['You are in plan mode.', 'exit_plan_mode', 'Do not use todo_write to track this planning phase', 'Make the plan decision-complete']) {
|