dsh-lean-router 2.2.6 → 2.2.7

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.
@@ -1,6 +1,18 @@
1
1
  # Changelog
2
2
 
3
- > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.6).
3
+ > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.2.7).
4
+
5
+ ## 2.2.7 (2026-11-30)
6
+
7
+ ### Added
8
+
9
+ - **Ledger snapshot on disk**: after recording one usage entry, the ledger atomically writes an aggregate to `<DSH_HOME>/storages/lean-router/token-report.json` (`DSH_HOME` defaults to `~/.dsh`; override with `config.snapshotPath`, disable with `config.snapshot: false`). The agent can now `read` the same data the command shows instead of asking the user to copy it. The snapshot holds totals plus per-session records/prompt/input/cacheRead/cacheWrite/output/reasoning and the latest turn/step/seq.
10
+ - **`/token-report json` scope**: the command gains `json`, which prints the snapshot file content byte for byte; a missing file yields `{"error":"snapshot missing","path":"..."}`. The `session` and `all` text formats are unchanged.
11
+ - Writes are atomic (`.tmp` then rename) and the directory is created on demand; any write failure warns once and never affects recording or the command.
12
+
13
+ ### Tests
14
+
15
+ - 6 new cases (default path and config resolution, single-record shape, cross-session aggregation, disable switch, write failure not throwing, `json` matching the file bytes); the full suite is 269 tests, 268 passing, 0 failing, 1 skipped.
4
16
 
5
17
  ## 2.2.6 (2026-11-29)
6
18
 
package/docs/changelog.md CHANGED
@@ -1,6 +1,18 @@
1
1
  # 变更记录(changelog)
2
2
 
3
- > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.6)。
3
+ > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.2.7)。
4
+
5
+ ## 2.2.7 (2026-11-30)
6
+
7
+ ### 新增
8
+
9
+ - **账本快照落盘**:账本每记录一条 usage,就把汇总原子写入 `<DSH_HOME>/storages/lean-router/token-report.json`(`DSH_HOME` 缺省为 `~/.dsh`;可用 `config.snapshotPath` 覆盖路径、`config.snapshot: false` 关闭)。这样代理用 `read` 就能直接读到与命令同源的数据,不必再由用户复制粘贴。快照含 totals 与按会话聚合的 records/prompt/input/cacheRead/cacheWrite/output/reasoning 及最近 turn/step/seq。
10
+ - **`/token-report json` 口径**:命令新增 `json`,直接输出快照文件内容(与文件字节一致);文件不存在时返回 `{"error":"snapshot missing","path":"..."}`。`session` 与 `all` 的文本格式不变。
11
+ - 写入是原子的(先写 `.tmp` 再 rename),目录自动创建;任何写入失败只 warn 一次,不影响记录与命令。
12
+
13
+ ### 测试
14
+
15
+ - 新增 6 项(默认路径与配置解析、单条记录结构、跨会话聚合、关闭开关、写失败不抛、`json` 与文件字节一致);全量 269 项、268 通过、0 失败、1 skip。
4
16
 
5
17
  ## 2.2.6 (2026-11-29)
6
18
 
@@ -4,11 +4,19 @@
4
4
  // 带 usage 的 assistant/message 并按 session/turn/step/seq 去重落账,但此前没有任何地方
5
5
  // 调用它,运行时完全不采集。本模块把它挂到宿主 preset:
6
6
  // 1. 创建 live adapter(订阅失败由适配器自己 warn 降级,绝不抛);
7
- // 2. 注册斜杠命令 token-report([session|all]),读账本 + createTokenReport 生成报告;
8
- // 3. 宿主 dispose 时卸载适配器与订阅,重复卸载幂等。
7
+ // 2. 注册斜杠命令 token-report([session|all|json]),读账本 + createTokenReport 生成报告;
8
+ // json 口径直接回放落盘快照,人和代理读到同一份数据;
9
+ // 3. 每真正记录一条 usage 就把「totals + 各会话聚合」原子写进
10
+ // <DSH_HOME>/storages/lean-router/token-report.json(config.snapshotPath 可改路径,
11
+ // config.snapshot === false 可关),写失败只 warn 一次,绝不影响采集与命令;
12
+ // 4. 宿主 dispose 时卸载适配器与订阅,重复卸载幂等。
9
13
  // 与 live.js 同口径:所有失败路径只 warn 不抛 —— 账本采集不得破坏宿主。
10
14
  // 数据同源:报告字段 = lib/token-ledger/index.js 的 createTokenReport
11
15
  // (usage.prompt = input + cacheRead + cacheWrite,五项分项由 normalizeUsage 补零)。
16
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
19
+
12
20
  import { createTokenReport } from '../token-ledger/index.js';
13
21
  import { createLiveUsageAdapter } from '../token-ledger/live.js';
14
22
 
@@ -22,10 +30,27 @@ export const inject = ['commands'];
22
30
 
23
31
  const TAG = '[lean-usage-ledger]';
24
32
  const COMMAND_NAME = 'token-report';
25
- const SCOPES = ['session', 'all'];
33
+ const SCOPES = ['session', 'all', 'json'];
26
34
  // 会话跟踪只服务于 /token-report all,上限与 delivery-gate 的 SESSION_CAP 同量级。
27
35
  const SESSION_CAP = 200;
28
36
  const EMPTY_HINT = '尚未采集到 usage,可能本会话还没有 assistant/message 事件';
37
+ const SNAPSHOT_SUBDIR = ['storages', 'lean-router'];
38
+ const SNAPSHOT_FILE = 'token-report.json';
39
+ const SNAPSHOT_TMP_SUFFIX = '.tmp';
40
+ // usage 分项 → 快照字段;prompt 恒为 input + cacheRead + cacheWrite(与 createTokenReport 同口径)。
41
+ const SNAPSHOT_FIELDS = [
42
+ ['input', 'inputTokens'],
43
+ ['cacheRead', 'cacheReadTokens'],
44
+ ['cacheWrite', 'cacheWriteTokens'],
45
+ ['output', 'outputTokens'],
46
+ ['reasoning', 'reasoningTokens'],
47
+ ];
48
+ // 写盘/读盘失败的告警按「用途 + 路径」模块级去重:一个坏路径只响一次,绝不随事件刷屏。
49
+ const warnedSnapshotFailures = new Set();
50
+
51
+ function toNumber(value) {
52
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
53
+ }
29
54
 
30
55
  function describeError(error) {
31
56
  if (error && typeof error.message === 'string') return error.message;
@@ -42,13 +67,107 @@ function warn(ctx, message) {
42
67
  }
43
68
  }
44
69
 
70
+ /** 同一条失败只 warn 一次(模块级去重)。 */
71
+ function warnSnapshotOnce(ctx, key, message) {
72
+ if (warnedSnapshotFailures.has(key)) return;
73
+ warnedSnapshotFailures.add(key);
74
+ warn(ctx, message);
75
+ }
76
+
77
+ /** <DSH_HOME>:优先环境变量,退回 ~/.dsh;两者都拿不到时用相对目录,仍不抛。 */
78
+ function dshHome() {
79
+ const fromEnv = process.env.DSH_HOME;
80
+ if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return fromEnv.trim();
81
+ try {
82
+ return join(homedir(), '.dsh');
83
+ } catch {
84
+ return '.dsh';
85
+ }
86
+ }
87
+
88
+ /**
89
+ * 快照落盘路径:`config.snapshotPath`(非空字符串)优先,相对路径按 cwd 解析;
90
+ * 否则 `<DSH_HOME>/storages/lean-router/token-report.json`。读取时取值,便于测试与配置热改。
91
+ */
92
+ export function resolveSnapshotPath(configured) {
93
+ if (typeof configured === 'string' && configured.trim().length > 0) {
94
+ const raw = configured.trim();
95
+ return isAbsolute(raw) ? raw : resolve(raw);
96
+ }
97
+ return join(dshHome(), ...SNAPSHOT_SUBDIR, SNAPSHOT_FILE);
98
+ }
99
+
100
+ function emptyStats() {
101
+ return {
102
+ records: 0,
103
+ prompt: 0,
104
+ input: 0,
105
+ cacheRead: 0,
106
+ cacheWrite: 0,
107
+ output: 0,
108
+ reasoning: 0,
109
+ };
110
+ }
111
+
112
+ function compareRecords(left, right) {
113
+ return toNumber(left.turn) - toNumber(right.turn)
114
+ || toNumber(left.step) - toNumber(right.step)
115
+ || toNumber(left.seq) - toNumber(right.seq);
116
+ }
117
+
45
118
  /**
46
- * 归一化插件配置:只认 `{ enabled?: boolean }`,缺省开启;显式 false 才关闭。
119
+ * 把一个会话的记录聚合成快照里的一条 stats。
120
+ * 键序与快照契约一致(updatedAt 由 buildSnapshotPayload 追加);没有记录时 records 为 0。
121
+ */
122
+ export function summarizeRecords(records) {
123
+ const stats = emptyStats();
124
+ let latest = null;
125
+ for (const record of Array.isArray(records) ? records : []) {
126
+ if (!record || typeof record !== 'object') continue;
127
+ stats.records += 1;
128
+ const usage = record.usage && typeof record.usage === 'object' ? record.usage : {};
129
+ for (const [key, field] of SNAPSHOT_FIELDS) stats[key] += toNumber(usage[field]);
130
+ if (latest === null || compareRecords(record, latest) >= 0) latest = record;
131
+ }
132
+ stats.prompt = stats.input + stats.cacheRead + stats.cacheWrite;
133
+ const lastTurn = latest === null ? 0 : toNumber(latest.turn);
134
+ const lastStep = latest === null ? 0 : toNumber(latest.step);
135
+ const lastSeq = latest === null ? 0 : toNumber(latest.seq);
136
+ return { ...stats, lastTurn, lastStep, lastSeq };
137
+ }
138
+
139
+ /** 由各会话 stats 合成快照 payload:totals 为重算值,sessions 保留每会话聚合。 */
140
+ export function buildSnapshotPayload(statsById, updatedAt) {
141
+ const totals = emptyStats();
142
+ const sessions = {};
143
+ for (const [id, stats] of Object.entries(statsById ?? {})) {
144
+ sessions[id] = { ...stats, updatedAt };
145
+ totals.records += stats.records;
146
+ for (const [key] of SNAPSHOT_FIELDS) totals[key] += stats[key];
147
+ }
148
+ totals.prompt = totals.input + totals.cacheRead + totals.cacheWrite;
149
+ return { updatedAt, totals, sessions };
150
+ }
151
+
152
+ /** 原子写:先写 <path>.tmp 再 rename 覆盖,读者不会看到半截文件。目录缺失自动创建。 */
153
+ function writeSnapshotFile(file, payload) {
154
+ const tmp = file + SNAPSHOT_TMP_SUFFIX;
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\n', 'utf8');
157
+ renameSync(tmp, file);
158
+ }
159
+
160
+ /**
161
+ * 归一化插件配置:只认 `{ enabled?, snapshot?, snapshotPath? }`,缺省全开;显式 false 才关闭。
47
162
  * 非对象 / 未知键不抛,按默认值继续(配置错误不该让宿主启动失败)。
48
163
  */
49
164
  export function resolveConfig(config) {
50
165
  const source = config && typeof config === 'object' ? config : {};
51
- return { enabled: source.enabled !== false };
166
+ return {
167
+ enabled: source.enabled !== false,
168
+ snapshot: source.snapshot !== false,
169
+ snapshotPath: resolveSnapshotPath(source.snapshotPath),
170
+ };
52
171
  }
53
172
 
54
173
  /** 从命令 invocation 里取当前会话 id(host 端 agent.session.id;测试可传裸对象)。 */
@@ -94,13 +213,16 @@ function formatReport(report, { scope = 'session', sessions = [] } = {}) {
94
213
  }
95
214
 
96
215
  /**
97
- * 账本运行时:live adapter + 会话跟踪 + token-report handler + dispose。
216
+ * 账本运行时:live adapter + 会话跟踪 + 快照落盘 + token-report handler + dispose。
98
217
  *
99
218
  * @param ctx - 插件上下文;只用 `on` 与 `logger`。缺 `on` 时适配器自身降级,本模块不抛。
100
- * @returns `{ adapter, handler, readRecords, dispose, seenSessions }`。
219
+ * @param config - 插件配置;这里只关心 `snapshot` / `snapshotPath`(`enabled` 由 apply 判断)。
220
+ * @returns `{ adapter, handler, readRecords, writeSnapshot, dispose, seenSessions, snapshotPath }`。
101
221
  */
102
- export function createUsageLedger(ctx) {
103
- const adapter = createLiveUsageAdapter(ctx);
222
+ export function createUsageLedger(ctx, config) {
223
+ const settings = resolveConfig(config);
224
+ const snapshotPath = settings.snapshotPath;
225
+ const snapshotEnabled = settings.snapshot;
104
226
  const seenSessions = [];
105
227
  const seen = new Set();
106
228
  let trackerOff = null;
@@ -124,6 +246,70 @@ export function createUsageLedger(ctx) {
124
246
  }
125
247
  }
126
248
 
249
+ // onRecord 只在 live.js 真正新增一条记录后回调,事件过滤口径与账本完全同源。
250
+ const adapter = createLiveUsageAdapter(ctx, {
251
+ onRecord: (record) => {
252
+ writeSnapshot(record);
253
+ },
254
+ });
255
+
256
+ /**
257
+ * 把账本汇总原子落盘,供代理自己读(`/token-report json` 与它同源)。
258
+ * 只在确实记录了一条 usage 时写;失败只 warn 一次,绝不抛、不影响记录与命令。
259
+ */
260
+ function writeSnapshot(trigger) {
261
+ if (!snapshotEnabled || disposed) return;
262
+ try {
263
+ const ids = [];
264
+ const push = (id) => {
265
+ if (typeof id === 'string' && id.length > 0 && !ids.includes(id)) ids.push(id);
266
+ };
267
+ for (const id of seenSessions) push(id);
268
+ // 新会话的首条事件里跟踪订阅可能还没跑(适配器先订阅),显式补上触发者。
269
+ if (trigger && typeof trigger === 'object') push(trigger.sessionId);
270
+
271
+ const updatedAt = new Date().toISOString();
272
+ const statsById = {};
273
+ for (const id of ids) {
274
+ let records = [];
275
+ try {
276
+ records = adapter.read(id, 0);
277
+ } catch (error) {
278
+ warn(ctx, 'snapshot read failed for session ' + id + ': ' + describeError(error));
279
+ continue;
280
+ }
281
+ const stats = summarizeRecords(records);
282
+ if (stats.records === 0) continue;
283
+ statsById[id] = stats;
284
+ }
285
+ writeSnapshotFile(snapshotPath, buildSnapshotPayload(statsById, updatedAt));
286
+ } catch (error) {
287
+ warnSnapshotOnce(
288
+ ctx,
289
+ 'write:' + snapshotPath,
290
+ 'snapshot write failed (' + snapshotPath + '): ' + describeError(error),
291
+ );
292
+ }
293
+ }
294
+
295
+ /** `json` 口径:回放落盘快照原文;缺失或读不出时给代理一个可解析的错误 JSON。 */
296
+ function readSnapshotText() {
297
+ try {
298
+ const text = readFileSync(snapshotPath, 'utf8');
299
+ if (typeof text === 'string' && text.trim().length > 0) return text;
300
+ } catch (error) {
301
+ // 文件还没写过是最常见的正常状态,不为 ENOENT 记告警。
302
+ if (!error || error.code !== 'ENOENT') {
303
+ warnSnapshotOnce(
304
+ ctx,
305
+ 'read:' + snapshotPath,
306
+ 'snapshot read failed (' + snapshotPath + '): ' + describeError(error),
307
+ );
308
+ }
309
+ }
310
+ return JSON.stringify({ error: 'snapshot missing', path: snapshotPath });
311
+ }
312
+
127
313
  /**
128
314
  * 按范围读记录:session = 当前会话(取不到会话时退回已跟踪集合);all = 已跟踪 ∪ 当前。
129
315
  * 单会话读失败只 warn 跳过,不让一条坏记录毁掉整份报告。
@@ -161,9 +347,10 @@ export function createUsageLedger(ctx) {
161
347
  : '';
162
348
  const scope = raw.length === 0 ? 'session' : raw;
163
349
  if (!SCOPES.includes(scope)) {
164
- warn(ctx, 'unknown scope "' + raw + '"; expected session or all');
165
- return { kind: 'error', text: '/' + COMMAND_NAME + ' 未知范围 "' + raw + '",用法:/' + COMMAND_NAME + ' [session|all]' };
350
+ warn(ctx, 'unknown scope "' + raw + '"; expected session, all or json');
351
+ return { kind: 'error', text: '/' + COMMAND_NAME + ' 未知范围 "' + raw + '",用法:/' + COMMAND_NAME + ' [session|all|json]' };
166
352
  }
353
+ if (scope === 'json') return { kind: 'success', text: readSnapshotText() };
167
354
  try {
168
355
  const collected = readRecords(invocation, scope);
169
356
  const report = createTokenReport({ records: collected.records });
@@ -192,7 +379,7 @@ export function createUsageLedger(ctx) {
192
379
  }
193
380
  }
194
381
 
195
- return { adapter, handler, readRecords, dispose, seenSessions };
382
+ return { adapter, handler, readRecords, writeSnapshot, dispose, seenSessions, snapshotPath };
196
383
  }
197
384
 
198
385
  /**
@@ -203,7 +390,7 @@ export function createUsageLedger(ctx) {
203
390
  export function apply(ctx, config) {
204
391
  const resolved = resolveConfig(config);
205
392
  if (!resolved.enabled) return;
206
- const ledger = createUsageLedger(ctx);
393
+ const ledger = createUsageLedger(ctx, resolved);
207
394
  const context = ctx && typeof ctx === 'object' ? ctx : {};
208
395
  const commands = context.commands;
209
396
 
@@ -212,7 +399,7 @@ export function apply(ctx, config) {
212
399
  commands.register({
213
400
  name: COMMAND_NAME,
214
401
  description: 'Report the live Usage ledger captured from assistant/message events',
215
- input: { hint: '[session|all]' },
402
+ input: { hint: '[session|all|json]' },
216
403
  handler: (invocation) => ledger.handler(invocation),
217
404
  });
218
405
  } catch (error) {
@@ -242,6 +429,9 @@ export default { name, inject, apply };
242
429
  /** 测试与集成内用的内部实现出口(不进公开契约文档)。 */
243
430
  export const __internals = {
244
431
  resolveConfig,
432
+ resolveSnapshotPath,
433
+ summarizeRecords,
434
+ buildSnapshotPayload,
245
435
  sessionIdOf,
246
436
  formatReport,
247
437
  createUsageLedger,
@@ -74,6 +74,8 @@ export function createLiveUsageAdapter(ctx = {}, options = {}) {
74
74
  const context = ctx && typeof ctx === 'object' ? ctx : {};
75
75
  const settings = options && typeof options === 'object' ? options : {};
76
76
  const logger = settings.logger ?? context.logger;
77
+ // 已落账通知:只在 commit 真正新增一条记录后触发,供上层同步派生视图(如 token 快照)。
78
+ const onRecord = typeof settings.onRecord === 'function' ? settings.onRecord : null;
77
79
  const adapter = createMemoryUsageAdapter();
78
80
  const committed = new Set();
79
81
  let disposed = false;
@@ -97,6 +99,13 @@ export function createLiveUsageAdapter(ctx = {}, options = {}) {
97
99
  warn('usage watcher failed: ' + describeError(error));
98
100
  }
99
101
  committed.add(key);
102
+ if (onRecord !== null) {
103
+ try {
104
+ onRecord(record);
105
+ } catch (error) {
106
+ warn('onRecord callback failed: ' + describeError(error));
107
+ }
108
+ }
100
109
  return true;
101
110
  }
102
111
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lean-router",
3
- "version": "2.2.6",
3
+ "version": "2.2.7",
4
4
  "description": "lean 省 token × 思考链路由 × code_run 工具遮蔽的 DSH cordis 插件(单 bundle:预设)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -1,9 +1,17 @@
1
- // test/usage-ledger.test.mjs —— 加料件:live Usage 账本挂载(订阅、token-report、降级与卸载)
1
+ // test/usage-ledger.test.mjs —— 加料件:live Usage 账本挂载(订阅、token-report、快照落盘、降级与卸载)
2
2
  import test from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join, resolve } from 'node:path';
4
7
 
5
8
  import { apply, __internals } from 'dsh-lean-router/lean/usage-ledger';
6
9
 
10
+ // 快照默认落在 <DSH_HOME>/storages/lean-router/:把 DSH_HOME 指到临时目录,
11
+ // 免得测试往真实 home 写文件(node --test 每个测试文件独立进程,互不影响)。
12
+ const TEST_HOME = mkdtempSync(join(tmpdir(), 'dsh-usage-ledger-home-'));
13
+ process.env.DSH_HOME = TEST_HOME;
14
+
7
15
  const BASE_USAGE = {
8
16
  inputTokens: 10,
9
17
  outputTokens: 3,
@@ -84,6 +92,17 @@ function invocation(sessionId, rawInput = '') {
84
92
  return { agent: { session: { id: sessionId } }, rawInput };
85
93
  }
86
94
 
95
+ /** 独立的临时快照路径;父目录故意不存在,顺带验证写入时自动建目录。 */
96
+ function tempSnapshotPath(t) {
97
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-usage-ledger-snapshot-'));
98
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
99
+ return join(dir, 'storages', 'lean-router', 'token-report.json');
100
+ }
101
+
102
+ function readSnapshot(file) {
103
+ return JSON.parse(readFileSync(file, 'utf8'));
104
+ }
105
+
87
106
  test('订阅 session/event 后 adapter.read 拿到一条 assistant/message usage 记录', () => {
88
107
  const logger = createLogger();
89
108
  const ctx = createFakeCtx({ logger });
@@ -104,7 +123,7 @@ test('token-report 返回 success,文本含记录数、prompt 总量与五项
104
123
  const ctx = createFakeCtx({ logger: createLogger() });
105
124
  apply(ctx);
106
125
  const definition = commandOf(ctx);
107
- assert.equal(definition.input.hint, '[session|all]');
126
+ assert.equal(definition.input.hint, '[session|all|json]');
108
127
 
109
128
  ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 7, turn: 2, step: 3 }));
110
129
  const result = definition.handler(invocation('session-a'));
@@ -206,3 +225,175 @@ test('宿主 dispose 后卸载适配器与跟踪订阅,重复卸载幂等', ()
206
225
 
207
226
  assert.doesNotThrow(() => ctx.emit('dispose'));
208
227
  });
228
+
229
+ test('默认快照路径落在 <DSH_HOME>/storages/lean-router/token-report.json', () => {
230
+ assert.equal(
231
+ __internals.resolveSnapshotPath(undefined),
232
+ join(TEST_HOME, 'storages', 'lean-router', 'token-report.json'),
233
+ );
234
+ assert.equal(__internals.resolveSnapshotPath(' '), join(TEST_HOME, 'storages', 'lean-router', 'token-report.json'));
235
+ assert.equal(__internals.resolveSnapshotPath('relative/report.json'), resolve('relative/report.json'));
236
+ assert.deepEqual(
237
+ __internals.resolveConfig(undefined),
238
+ {
239
+ enabled: true,
240
+ snapshot: true,
241
+ snapshotPath: join(TEST_HOME, 'storages', 'lean-router', 'token-report.json'),
242
+ },
243
+ );
244
+ const customPath = join(TEST_HOME, 'custom-report.json');
245
+ assert.deepEqual(__internals.resolveConfig({ snapshot: false, snapshotPath: customPath }), {
246
+ enabled: true,
247
+ snapshot: false,
248
+ snapshotPath: customPath,
249
+ });
250
+ });
251
+
252
+ test('记录一条 usage 后原子写出快照,结构为 updatedAt / totals / sessions', (t) => {
253
+ const snapshotPath = tempSnapshotPath(t);
254
+ const logger = createLogger();
255
+ const ctx = createFakeCtx({ logger });
256
+ apply(ctx, { snapshotPath });
257
+
258
+ ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 7, turn: 2, step: 3 }));
259
+
260
+ assert.ok(existsSync(snapshotPath), '快照文件应已创建(含缺失的父目录)');
261
+ assert.equal(existsSync(snapshotPath + '.tmp'), false, '原子写不遗留 .tmp');
262
+ const snapshot = readSnapshot(snapshotPath);
263
+ assert.ok(Number.isFinite(Date.parse(snapshot.updatedAt)), 'updatedAt 应为 ISO 时间:' + snapshot.updatedAt);
264
+ assert.deepEqual(snapshot.totals, {
265
+ records: 1,
266
+ prompt: 13,
267
+ input: 10,
268
+ cacheRead: 2,
269
+ cacheWrite: 1,
270
+ output: 3,
271
+ reasoning: 1,
272
+ });
273
+ assert.deepEqual(Object.keys(snapshot.sessions), ['session-a']);
274
+ const entry = snapshot.sessions['session-a'];
275
+ assert.deepEqual(entry, {
276
+ records: 1,
277
+ prompt: 13,
278
+ input: 10,
279
+ cacheRead: 2,
280
+ cacheWrite: 1,
281
+ output: 3,
282
+ reasoning: 1,
283
+ lastTurn: 2,
284
+ lastStep: 3,
285
+ lastSeq: 7,
286
+ updatedAt: entry.updatedAt,
287
+ });
288
+ assert.ok(Number.isFinite(Date.parse(entry.updatedAt)));
289
+ assert.deepEqual(logger.warnings, []);
290
+ });
291
+
292
+ test('多条记录后 totals 与 sessions 聚合正确(prompt = input + cacheRead + cacheWrite)', (t) => {
293
+ const snapshotPath = tempSnapshotPath(t);
294
+ const ctx = createFakeCtx({ logger: createLogger() });
295
+ apply(ctx, { snapshotPath });
296
+
297
+ ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 1, turn: 1, step: 1 }));
298
+ ctx.emit('session/event', { id: 'session-a' }, assistantEvent({
299
+ seq: 5,
300
+ turn: 3,
301
+ step: 4,
302
+ usage: { inputTokens: 5, outputTokens: 7, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 2 },
303
+ }));
304
+ ctx.emit('session/event', { id: 'session-b' }, assistantEvent({
305
+ seq: 2,
306
+ turn: 2,
307
+ step: 1,
308
+ usage: { inputTokens: 20, outputTokens: 6, cacheReadTokens: 4, cacheWriteTokens: 2, reasoningTokens: 0 },
309
+ }));
310
+
311
+ const snapshot = readSnapshot(snapshotPath);
312
+ assert.deepEqual(snapshot.totals, {
313
+ records: 3,
314
+ prompt: 44,
315
+ input: 35,
316
+ cacheRead: 6,
317
+ cacheWrite: 3,
318
+ output: 16,
319
+ reasoning: 3,
320
+ });
321
+ assert.deepEqual(Object.keys(snapshot.sessions).sort(), ['session-a', 'session-b']);
322
+
323
+ const a = snapshot.sessions['session-a'];
324
+ assert.equal(a.records, 2);
325
+ assert.equal(a.prompt, 18, '13 + 5');
326
+ assert.equal(a.prompt, a.input + a.cacheRead + a.cacheWrite);
327
+ assert.equal(a.lastTurn, 3);
328
+ assert.equal(a.lastStep, 4);
329
+ assert.equal(a.lastSeq, 5);
330
+
331
+ const b = snapshot.sessions['session-b'];
332
+ assert.equal(b.records, 1);
333
+ assert.equal(b.prompt, 26, '20 + 4 + 2');
334
+ assert.equal(b.prompt, b.input + b.cacheRead + b.cacheWrite);
335
+ assert.equal(b.lastSeq, 2);
336
+ });
337
+
338
+ test('config.snapshot === false 时不写文件,json 口径报 missing', (t) => {
339
+ const snapshotPath = tempSnapshotPath(t);
340
+ const logger = createLogger();
341
+ const ctx = createFakeCtx({ logger });
342
+ apply(ctx, { snapshotPath, snapshot: false });
343
+
344
+ ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 1 }));
345
+
346
+ assert.equal(existsSync(snapshotPath), false, '关闭快照后不应创建文件');
347
+ assert.deepEqual(logger.warnings, []);
348
+ // 记录本身照旧
349
+ const text = commandOf(ctx).handler(invocation('session-a'));
350
+ assert.equal(text.kind, 'success');
351
+ assert.ok(text.text.includes('记录 1 条'), text.text);
352
+
353
+ const json = commandOf(ctx).handler(invocation('session-a', 'json'));
354
+ assert.equal(json.kind, 'success');
355
+ assert.deepEqual(JSON.parse(json.text), { error: 'snapshot missing', path: snapshotPath });
356
+ });
357
+
358
+ test('写快照失败只 warn 一次,且不影响记录与命令', (t) => {
359
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-usage-ledger-fail-'));
360
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
361
+ const blocker = join(dir, 'blocked');
362
+ writeFileSync(blocker, 'not a directory', 'utf8');
363
+ const snapshotPath = join(blocker, 'token-report.json');
364
+
365
+ const logger = createLogger();
366
+ const ctx = createFakeCtx({ logger });
367
+ apply(ctx, { snapshotPath });
368
+
369
+ // 写入失败绝不能冒泡到 session/event 的发布方
370
+ assert.doesNotThrow(() => ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 1 })));
371
+ assert.doesNotThrow(() => ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 2 })));
372
+
373
+ const failures = logger.warnings.filter((message) => message.includes('snapshot write failed'));
374
+ assert.equal(failures.length, 1, '同一坏路径只 warn 一次:' + logger.warnings.join(' | '));
375
+ assert.equal(existsSync(snapshotPath), false);
376
+ assert.equal(commandOf(ctx).handler(invocation('session-a')).kind, 'success');
377
+ assert.ok(commandOf(ctx).handler(invocation('session-a')).text.includes('记录 2 条'));
378
+ // 快照缺失时 json 口径给出可解析的错误 JSON,而不是抛
379
+ assert.deepEqual(
380
+ JSON.parse(commandOf(ctx).handler(invocation('session-a', 'json')).text),
381
+ { error: 'snapshot missing', path: snapshotPath },
382
+ );
383
+ });
384
+
385
+ test('json 口径直接输出快照文件内容,与文件字节一致', (t) => {
386
+ const snapshotPath = tempSnapshotPath(t);
387
+ const ctx = createFakeCtx({ logger: createLogger() });
388
+ apply(ctx, { snapshotPath });
389
+ ctx.emit('session/event', { id: 'session-a' }, assistantEvent({ seq: 7, turn: 2, step: 3 }));
390
+
391
+ const result = commandOf(ctx).handler(invocation('session-a', 'json'));
392
+ assert.equal(result.kind, 'success');
393
+ assert.equal(result.text, readFileSync(snapshotPath, 'utf8'));
394
+ const parsed = JSON.parse(result.text);
395
+ assert.deepEqual(parsed, readSnapshot(snapshotPath));
396
+ assert.equal(parsed.totals.prompt, 13);
397
+ assert.equal(parsed.sessions['session-a'].lastSeq, 7);
398
+ });
399
+