dsh-lean-router 2.1.1 → 2.2.0

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.
@@ -0,0 +1,246 @@
1
+ // dsh-lean-router · lib/lean/usage-ledger.js —— 加料件 · live Usage 账本挂载点
2
+ //
3
+ // 背景:lib/token-ledger/live.js 的 createLiveUsageAdapter 已能订阅 session/event、只收
4
+ // 带 usage 的 assistant/message 并按 session/turn/step/seq 去重落账,但此前没有任何地方
5
+ // 调用它,运行时完全不采集。本模块把它挂到宿主 preset:
6
+ // 1. 创建 live adapter(订阅失败由适配器自己 warn 降级,绝不抛);
7
+ // 2. 注册斜杠命令 token-report([session|all]),读账本 + createTokenReport 生成报告;
8
+ // 3. 宿主 dispose 时卸载适配器与订阅,重复卸载幂等。
9
+ // 与 live.js 同口径:所有失败路径只 warn 不抛 —— 账本采集不得破坏宿主。
10
+ // 数据同源:报告字段 = lib/token-ledger/index.js 的 createTokenReport
11
+ // (usage.prompt = input + cacheRead + cacheWrite,五项分项由 normalizeUsage 补零)。
12
+ import { createTokenReport } from '../token-ledger/index.js';
13
+ import { createLiveUsageAdapter } from '../token-ledger/live.js';
14
+
15
+ export const name = 'lean-usage-ledger';
16
+
17
+ const TAG = '[lean-usage-ledger]';
18
+ const COMMAND_NAME = 'token-report';
19
+ const SCOPES = ['session', 'all'];
20
+ // 会话跟踪只服务于 /token-report all,上限与 delivery-gate 的 SESSION_CAP 同量级。
21
+ const SESSION_CAP = 200;
22
+ const EMPTY_HINT = '尚未采集到 usage,可能本会话还没有 assistant/message 事件';
23
+
24
+ function describeError(error) {
25
+ if (error && typeof error.message === 'string') return error.message;
26
+ return String(error);
27
+ }
28
+
29
+ function warn(ctx, message) {
30
+ const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined;
31
+ if (!logger || typeof logger.warn !== 'function') return;
32
+ try {
33
+ logger.warn(TAG + ' ' + message);
34
+ } catch {
35
+ // A logger must never break usage capture.
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 归一化插件配置:只认 `{ enabled?: boolean }`,缺省开启;显式 false 才关闭。
41
+ * 非对象 / 未知键不抛,按默认值继续(配置错误不该让宿主启动失败)。
42
+ */
43
+ export function resolveConfig(config) {
44
+ const source = config && typeof config === 'object' ? config : {};
45
+ return { enabled: source.enabled !== false };
46
+ }
47
+
48
+ /** 从命令 invocation 里取当前会话 id(host 端 agent.session.id;测试可传裸对象)。 */
49
+ function sessionIdOf(invocation) {
50
+ if (invocation === undefined || invocation === null || typeof invocation !== 'object') return null;
51
+ const agent = invocation.agent;
52
+ const candidates = [
53
+ agent && agent.session && agent.session.id,
54
+ agent && agent.sessionId,
55
+ invocation.session && invocation.session.id,
56
+ invocation.sessionId,
57
+ ];
58
+ for (const candidate of candidates) {
59
+ if (typeof candidate === 'string' && candidate.length > 0) return candidate;
60
+ }
61
+ return null;
62
+ }
63
+
64
+ /**
65
+ * 把 createTokenReport 的结果排成命令文本。
66
+ * 必含:记录条数、prompt 总量(input+cacheRead+cacheWrite)、五项分项、最近一条 turn/step/seq。
67
+ * 没有任何记录时返回 success 文案(尚未采集),不返回空串。
68
+ */
69
+ function formatReport(report, { scope = 'session', sessions = [] } = {}) {
70
+ const entries = Array.isArray(report.entries) ? report.entries : [];
71
+ const usage = report.usage ?? {};
72
+ const n = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : 0);
73
+ const where = scope === 'all'
74
+ ? 'all · ' + sessions.length + ' 个会话'
75
+ : 'session · ' + (sessions.length > 0 ? sessions[0] : '未知会话');
76
+ const head = 'token-report · ' + where + ' · 记录 ' + entries.length + ' 条';
77
+ if (entries.length === 0) return head + '\n' + EMPTY_HINT;
78
+ const last = entries[entries.length - 1];
79
+ return [
80
+ head,
81
+ 'prompt 总量 ' + n(usage.prompt) + '(input ' + n(usage.inputTokens) + ' + cacheRead '
82
+ + n(usage.cacheReadTokens) + ' + cacheWrite ' + n(usage.cacheWriteTokens) + ')',
83
+ '分项:input ' + n(usage.inputTokens) + ' · output ' + n(usage.outputTokens)
84
+ + ' · cacheRead ' + n(usage.cacheReadTokens) + ' · cacheWrite ' + n(usage.cacheWriteTokens)
85
+ + ' · reasoning ' + n(usage.reasoningTokens),
86
+ '最近一条:turn ' + n(last.turn) + ' · step ' + n(last.step) + ' · seq ' + n(last.seq),
87
+ ].join('\n');
88
+ }
89
+
90
+ /**
91
+ * 账本运行时:live adapter + 会话跟踪 + token-report handler + dispose。
92
+ *
93
+ * @param ctx - 插件上下文;只用 `on` 与 `logger`。缺 `on` 时适配器自身降级,本模块不抛。
94
+ * @returns `{ adapter, handler, readRecords, dispose, seenSessions }`。
95
+ */
96
+ export function createUsageLedger(ctx) {
97
+ const adapter = createLiveUsageAdapter(ctx);
98
+ const seenSessions = [];
99
+ const seen = new Set();
100
+ let trackerOff = null;
101
+ let disposed = false;
102
+
103
+ // 跟踪出现过的会话,供 `/token-report all` 汇总;与适配器各用一条订阅,互不共享内部状态。
104
+ if (ctx && typeof ctx.on === 'function') {
105
+ try {
106
+ const off = ctx.on('session/event', (session) => {
107
+ const id = session && typeof session.id === 'string' ? session.id : null;
108
+ if (id === null || id.length === 0 || seen.has(id)) return;
109
+ if (seenSessions.length >= SESSION_CAP) {
110
+ seen.delete(seenSessions.shift());
111
+ }
112
+ seen.add(id);
113
+ seenSessions.push(id);
114
+ });
115
+ if (typeof off === 'function') trackerOff = off;
116
+ } catch (error) {
117
+ warn(ctx, 'could not track sessions for ' + COMMAND_NAME + ': ' + describeError(error));
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 按范围读记录:session = 当前会话(取不到会话时退回已跟踪集合);all = 已跟踪 ∪ 当前。
123
+ * 单会话读失败只 warn 跳过,不让一条坏记录毁掉整份报告。
124
+ */
125
+ function readRecords(invocation, scope) {
126
+ const current = sessionIdOf(invocation);
127
+ const sessions = [];
128
+ const push = (id) => {
129
+ if (typeof id === 'string' && id.length > 0 && !sessions.includes(id)) sessions.push(id);
130
+ };
131
+ if (scope === 'all') {
132
+ for (const id of seenSessions) push(id);
133
+ push(current);
134
+ } else if (current !== null) {
135
+ push(current);
136
+ } else {
137
+ for (const id of seenSessions) push(id);
138
+ }
139
+ const records = [];
140
+ for (const id of sessions) {
141
+ try {
142
+ records.push(...adapter.read(id, 0));
143
+ } catch (error) {
144
+ warn(ctx, 'read failed for session ' + id + ': ' + describeError(error));
145
+ }
146
+ }
147
+ return { records, sessions };
148
+ }
149
+
150
+ /** 命令 handler:返回 `{ kind: 'success'|'error', text }`(与 /band 同形态)。 */
151
+ function handler(invocation) {
152
+ if (disposed) return { kind: 'error', text: '/' + COMMAND_NAME + ' 已随插件卸载' };
153
+ const raw = invocation && typeof invocation.rawInput === 'string'
154
+ ? invocation.rawInput.trim().toLowerCase()
155
+ : '';
156
+ const scope = raw.length === 0 ? 'session' : raw;
157
+ if (!SCOPES.includes(scope)) {
158
+ warn(ctx, 'unknown scope "' + raw + '"; expected session or all');
159
+ return { kind: 'error', text: '/' + COMMAND_NAME + ' 未知范围 "' + raw + '",用法:/' + COMMAND_NAME + ' [session|all]' };
160
+ }
161
+ try {
162
+ const collected = readRecords(invocation, scope);
163
+ const report = createTokenReport({ records: collected.records });
164
+ return { kind: 'success', text: formatReport(report, { scope, sessions: collected.sessions }) };
165
+ } catch (error) {
166
+ warn(ctx, 'report failed: ' + describeError(error));
167
+ return { kind: 'error', text: '/' + COMMAND_NAME + ' 生成报告失败:' + describeError(error) };
168
+ }
169
+ }
170
+
171
+ function dispose() {
172
+ if (disposed) return;
173
+ disposed = true;
174
+ try {
175
+ adapter.dispose();
176
+ } catch (error) {
177
+ warn(ctx, 'adapter dispose failed: ' + describeError(error));
178
+ }
179
+ const off = trackerOff;
180
+ trackerOff = null;
181
+ if (typeof off !== 'function') return;
182
+ try {
183
+ off();
184
+ } catch (error) {
185
+ warn(ctx, 'listener dispose failed: ' + describeError(error));
186
+ }
187
+ }
188
+
189
+ return { adapter, handler, readRecords, dispose, seenSessions };
190
+ }
191
+
192
+ /**
193
+ * 插件入口(形态与 lib/lean/delivery-gate.js 的 apply 一致)。
194
+ *
195
+ * enabled: false 时既不订阅 session/event 也不注册命令;宿主在模块加载阶段不会被猜测性采集。
196
+ */
197
+ export function apply(ctx, config) {
198
+ const resolved = resolveConfig(config);
199
+ if (!resolved.enabled) return;
200
+ const ledger = createUsageLedger(ctx);
201
+ const context = ctx && typeof ctx === 'object' ? ctx : {};
202
+ const commands = context.commands;
203
+
204
+ if (commands && typeof commands.register === 'function') {
205
+ try {
206
+ commands.register({
207
+ name: COMMAND_NAME,
208
+ description: 'Report the live Usage ledger captured from assistant/message events',
209
+ input: { hint: '[session|all]' },
210
+ handler: (invocation) => ledger.handler(invocation),
211
+ });
212
+ } catch (error) {
213
+ warn(context, 'could not register /' + COMMAND_NAME + ': ' + describeError(error));
214
+ }
215
+ } else {
216
+ warn(context, 'ctx.commands is unavailable; /' + COMMAND_NAME + ' not registered');
217
+ }
218
+
219
+ // 宿主卸载:优先走 dispose 事件;订阅不到就靠 ctx.effect/宿主自行回收,绝不让挂载失败。
220
+ if (typeof context.on === 'function') {
221
+ try {
222
+ context.on('dispose', () => {
223
+ ledger.dispose();
224
+ });
225
+ } catch (error) {
226
+ warn(context, 'could not hook dispose: ' + describeError(error));
227
+ }
228
+ } else {
229
+ warn(context, 'ctx.on is unavailable; usage-ledger dispose hook disabled');
230
+ }
231
+ }
232
+
233
+ /** 默认导出(插件行兼容形态,与命名导出同体)。 */
234
+ export default { name, apply };
235
+
236
+ /** 测试与集成内用的内部实现出口(不进公开契约文档)。 */
237
+ export const __internals = {
238
+ resolveConfig,
239
+ sessionIdOf,
240
+ formatReport,
241
+ createUsageLedger,
242
+ COMMAND_NAME,
243
+ EMPTY_HINT,
244
+ SESSION_CAP,
245
+ TAG,
246
+ };
@@ -2,6 +2,7 @@
2
2
  * [vendored @ upstream dsh-codemode 0.3.x main f9758ec1061a9a0af4f1dfefbacc19c5987b11d1]
3
3
  * Source: upstream lib/discovery.js (dsh-codemode 0.3.0, main @ f9758ec).
4
4
  * Vendored for dsh-lean-router ticket-04, file-for-file unchanged; the four meta tools (list/search/describe/debug), their definitions and the registry-public reads are unchanged.
5
+ * Deviation from upstream: this fork returns parameter NAMES (`params`) from search and keeps the full JSON parameter schema on describe only (lazy schema fetch).
5
6
  *
6
7
  * The three discovery tools registered inside the codemode preset scope.
7
8
  *
@@ -34,6 +35,17 @@ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true };
34
35
  /** Upper bound on rows a single call materializes, so a 300-tool server cannot blow up a program. */
35
36
  const MAX_ROWS = 2000;
36
37
 
38
+ /**
39
+ * Parameter NAMES for one definition, in declaration order, or `undefined` when
40
+ * the schema declares no `properties` at all — the caller then says `noParams`
41
+ * so a free-form argument object is not mistaken for "takes no arguments".
42
+ */
43
+ function parameterNames(parameters) {
44
+ const properties = parameters?.properties;
45
+ if (properties === null || typeof properties !== 'object' || Array.isArray(properties)) return undefined;
46
+ return Object.keys(properties);
47
+ }
48
+
37
49
  /** Render a JSON value as one text block. */
38
50
  function renderJson(value) {
39
51
  const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
@@ -125,7 +137,7 @@ export function createDiscoveryTools(ctx, options, runToolName = DEFAULT_RUN_TOO
125
137
  description:
126
138
  `List every tool this session can call from inside ${runToolName}, including the ones masked out of the `
127
139
  + 'model context (MCP tools, tools contributed by plugins outside this preset). Returns name, truncated '
128
- + 'description, namespace and a hidden flag — no schemas. Use the search tool to obtain parameter schemas.',
140
+ + 'description, namespace and a hidden flag — no schemas. Use the search tool for parameter names, then describe for a full schema.',
129
141
  parameters: {
130
142
  type: 'object',
131
143
  additionalProperties: false,
@@ -158,8 +170,9 @@ export function createDiscoveryTools(ctx, options, runToolName = DEFAULT_RUN_TOO
158
170
  {
159
171
  name: searchName,
160
172
  description:
161
- 'Rank the callable tools against a query and return the best matches WITH their full JSON parameter '
162
- + `schemas. This is the intended first step before calling a tool the model cannot see from inside ${runToolName}.`,
173
+ 'Rank the callable tools against a query and return the best matches with their parameter NAMES, not their '
174
+ + `full JSON schemas; call ${describeName} with a match's name for its complete parameter schema. This is the `
175
+ + `intended first step before calling a tool the model cannot see from inside ${runToolName}.`,
163
176
  parameters: {
164
177
  type: 'object',
165
178
  additionalProperties: false,
@@ -188,14 +201,16 @@ export function createDiscoveryTools(ctx, options, runToolName = DEFAULT_RUN_TOO
188
201
  return {
189
202
  query,
190
203
  count: ranked.length,
191
- tools: ranked.map((row) => ({
192
- name: row.name,
193
- description: truncate(row.description, options.maxDescriptionChars * 2),
194
- namespace: isMaskedName(row.name, options, view) ? namespaceOf(row.name) : 'native',
195
- hidden: isMaskedName(row.name, options, view),
196
- parameters: row.definition.parameters ?? { type: 'object', additionalProperties: true },
197
- output: row.definition.output?.schema,
198
- })),
204
+ tools: ranked.map((row) => {
205
+ const names = parameterNames(row.definition.parameters);
206
+ return {
207
+ name: row.name,
208
+ description: truncate(row.description, options.maxDescriptionChars * 2),
209
+ namespace: isMaskedName(row.name, options, view) ? namespaceOf(row.name) : 'native',
210
+ hidden: isMaskedName(row.name, options, view),
211
+ ...(names === undefined ? { noParams: true } : { params: names }),
212
+ };
213
+ }),
199
214
  };
200
215
  },
201
216
  },
@@ -366,9 +366,10 @@ export function buildCodemodeSectionText(input) {
366
366
  lines.push('');
367
367
  lines.push('```js');
368
368
  lines.push(`const { tools: hits } = await tools.${searchTool}({ query: "what you need", limit: ${searchLimit} })`);
369
+ lines.push(`const { parameters } = await tools.${describeTool}({ name: hits[0].name }); // only when the parameter names are not enough`);
369
370
  lines.push(retained
370
- ? 'await tools[hits[0].name]({ /* args from hits[0].parameters */ })'
371
- : 'return await tools[hits[0].name]({ /* args from hits[0].parameters */ })');
371
+ ? 'await tools[hits[0].name]({ /* args from parameters */ })'
372
+ : 'return await tools[hits[0].name]({ /* args from parameters */ })');
372
373
  lines.push('```');
373
374
  } else {
374
375
  lines.push('### Masked tools');
@@ -379,7 +380,7 @@ export function buildCodemodeSectionText(input) {
379
380
  lines.push('### Discovery API');
380
381
  lines.push('');
381
382
  lines.push(`- \`tools.${listTool}({ namespace? })\` — every callable tool, masked ones included: \`{ name, description, namespace, hidden }\`.`);
382
- lines.push(`- \`tools.${searchTool}({ query, limit?, namespace? })\` — ranked matches with full parameter schemas; the intended first step.`);
383
+ lines.push(`- \`tools.${searchTool}({ query, limit?, namespace? })\` — ranked matches with their parameter names; the intended first step, then \`${describeTool}\` for one match's full schema.`);
383
384
  lines.push(`- \`tools.${describeTool}({ name })\` — one tool's description and full parameter schema.`);
384
385
  if (metaTools.length > 3) {
385
386
  lines.push(`- \`tools.${metaTools[3]}({ limit? })\` — what Code Mode masked out of this session, for troubleshooting.`);
@@ -387,7 +388,7 @@ export function buildCodemodeSectionText(input) {
387
388
  lines.push('');
388
389
  lines.push('### Hard rules');
389
390
  lines.push('');
390
- lines.push(`- Never guess a masked tool's name or arguments: call \`${searchTool}\` first, read \`parameters\`, then call it inside a \`${runToolName}\` program.`);
391
+ lines.push(`- Never guess a masked tool's name or arguments: call \`${searchTool}\` for the name and its parameter names, call \`${describeTool}\` when you need the full parameter schema, then call it inside a \`${runToolName}\` program.`);
391
392
  lines.push('- A direct call to a masked tool from outside a program is rejected by the harness.');
392
393
  lines.push(`- The discovery tools are only callable from inside \`${runToolName}\`; they are not in your tool list.`);
393
394
  return lines.join('\n');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lean-router",
3
- "version": "2.1.1",
3
+ "version": "2.2.0",
4
4
  "description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -11,6 +11,7 @@
11
11
  "./toolface": "./lib/toolface/index.js",
12
12
  "./lean/delivery-gate": "./lib/lean/delivery-gate.js",
13
13
  "./lean/tool-concurrency": "./lib/lean/tool-concurrency.js",
14
+ "./lean/usage-ledger": "./lib/lean/usage-ledger.js",
14
15
  "./token-ledger": "./lib/token-ledger/index.js",
15
16
  "./token-ledger/live": "./lib/token-ledger/live.js"
16
17
  },
@@ -31,40 +31,37 @@
31
31
  LEAN OPERATING RULES (hard constraints; they override habit and tool default wording):
32
32
 
33
33
  BUDGET FIRST
34
- 1. Turn budget, not step budget. Target <=20 turns; turns are the measured cost (folding many calls
35
- into one turn is cheap, thrashing across turns is expensive). If a task passes 3x the expected
36
- turns (~60), stop and re-plan instead of repeating the same loop.
37
- 2. Deliberate briefly. Do not enumerate an exhaustive design before acting: one short
38
- deliberation, then run one cheap probe/command to learn the facts. Acting beats more planning.
34
+ 1. Turn budget, not step budget. Target <=20 turns; folding calls into one turn is cheap, thrashing
35
+ across turns is not. Past 3x the expected turns (~60), stop and re-plan instead of looping.
36
+ Re-check roughly every 10 turns that this is still the shortest path; if it is not, re-plan.
37
+ 2. Deliberate briefly. One short deliberation, then one cheap probe/command to learn the facts;
38
+ do not enumerate an exhaustive design before acting.
39
39
  3. Input/answer-type tasks (submit a file or an answer): produce the SMALLEST artifact that
40
40
  satisfies the stated constraints first; refine only while you are under the turn budget.
41
- 4. Gate before delivery, not after. If the task states hidden tests, a judge, or hard limits
42
- (time/memory/output), run ONE consolidated acceptance pass over every stated criterion at once (all
43
- samples, edge cases, largest legal scale) and quote the measured numbers; measure hard limits with
44
- the command the judge would use (/usr/bin/time -v, ulimit -v, ...), and treat over-limit as a failure
45
- even when the answer is otherwise correct. Otherwise ONE consolidated check per deliverable is enough:
46
- do not verify claim by claim, do not re-run a check that already passed, and name what you did not
47
- verify. Once the gate passes, stop testing and deliver: do not add extra randomized or stress rounds unless the gate itself failed.
41
+ 4. Gate before delivery, not after. Run ONE consolidated acceptance pass over every stated
42
+ criterion, quote the measured numbers, and name what you did not verify. Measure hard limits
43
+ with the command the judge would use (/usr/bin/time -v, ulimit -v). Over-limit is a failure even
44
+ when the answer is otherwise correct. Do not verify claim by claim, do not re-run a check that
45
+ already passed, and once the gate passes stop testing and deliver.
48
46
 
49
47
  5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
50
- (no cat/head/tail/sed -n/find/ls -R); piping a command's own output through head is fine.
51
- 6. Output budget. Batch independent calls into one step. Pipe or redirect long output
52
- (| head -40; redirect to "$env:TEMP/out.log" in PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
48
+ (no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
49
+ 6. Output budget. Batch independent calls into one step; pipe or redirect long output
50
+ (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
53
51
  Never print a dump you could grep.
54
52
  7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
55
- run_code program; a single-call step may still go through a one-line program so its noise stays
56
- out of context. Measured: folding pays off on multi-file/repo work (up to 8x fewer turns, 2-8x
57
- less wall clock) and is neutral on single-file algorithm tasks - there spend the budget on
58
- reasoning and testing, not on batching.
59
- 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived
60
- answers from files with grep/scripts instead of re-reading them into context. Keep NOTES
61
- short and factual (<=60 lines).
62
- 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never
63
- re-emit an unchanged file. After two failed shell patches, switch to the editor.
53
+ run_code program; a single call may still go through a one-line program so its noise stays out
54
+ of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
55
+ single-file algorithm tasks - there spend the budget on reasoning and testing, not batching.
56
+ 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived answers
57
+ from files with grep/scripts instead of re-reading them into context. Keep NOTES short and
58
+ factual (<=60 lines).
59
+ 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never re-emit an
60
+ unchanged file. After two failed shell patches, switch to the editor.
64
61
 
65
62
  SAFETY
66
- 10. Answer in the user's language. Honour scope literally (new project => do not read or
67
- copy old-project files). Use subagents only when the user asks or the harness delegates; never spawn them to look busy.
63
+ 10. Honour scope literally (a new project means do not read or copy old-project files). Use
64
+ subagents only when the user asks or the harness delegates; never spawn them to look busy.
68
65
  11. Never put secrets, tokens or private raw material into the session; reference by path.
69
66
 
70
67
  WHEN BLOCKED
@@ -74,13 +71,11 @@
74
71
  prefer fewer, larger turns; on a low-latency route more probing is affordable. Never trade
75
72
  correctness for turn count.
76
73
 
77
- SOFT GATES (clarify -> plan -> deliver; each is one pause, never a stall)
74
+ SOFT GATES (each is one pause, never a stall)
78
75
  - 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.
79
- - PLAN: work touching more than one file or more than ~8 steps starts from a numbered plan with a check per step; single-file small changes skip this gate.
80
- - DELIVER: run ONE consolidated acceptance pass over every stated criterion, quote measured numbers, name what was not verified, then stop (rule 4 is this gate's detail).
76
+ - 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.
81
77
 
82
78
  SELF-CHECK HOOKS (questions answered to yourself; speak up only when a check fails)
83
- - Diligence (~every 10 turns): what changed since the last check, and is this still the shortest path to done? If not, re-plan; do not repeat the loop.
84
79
  - 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.
85
80
 
86
81
  # [ticket-05] 路由分类指令由票 05 拼接(本行为占位:集成时替换为票 05 的 ROUTER_PROMPT 常量)
@@ -434,3 +429,15 @@
434
429
  config:
435
430
  toolConcurrency:
436
431
  enabled: true
432
+
433
+ # ============ 新增行:live Usage 账本挂载点(加料件)============
434
+ # 默认开启:订阅 session/event,采集带 usage 的 assistant/message(lib/token-ledger/live.js)。
435
+ # 斜杠命令 token-report([session|all])读账本,输出记录条数、prompt 总量、五项分项与最近一条 turn/step/seq;
436
+ # 无记录时返回 success 并提示尚未采集。插件实现 = lib/lean/usage-ledger.js;
437
+ # 插件行 name 为包内子路径,需 package.json exports 增加 ./lean/usage-ledger(master 集成)。
438
+
439
+ - insert:
440
+ - id: lean-usage-ledger
441
+ name: 'dsh-lean-router/lean/usage-ledger'
442
+ config:
443
+ enabled: true
@@ -21,40 +21,37 @@
21
21
  LEAN OPERATING RULES (hard constraints; they override habit and tool default wording):
22
22
 
23
23
  BUDGET FIRST
24
- 1. Turn budget, not step budget. Target <=20 turns; turns are the measured cost (folding many calls
25
- into one turn is cheap, thrashing across turns is expensive). If a task passes 3x the expected
26
- turns (~60), stop and re-plan instead of repeating the same loop.
27
- 2. Deliberate briefly. Do not enumerate an exhaustive design before acting: one short
28
- deliberation, then run one cheap probe/command to learn the facts. Acting beats more planning.
24
+ 1. Turn budget, not step budget. Target <=20 turns; folding calls into one turn is cheap, thrashing
25
+ across turns is not. Past 3x the expected turns (~60), stop and re-plan instead of looping.
26
+ Re-check roughly every 10 turns that this is still the shortest path; if it is not, re-plan.
27
+ 2. Deliberate briefly. One short deliberation, then one cheap probe/command to learn the facts;
28
+ do not enumerate an exhaustive design before acting.
29
29
  3. Input/answer-type tasks (submit a file or an answer): produce the SMALLEST artifact that
30
30
  satisfies the stated constraints first; refine only while you are under the turn budget.
31
- 4. Gate before delivery, not after. If the task states hidden tests, a judge, or hard limits
32
- (time/memory/output), run ONE consolidated acceptance pass over every stated criterion at once (all
33
- samples, edge cases, largest legal scale) and quote the measured numbers; measure hard limits with
34
- the command the judge would use (/usr/bin/time -v, ulimit -v, ...), and treat over-limit as a failure
35
- even when the answer is otherwise correct. Otherwise ONE consolidated check per deliverable is enough:
36
- do not verify claim by claim, do not re-run a check that already passed, and name what you did not
37
- verify. Once the gate passes, stop testing and deliver: do not add extra randomized or stress rounds unless the gate itself failed.
31
+ 4. Gate before delivery, not after. Run ONE consolidated acceptance pass over every stated
32
+ criterion, quote the measured numbers, and name what you did not verify. Measure hard limits
33
+ with the command the judge would use (/usr/bin/time -v, ulimit -v). Over-limit is a failure even
34
+ when the answer is otherwise correct. Do not verify claim by claim, do not re-run a check that
35
+ already passed, and once the gate passes stop testing and deliver.
38
36
 
39
37
  5. Tool choice. Inspect files with read/glob/grep; never use the shell to browse a file
40
- (no cat/head/tail/sed -n/find/ls -R); piping a command's own output through head is fine.
41
- 6. Output budget. Batch independent calls into one step. Pipe or redirect long output
42
- (| head -40; redirect to "$env:TEMP/out.log" in PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
38
+ (no cat/head/tail/sed -n/find/ls -R). Piping a command's own output through head is fine.
39
+ 6. Output budget. Batch independent calls into one step; pipe or redirect long output
40
+ (| head -40; redirect to $env:TEMP/out.log on PowerShell, %TEMP%\out.log in cmd, /tmp/out.log on POSIX).
43
41
  Never print a dump you could grep.
44
42
  7. Programmatic tool mode, adaptively. Fold 3+ independent calls of one logical step into ONE
45
- run_code program; a single-call step may still go through a one-line program so its noise stays
46
- out of context. Measured: folding pays off on multi-file/repo work (up to 8x fewer turns, 2-8x
47
- less wall clock) and is neutral on single-file algorithm tasks - there spend the budget on
48
- reasoning and testing, not on batching.
49
- 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived
50
- answers from files with grep/scripts instead of re-reading them into context. Keep NOTES
51
- short and factual (<=60 lines).
52
- 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never
53
- re-emit an unchanged file. After two failed shell patches, switch to the editor.
43
+ run_code program; a single call may still go through a one-line program so its noise stays out
44
+ of context. Measured: pays off on multi-file/repo work (up to 8x fewer turns) and is neutral on
45
+ single-file algorithm tasks - there spend the budget on reasoning and testing, not batching.
46
+ 8. Context discipline (biggest measured lever). Read only what is new; rebuild derived answers
47
+ from files with grep/scripts instead of re-reading them into context. Keep NOTES short and
48
+ factual (<=60 lines).
49
+ 9. Author incrementally: create a file once (skeleton), then extend it with edit. Never re-emit an
50
+ unchanged file. After two failed shell patches, switch to the editor.
54
51
 
55
52
  SAFETY
56
- 10. Answer in the user's language. Honour scope literally (new project => do not read or
57
- copy old-project files). Use subagents only when the user asks or the harness delegates; never spawn them to look busy.
53
+ 10. Honour scope literally (a new project means do not read or copy old-project files). Use
54
+ subagents only when the user asks or the harness delegates; never spawn them to look busy.
58
55
  11. Never put secrets, tokens or private raw material into the session; reference by path.
59
56
 
60
57
  WHEN BLOCKED
@@ -64,13 +61,11 @@
64
61
  prefer fewer, larger turns; on a low-latency route more probing is affordable. Never trade
65
62
  correctness for turn count.
66
63
 
67
- SOFT GATES (clarify -> plan -> deliver; each is one pause, never a stall)
64
+ SOFT GATES (each is one pause, never a stall)
68
65
  - 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.
69
- - PLAN: work touching more than one file or more than ~8 steps starts from a numbered plan with a check per step; single-file small changes skip this gate.
70
- - DELIVER: run ONE consolidated acceptance pass over every stated criterion, quote measured numbers, name what was not verified, then stop (rule 4 is this gate's detail).
66
+ - 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.
71
67
 
72
68
  SELF-CHECK HOOKS (questions answered to yourself; speak up only when a check fails)
73
- - Diligence (~every 10 turns): what changed since the last check, and is this still the shortest path to done? If not, re-plan; do not repeat the loop.
74
69
  - 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.
75
70
 
76
71
  Routing: before acting on any new task, classify it - (build) create something new end-to-end, or (fix) diagnose and repair something broken - then adopt the matching style: build -> hands-on production; fix -> inspect-and-plan.