dsh-lean-router 0.0.0-stage → 0.2.3

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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +23 -0
  3. package/README.en.md +73 -0
  4. package/README.md +72 -2
  5. package/cordis.patch.yml +870 -0
  6. package/docs/adr/0001-token-ledger-durable-usage.md +11 -0
  7. package/docs/agents/domain.md +38 -0
  8. package/docs/agents/issue-tracker.md +44 -0
  9. package/docs/agents/release.md +24 -0
  10. package/docs/agents/triage-labels.md +13 -0
  11. package/docs/agents/verification.md +32 -0
  12. package/docs/architecture.en.md +67 -0
  13. package/docs/architecture.md +66 -0
  14. package/docs/changelog.en.md +266 -0
  15. package/docs/changelog.md +269 -0
  16. package/docs/configuration.en.md +57 -0
  17. package/docs/configuration.md +57 -0
  18. package/docs/install.en.md +60 -0
  19. package/docs/install.md +60 -0
  20. package/docs/quickstart.en.md +75 -0
  21. package/docs/quickstart.md +75 -0
  22. package/docs/release-checklist.en.md +82 -0
  23. package/docs/release-checklist.md +131 -0
  24. package/docs//345/244/215/346/240/270-/345/205/263/346/217/222/344/273/266/346/270/205/345/215/225.md +108 -0
  25. package/docs//345/267/245/345/205/267/351/201/256/350/224/275-/346/216/245/347/272/277/350/257/264/346/230/216.md +140 -0
  26. package/docs//350/267/257/347/224/261-/350/256/276/350/256/241/350/257/264/346/230/216.md +104 -0
  27. package/lib/bands.js +149 -0
  28. package/lib/index.js +12 -0
  29. package/lib/lean/compaction.js +119 -0
  30. package/lib/lean/delivery-gate.js +312 -0
  31. package/lib/lean/disabled.js +61 -0
  32. package/lib/lean/history-budget.js +301 -0
  33. package/lib/lean/history-downgrade.js +345 -0
  34. package/lib/lean/index.js +19 -0
  35. package/lib/lean/output-slim.js +271 -0
  36. package/lib/lean/persona-text.js +111 -0
  37. package/lib/lean/plan-mode.js +31 -0
  38. package/lib/lean/pruner.js +75 -0
  39. package/lib/lean/tool-concurrency.js +319 -0
  40. package/lib/lean/usage-ledger.js +442 -0
  41. package/lib/router.js +287 -0
  42. package/lib/token-ledger/index.js +147 -0
  43. package/lib/token-ledger/live.js +193 -0
  44. package/lib/toolface/discovery.js +297 -0
  45. package/lib/toolface/executor.js +323 -0
  46. package/lib/toolface/index.js +242 -0
  47. package/lib/toolface/pool.js +160 -0
  48. package/lib/toolface/retention.js +187 -0
  49. package/lib/toolface/rules.js +395 -0
  50. package/lib/toolface/scope.js +188 -0
  51. package/lib/toolface/transport.js +335 -0
  52. package/package.json +65 -4
  53. package/presets/base/frag-lean.patch.yml +459 -0
  54. package/presets/base/frag-preset.patch.yml +274 -0
  55. package/presets/base/frag-router.patch.yml +17 -0
  56. package/presets/base/frag-toolface.patch.yml +73 -0
  57. package/presets/base/lean-router.patch.yml +44 -0
  58. package/scripts/build-bundle.mjs +45 -0
  59. package/scripts/doctor.mjs +35 -0
  60. package/scripts/install-profile.mjs +113 -0
  61. package/scripts/install.mjs +20 -0
  62. package/scripts/integrate-preset.mjs +107 -0
  63. package/scripts/release.mjs +145 -0
  64. package/scripts/verify.mjs +8 -0
  65. package/test/build.test.mjs +7 -0
  66. package/test/history-budget.test.mjs +210 -0
  67. package/test/history-downgrade.test.mjs +379 -0
  68. package/test/integration-preset.test.mjs +59 -0
  69. package/test/lean-compaction.test.mjs +47 -0
  70. package/test/lean-concurrency.test.mjs +117 -0
  71. package/test/lean-delivery-gate.test.mjs +75 -0
  72. package/test/lean-frag.test.mjs +132 -0
  73. package/test/lean-modules.test.mjs +112 -0
  74. package/test/lean-pruner.test.mjs +42 -0
  75. package/test/output-slim.test.mjs +212 -0
  76. package/test/package.test.mjs +20 -0
  77. package/test/patch-yaml.test.mjs +45 -0
  78. package/test/plugin-entry.test.mjs +26 -0
  79. package/test/router-bands.test.mjs +98 -0
  80. package/test/router.test.mjs +215 -0
  81. package/test/token-ledger-live.test.mjs +351 -0
  82. package/test/token-ledger.test.mjs +264 -0
  83. package/test/toolface-executor.test.mjs +302 -0
  84. package/test/toolface-mask.test.mjs +258 -0
  85. package/test/toolface-rules.test.mjs +177 -0
  86. package/test/toolface-runtime.test.mjs +466 -0
  87. package/test/toolface-wiring.test.mjs +272 -0
  88. package/test/usage-ledger-inject.test.mjs +50 -0
  89. package/test/usage-ledger.test.mjs +399 -0
@@ -0,0 +1,271 @@
1
+ // dsh-lean-router · lib/lean/output-slim.js —— 机制 5:工具输出的保守压缩(同步纯函数)
2
+ //
3
+ // 口径(ticket: context_output_compactor,GT-17「不改 JSON 结构」):
4
+ // - 只在文本超过阈值时启用,小输出一个字都不改;
5
+ // - 普通文本:只折叠「连续 >= 3 行完全相同」的块,保留一行并紧跟一行 marker;
6
+ // - 可 JSON.parse 的文本(code_run 的 content 恒为 JSON 文本):绝不按行折叠顶层。
7
+ // 改为两条保持结构的压缩:
8
+ // a) 字符串值内部做相邻重复行折叠(marker 作为字符串内容);
9
+ // b) 字符串数组折叠相邻相同元素——保留第一个,后面连续相同的 N 个(N >= 2)
10
+ // 替换为一个 marker 字符串,数组长度因此变短(预期行为)。
11
+ // 键与类型不变,再 JSON.stringify 输出;若 stringify 后不比原文短则返回原文;
12
+ // - 错误 / 异常 / 失败 / 退出码 / 文件路径 / 结论行永不折叠、永不删除(两种路径同判据);
13
+ // - 不做结构化摘要、不改值、不重排键。
14
+ //
15
+ // 与 lib/lean/pruner.js 的关系:pruner 按头 / 中 / 尾裁掉中段(宿主 pruner 的纯函数端口),
16
+ // 本模块只做「相邻重复行」的局部折叠,判据更保守,二者互不替代。
17
+ //
18
+ // 零依赖、同步、纯函数:不读会话、不碰 Cordis 上下文,可脱离宿主单测。
19
+ // 注意:本模块只产出「模型可见文本」,值的处理在其调用方(lib/toolface/executor.js)。
20
+
21
+ /** 启用压缩的最小文本长度(严格大于该值才启用,等于阈值不启用)。 */
22
+ export const SLIM_THRESHOLD_CHARS = 2000;
23
+
24
+ /** 连续相同行达到该数量才折叠;2 行重复保持原样。 */
25
+ export const COLLAPSE_MIN_LINES = 3;
26
+
27
+ /** 单次折叠的 marker 原文({collapsed} 为被折叠掉的行数,即 run 长度 - 1)。 */
28
+ export const COLLAPSE_MARKER = '[... {collapsed} identical lines collapsed]';
29
+
30
+ /** 压缩收益 marker 原文({saved} 为折叠本身节省的字符数,不含本 marker)。 */
31
+ export const SAVED_MARKER = '[... output compacted: {saved} chars saved ...]';
32
+
33
+ /**
34
+ * 受保护行的判据。任何命中一项的行都不折叠——宁可少折叠,也不把结论行吃掉。
35
+ * 覆盖:错误 / 异常 / 失败 / 退出码(含中文口径)、结论行、文件路径。
36
+ */
37
+ const PROTECTED_PATTERNS = [
38
+ // 错误 / 异常 / 失败 / 致命(含 stderr、非零退出等常见措辞)
39
+ /\b(?:error|errors|exception|exceptions|failed|failure|failures|fatal|panic|traceback|throw|throws|threw|stderr|denied|refused)\b/i,
40
+ // 退出码 / 退出状态
41
+ /\b(?:exit\s*(?:code|status))\b/i,
42
+ /\b(?:exited\s+with|non-?zero)\b/i,
43
+ // 中文口径的错误与结论
44
+ /(?:错误|异常|失败|退出码|结论|总结|原因|无法|抛出)/,
45
+ // 结论行:整行以结论词开头(大小写不敏感)
46
+ /^\s*(?:summary|conclusion|result|verdict|totals?)\b/i,
47
+ // 文件路径:盘符、UNC、POSIX 绝对路径、./ ../ 相对路径
48
+ /(?:^|[\s"'(<[=:])(?:[A-Za-z]:[\\/]|\\\\|\/|\.{1,2}\/)/,
49
+ // 文件路径:带已知扩展名的文件名
50
+ /(?:^|[\s"'(<[=:])[\w.@~+-]+\.(?:[cm]?[jt]sx?|jsonc?|py|rb|go|rs|java|kt|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|ps1|cmd|bat|md|markdown|txt|log|ya?ml|toml|ini|cfg|conf|xml|html?|css|scss|sql|db|lock|env|patch|diff)\b/i,
51
+ ];
52
+
53
+ /**
54
+ * 裸大整数 token(16 位以上):`JSON.parse` 会丢精度,遇到这类文档完全不碰,
55
+ * 宁可放弃这次压缩也不改写用户数据。
56
+ */
57
+ const BIG_INTEGER_TOKEN = /(?:^|[\s:,[{])-?\d{16,}(?=[\s,\]}]|$)/;
58
+
59
+ /** 解析阈值:非正数 / 非数字回落到默认值。 */
60
+ function resolveThreshold(options) {
61
+ const value = options?.thresholdChars;
62
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : SLIM_THRESHOLD_CHARS;
63
+ }
64
+
65
+ /** 该行是否必须原样保留。 */
66
+ export function isProtectedLine(line) {
67
+ return typeof line === 'string' && PROTECTED_PATTERNS.some((pattern) => pattern.test(line));
68
+ }
69
+
70
+ /** 折叠结果的可读 marker。 */
71
+ function collapseMarker(collapsed) {
72
+ return COLLAPSE_MARKER.replace('{collapsed}', String(collapsed));
73
+ }
74
+
75
+ /** 收益 marker。 */
76
+ function savedMarker(saved) {
77
+ return SAVED_MARKER.replace('{saved}', String(saved));
78
+ }
79
+
80
+ /**
81
+ * 按行折叠相邻重复块(不设阈值门、不加收益 marker):普通文本与 JSON 字符串值共用。
82
+ *
83
+ * @param text - 待折叠文本。
84
+ * @returns `{ eol, body, collapsedLines }`:换行风格、折叠正文、被折叠掉的总行数。
85
+ */
86
+ function foldLines(text) {
87
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
88
+ const lines = text.split(/\r?\n/);
89
+ const kept = [];
90
+ let collapsedLines = 0;
91
+
92
+ for (let index = 0; index < lines.length;) {
93
+ const line = lines[index];
94
+ let end = index + 1;
95
+ while (end < lines.length && lines[end] === line) end += 1;
96
+ const runLength = end - index;
97
+ // 受保护的行整段保留:连续相同的错误行也是每条都有信息。
98
+ if (runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(line)) {
99
+ const collapsed = runLength - 1;
100
+ kept.push(line);
101
+ kept.push(collapseMarker(collapsed));
102
+ collapsedLines += collapsed;
103
+ } else {
104
+ for (let offset = index; offset < end; offset += 1) kept.push(line);
105
+ }
106
+ index = end;
107
+ }
108
+
109
+ return { eol, body: kept.join(eol), collapsedLines };
110
+ }
111
+
112
+ /**
113
+ * 折叠一段普通文本并在末尾补收益 marker;不值得改时返回原值。
114
+ * @param text - 已确认超过阈值的文本。
115
+ * @returns 折叠后的文本,或原值。
116
+ */
117
+ function slimPlainText(text) {
118
+ const folded = foldLines(text);
119
+ if (folded.collapsedLines === 0) return text;
120
+ const savedChars = text.length - folded.body.length;
121
+ // 负收益(折叠 marker 比省下的内容还长)就不动原文。
122
+ if (savedChars <= 0) return text;
123
+ return folded.body + folded.eol + savedMarker(savedChars);
124
+ }
125
+
126
+ /**
127
+ * 压缩 JSON 文档里的一个字符串值:只在字符串内部折叠相邻重复行。
128
+ * 未超过阈值的字符串(短值)不碰。
129
+ */
130
+ function slimJsonString(value, threshold) {
131
+ if (value.length <= threshold) return value;
132
+ const folded = foldLines(value);
133
+ if (folded.collapsedLines === 0) return value;
134
+ const savedChars = value.length - folded.body.length;
135
+ if (savedChars <= 0) return value;
136
+ return folded.body + folded.eol + savedMarker(savedChars);
137
+ }
138
+
139
+ /**
140
+ * 折叠字符串数组里相邻相同的元素:保留第一个,后面连续相同的 N 个(N >= 2)
141
+ * 替换成一个 marker 字符串。错误 / 路径 / 结论行元素永不折叠。
142
+ * 非字符串元素不参与折叠(类型与顺序都保持)。
143
+ *
144
+ * @param items - 已递归处理过的数组元素。
145
+ * @returns `{ items, collapsed }`:折叠后的数组与被折叠掉的元素总数。
146
+ */
147
+ function foldStringRuns(items) {
148
+ const kept = [];
149
+ let collapsed = 0;
150
+ for (let index = 0; index < items.length;) {
151
+ const item = items[index];
152
+ let end = index + 1;
153
+ if (typeof item === 'string') {
154
+ while (end < items.length && items[end] === item) end += 1;
155
+ }
156
+ const runLength = end - index;
157
+ // 保留首个,其余至少 2 个才折叠(单个 marker 才比被折叠的元素更短)。
158
+ if (typeof item === 'string' && runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(item)) {
159
+ kept.push(item);
160
+ kept.push(collapseMarker(runLength - 1));
161
+ collapsed += runLength - 1;
162
+ } else {
163
+ for (let offset = index; offset < end; offset += 1) kept.push(items[offset]);
164
+ }
165
+ index = end;
166
+ }
167
+ return { items: kept, collapsed };
168
+ }
169
+
170
+ /**
171
+ * 递归压缩 JSON 值:字符串值内部折叠,字符串数组折叠相邻相同元素;键与类型不变。
172
+ * 数组长度可能变短(只在字符串数组的重复段上),这是预期行为。
173
+ * @returns `{ value, changed }`;`changed` 为 false 时 `value` 与入参结构等价。
174
+ */
175
+ function compactJsonStrings(node, threshold) {
176
+ let changed = false;
177
+ const walk = (current) => {
178
+ if (typeof current === 'string') {
179
+ const slimmed = slimJsonString(current, threshold);
180
+ if (slimmed === current) return current;
181
+ changed = true;
182
+ return slimmed;
183
+ }
184
+ if (Array.isArray(current)) {
185
+ const mapped = current.map(walk);
186
+ const folded = foldStringRuns(mapped);
187
+ if (folded.collapsed > 0) changed = true;
188
+ return folded.collapsed > 0 ? folded.items : mapped;
189
+ }
190
+ if (current !== null && typeof current === 'object') {
191
+ // Object.fromEntries 走 CreateDataProperty,`__proto__` 这类键不会被改写。
192
+ return Object.fromEntries(Object.entries(current).map(([key, child]) => [key, walk(child)]));
193
+ }
194
+ return current;
195
+ };
196
+ const value = walk(node);
197
+ return { value, changed };
198
+ }
199
+
200
+ /**
201
+ * JSON 文档路径:只压缩字符串值内部,结构不动。
202
+ *
203
+ * @param text - 已确认超过阈值的文本。
204
+ * @param threshold - 单字符串值启用折叠的长度阈值。
205
+ * @returns 压缩后的 JSON 文本;不是 JSON、无可压缩字符串、或 stringify 后不更短时返回原文。
206
+ */
207
+ function slimJsonDocument(text, threshold) {
208
+ const trimmed = text.trim();
209
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return undefined;
210
+ if (BIG_INTEGER_TOKEN.test(text)) return text;
211
+ let parsed;
212
+ try {
213
+ parsed = JSON.parse(text);
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ if (parsed === null || typeof parsed !== 'object') return undefined;
218
+ const { value, changed } = compactJsonStrings(parsed, threshold);
219
+ if (!changed) return text;
220
+ // 与 code_run 的 renderJson 同形(2 空格缩进),保证模型读到的排版一致。
221
+ const rendered = JSON.stringify(value, null, 2);
222
+ return rendered.length < text.length ? rendered : text;
223
+ }
224
+
225
+ /**
226
+ * 保守压缩一段模型可见文本。
227
+ *
228
+ * - 非字符串或空串:原样返回;
229
+ * - 未超过阈值:原样返回;
230
+ * - JSON 文本:递归压缩字符串值内部,并折叠字符串数组里相邻相同的元素(数组长度可变短),
231
+ * 键与类型不变;不短则原样返回;
232
+ * - 普通文本:行级折叠相邻重复块,受保护行不折叠。
233
+ *
234
+ * @param text - 待压缩文本。
235
+ * @param options - `thresholdChars` 覆盖阈值(仅供测试 / 预检)。
236
+ * @returns 压缩后的文本;任何情况下都不比原文长(JSON 路径保证),不需要压缩时返回原值。
237
+ */
238
+ export function slimToolOutput(text, options) {
239
+ if (typeof text !== 'string' || text.length === 0) return text;
240
+ const threshold = resolveThreshold(options);
241
+ if (text.length <= threshold) return text;
242
+
243
+ const json = slimJsonDocument(text, threshold);
244
+ if (json !== undefined) return json;
245
+
246
+ return slimPlainText(text);
247
+ }
248
+
249
+ /**
250
+ * 压缩一条 content 数组里的文本块。
251
+ *
252
+ * 只改 `type === 'text'` 且 `text` 是字符串的块,块上的其他字段原样保留;
253
+ * 非 text 块(图片等)与整段无变化时返回**原数组引用**,让调用方可以据此判断是否改动。
254
+ *
255
+ * @param blocks - 工具结果的内容块;非数组原样返回。
256
+ * @param options - 透传给 {@link slimToolOutput}。
257
+ * @returns 压缩后的数组,或未发生变化时的原数组。
258
+ */
259
+ export function slimContentBlocks(blocks, options) {
260
+ if (!Array.isArray(blocks)) return blocks;
261
+ let changed = false;
262
+ const next = blocks.map((block) => {
263
+ if (block === null || typeof block !== 'object') return block;
264
+ if (block.type !== 'text' || typeof block.text !== 'string') return block;
265
+ const slimmed = slimToolOutput(block.text, options);
266
+ if (slimmed === block.text) return block;
267
+ changed = true;
268
+ return { ...block, text: slimmed };
269
+ });
270
+ return changed ? next : blocks;
271
+ }
@@ -0,0 +1,111 @@
1
+ // dsh-lean-router · lib/lean/persona-text.js —— persona 双档文本(票 03 lean 层)
2
+ //
3
+ // 上游来源(vendored 口径注明,见约束台账 v1):
4
+ // - D:\Agent Workspace\.scratch\upstream\flash-presets\presets\flash-lean-ptc-v3.patch.yml
5
+ // L15-60:lean 13 条规则全文与 prefix 原文
6
+ // - D:\Agent Workspace\.scratch\upstream\flash-presets\presets\flash-lean-ptc-v3-balance.patch.yml
7
+ // L13-18:balance 3 条规则全文
8
+ // 本包增补(批准计划 .scratch/dsh-lean-router/plan.md L45/L107,62 问定案):
9
+ // - 软门:澄清 → 计划(交付门由规则 4 覆盖,不再单列)
10
+ // - 自检题钩子:只保留「合上 AI 也能做」合卷自检;勤勉自检并入规则 1
11
+ // - 两个 suffix 末行各留一行拼接占位:路由分类指令由票 05 拼接(t5 交付 ROUTER_PROMPT
12
+ // 常量,master 集成时替换占位行;本文件不写任何路由内容)
13
+ // 适配说明(与上游的实质差异):
14
+ // - 规则 7 删去 "run_code is the only tool this surface exposes"(flash 的 PTC-only 工具面
15
+ // 口径);本包工具面为票 04 的 native+code_run,折叠逻辑原样保留。
16
+ // - no-op 审查(2026-11-29):删去宿主已注入的 "Answer in the user's language"、
17
+ // 与规则 4 重复的 DELIVER 软门、与规则 1 重叠的 Diligence 钩子,并压缩各条措辞;
18
+ // 每条约束的判据保留,4581 → 约 3.4k 字符。
19
+ // 零依赖数据模块:纯 node / 任何宿主环境均可直接动态 import,不崩溃。
20
+
21
+ /** persona 前缀(照抄上游两档共用的 prefix,flash-lean-ptc-v3.patch.yml L60)。 */
22
+ export const PERSONA_PREFIX = 'You are a coding agent powered by the {{model}} model.';
23
+
24
+ /** 票 05 路由分类指令的拼接占位行(suffix 内,master 集成时整行替换)。 */
25
+ export const ROUTER_SLOT_COMMENT =
26
+ '# [ticket-05] 路由分类指令由票 05 拼接(本行为占位:集成时替换为票 05 的 ROUTER_PROMPT 常量)';
27
+
28
+ /** lean 档 2 软门(澄清/计划两晋级条件;交付门已由规则 4 覆盖,不再重复)。 */
29
+ export const LEAN_SOFT_GATES = [
30
+ 'CLARIFY: if goal, scope, or acceptance is ambiguous in a way that changes the result, ask one consolidated question round before acting; when a cheap read/probe settles it, probe instead of asking.',
31
+ 'PLAN: work touching more than one file or more than ~8 steps starts with a numbered plan with a check per step; single-file small changes skip this gate.',
32
+ ];
33
+
34
+ /** lean 档自检题钩子(合卷自检;勤勉自检并入规则 1 的停止重规划)。 */
35
+ export const LEAN_SELF_CHECK_HOOKS = [
36
+ 'Close-the-book: could I redo the last step with the AI closed - do I actually know this fact, command, or path, or would I have to look it up again? If look-up, fetch it from the source of truth now instead of trusting recall.',
37
+ ];
38
+
39
+ /** lean 档 suffix 全文:13 条硬规则(上游原文,规则 7 微调见头部说明)+ 2 软门 + 自检钩 + 拼接占位。 */
40
+ export const LEAN_PERSONA_SUFFIX = [
41
+ 'LEAN OPERATING RULES (hard constraints; they override habit and tool default wording):',
42
+ '',
43
+ 'BUDGET FIRST',
44
+ '1. Turn budget, not step budget. Target <=20 turns; folding calls into one turn is cheap, thrashing',
45
+ ' across turns is not. Past 3x the expected turns (~60), stop and re-plan instead of looping.',
46
+ ' Re-check roughly every 10 turns that this is still the shortest path; if it is not, re-plan.',
47
+ '2. Deliberate briefly. One short deliberation, then one cheap probe/command to learn the facts;',
48
+ ' do not enumerate an exhaustive design before acting.',
49
+ '3. Input/answer-type tasks (submit a file or an answer): produce the SMALLEST artifact that',
50
+ ' satisfies the stated constraints first; refine only while you are under the turn budget.',
51
+ '4. Gate before delivery, not after. Run ONE consolidated acceptance pass over every stated',
52
+ ' criterion, quote the measured numbers, and name what you did not verify. Measure hard limits',
53
+ ' with the command the judge would use (/usr/bin/time -v, ulimit -v). Over-limit is a failure even',
54
+ ' when the answer is otherwise correct. Do not verify claim by claim, do not re-run a check that',
55
+ ' already passed, and once the gate passes stop testing and deliver.',
56
+ '',
57
+ '5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file',
58
+ ' (no cat/head/tail/sed -n/find/ls -R). Piping a command\'s own output through head is fine.',
59
+ '6. Output budget. Pipe or redirect long output',
60
+ ' (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\\out.log in cmd, /tmp/out.log on POSIX).',
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.',
66
+ '7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE',
67
+ ' run_code program; a single call may still go through a one-line program so its noise stays out',
68
+ ' of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on',
69
+ ' single-file algorithm tasks - there spend the budget on reasoning and testing, not batching.',
70
+ '8. Context discipline (biggest measured lever). Read only what is new; rebuild derived answers',
71
+ ' from files with grep/scripts instead of re-reading them into context. Keep NOTES short and',
72
+ ' factual (<=60 lines).',
73
+ '9. Author incrementally: create a file once (skeleton), then extend it with edit. Never re-emit an',
74
+ ' unchanged file. After two failed shell patches, switch to the editor.',
75
+ '',
76
+ 'SAFETY',
77
+ '10. Honour scope literally (a new project means do not read or copy old-project files). Use',
78
+ ' subagents only when the user asks or the harness delegates; never spawn them to look busy.',
79
+ '11. Never put secrets, tokens or private raw material into the session; reference by path.',
80
+ '',
81
+ 'WHEN BLOCKED',
82
+ '12. If two attempts at the same approach fail, change approach once; if that also fails, report the',
83
+ ' blocker with the exact command and observed output instead of continuing.',
84
+ '13. Route awareness: running on provider "{{provider}}" with model "{{model}}". On a high-latency route',
85
+ ' prefer fewer, larger turns; on a low-latency route more probing is affordable. Never trade',
86
+ ' correctness for turn count.',
87
+ '',
88
+ 'SOFT GATES (each is one pause, never a stall)',
89
+ ...LEAN_SOFT_GATES.map((line) => '- ' + line),
90
+ '',
91
+ 'SELF-CHECK HOOKS (questions answered to yourself; speak up only when a check fails)',
92
+ ...LEAN_SELF_CHECK_HOOKS.map((line) => '- ' + line),
93
+ '',
94
+ ROUTER_SLOT_COMMENT,
95
+ ].join('\n');
96
+
97
+ /** balance 档 suffix 全文:上游 balance 3 条原文 + 同一行拼接占位。 */
98
+ export const BALANCE_PERSONA_SUFFIX = [
99
+ 'CORE RULES (only what the harness cannot enforce for you):',
100
+ '1. Answer in the user scope. Honour the requested language and the stated scope literally; do not read or copy files outside it.',
101
+ '2. Never put secrets, tokens or private raw material into the session; reference them by path.',
102
+ '3. If two attempts at the same approach fail, change approach once; if that also fails, report the blocker with the exact command and the observed output instead of continuing.',
103
+ '',
104
+ ROUTER_SLOT_COMMENT,
105
+ ].join('\n');
106
+
107
+ /** 双档汇总:给 frag-lean.patch.yml 生成器与测试用。 */
108
+ export const PERSONA_TIERS = Object.freeze({
109
+ lean: Object.freeze({ prefix: PERSONA_PREFIX, suffix: LEAN_PERSONA_SUFFIX }),
110
+ balance: Object.freeze({ prefix: PERSONA_PREFIX, suffix: BALANCE_PERSONA_SUFFIX }),
111
+ });
@@ -0,0 +1,31 @@
1
+ // dsh-lean-router · lib/lean/plan-mode.js —— plan-mode v1 政策段文本(lean 层并入项)
2
+ //
3
+ // 逐行照抄上游(vendored):
4
+ // D:\Agent Workspace\.scratch\upstream\flash-presets\presets\flash-lean-ptc-v3.patch.yml
5
+ // L93-107(planning 组 → plan-mode 行 → config.section 全文)。
6
+ // 挂接形态与上游一致:planning 组(name cordis:group, group: true, isolate.planMode: true)
7
+ // 内含 plan-mode 行(name '@deepseek-ai/dsh-plan-mode',config.section = 本文本)。
8
+ // 零依赖数据模块。
9
+ //
10
+ // 待复核(写进报告 open_questions):末段 "Under programmatic tool mode ... run_code" 一句是
11
+ // flash PTC-only 工具面口径;本包票 04 为 native+code_run 遮蔽面,集成时 master 可决定
12
+ // 保留原句(run_code 仍为内置 PTC 传输)或换成 codemode 版本文本
13
+ // (codemode/cordis.patch.yml L75-86 末段无 run_code 句)。本文件照抄 flash 原文。
14
+
15
+ /** plan-mode v1 政策段全文(上游 L97-107 原文)。 */
16
+ export const PLAN_MODE_SECTION = [
17
+ 'You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user\'s conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.',
18
+ '',
19
+ 'Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.',
20
+ '',
21
+ 'The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode.',
22
+ '',
23
+ 'Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out.',
24
+ '',
25
+ 'Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions.',
26
+ '',
27
+ 'When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask "should I proceed?" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation. If a review (or an ask_user_question) is aborted or times out, that is not a rejection either: do not resubmit on your own and do not switch modes yourself - tell the user it timed out and wait. Under programmatic tool mode exit_plan_mode (and ask_user_question) is reached through run_code: make it the program\'s only call and pass timeoutMs: 600000, because the run_code deadline includes the time the user spends reading the plan.',
28
+ ].join('\n');
29
+
30
+ /** planning 组行的骨架(isolate.planMode 与上游一致;组内行由 frag-lean.patch.yml 展开)。 */
31
+ export const PLANNING_GROUP_ISOLATE = Object.freeze({ planMode: true });
@@ -0,0 +1,75 @@
1
+ // dsh-lean-router · lib/lean/pruner.js —— 机制 2 · 工具输出裁剪(参数 + marker + 纯函数端口)
2
+ //
3
+ // 口径来源(lean 口径照抄 flash 实测,约束台账 v1 第 2 条):
4
+ // 上游 D:\Agent Workspace\.scratch\upstream\flash-presets\presets\flash-lean-ptc-v3.patch.yml
5
+ // L129-133(balance 档 L87-91 同值):thresholdChars 8192 / headChars 4096 / tailChars 1024。
6
+ // 裁剪机理(头=结构、尾=结论、中段=重复;中段替换为固定 marker):
7
+ // docs/技术文档-省token四机制.md L71-113。
8
+ // marker 与不变量镜像宿主:
9
+ // D:\Deepseek Harness\resources\app.asar\dsh\node_modules\@deepseek-ai\dsh-compaction-tool-result-pruner\lib\index.js
10
+ // L8(PRUNE_MARKER 原文)、L10-14(默认值)、L25-27(codePointLength 按码点计)、
11
+ // L43-44(headChars + marker + tailChars 必须 <= thresholdChars,否则抛错)、
12
+ // L91-124(pruneContent:按码点切,不拆代理对)。
13
+ // 零依赖:纯函数,任何环境可独立加载。
14
+ //
15
+ // 注意:执行由宿主 @deepseek-ai/dsh-compaction-tool-result-pruner 完成;本模块的 pruneText
16
+ // 是同判据的纯函数端口,供单测与 config 预检复用,不写会话。
17
+
18
+ /** 宿主 PRUNE_MARKER 原文(dsh-compaction-tool-result-pruner L8)。 */
19
+ export const PRUNE_MARKER = '\n\n[... tool result middle pruned ...]\n\n';
20
+
21
+ /** flash lean 实测口径的裁剪配置(frag-lean.patch.yml tool-result-pruner 行的数据源)。 */
22
+ export const LEAN_PRUNER_CONFIG = Object.freeze({
23
+ thresholdChars: 8192,
24
+ headChars: 4096,
25
+ tailChars: 1024,
26
+ });
27
+
28
+ /** 按 Unicode 码点计数(不拆代理对;镜像宿主 codePointLength L25-27)。 */
29
+ export function codePointLength(text) {
30
+ return Array.from(text).length;
31
+ }
32
+
33
+ /**
34
+ * 镜像宿主 resolveConfig(L33-46):未知键拒绝、整数性、以及
35
+ * headChars + marker 码点 + tailChars <= thresholdChars 的硬不变量。
36
+ */
37
+ export function validatePrunerConfig(config) {
38
+ for (const key of Object.keys(config)) {
39
+ if (key !== 'thresholdChars' && key !== 'headChars' && key !== 'tailChars') {
40
+ throw new Error('ToolResultPruneConfig: unknown key "' + key + '" (allowed: thresholdChars, headChars, tailChars)');
41
+ }
42
+ }
43
+ const resolved = {
44
+ thresholdChars: config.thresholdChars ?? LEAN_PRUNER_CONFIG.thresholdChars,
45
+ headChars: config.headChars ?? LEAN_PRUNER_CONFIG.headChars,
46
+ tailChars: config.tailChars ?? LEAN_PRUNER_CONFIG.tailChars,
47
+ };
48
+ if (!Number.isInteger(resolved.thresholdChars) || resolved.thresholdChars <= 0) {
49
+ throw new Error('ToolResultPruneConfig: thresholdChars must be a positive integer');
50
+ }
51
+ for (const name of ['headChars', 'tailChars']) {
52
+ if (!Number.isInteger(resolved[name]) || resolved[name] < 0) {
53
+ throw new Error('ToolResultPruneConfig: ' + name + ' must be a non-negative integer');
54
+ }
55
+ }
56
+ const emitted = resolved.headChars + codePointLength(PRUNE_MARKER) + resolved.tailChars;
57
+ if (emitted > resolved.thresholdChars) {
58
+ throw new Error('ToolResultPruneConfig: headChars + marker + tailChars (' + emitted + ') must be at most thresholdChars (' + resolved.thresholdChars + ')');
59
+ }
60
+ return Object.freeze(resolved);
61
+ }
62
+
63
+ /**
64
+ * pruneText:单条文本超出 thresholdChars 时保留头 headChars + marker + 尾 tailChars。
65
+ * 与宿主 pruneContent(L91-124)同判据:码点切分、不拆代理对;未超阈值返回 null。
66
+ * @returns 裁剪后的文本;未超阈值返回 null。
67
+ */
68
+ export function pruneText(text, config) {
69
+ const cfg = validatePrunerConfig({ ...LEAN_PRUNER_CONFIG, ...(config ?? {}) });
70
+ const points = Array.from(text);
71
+ if (points.length <= cfg.thresholdChars) return null;
72
+ const head = points.slice(0, cfg.headChars).join('');
73
+ const tail = points.slice(points.length - cfg.tailChars).join('');
74
+ return head + PRUNE_MARKER + tail;
75
+ }