tokless 0.5.0 → 0.5.2

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,32 +1,52 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { listSessions } = require('./lib/paths');
4
5
  const { analyzeSession } = require('./lib/analyzer');
5
6
  const { compareSessions } = require('./lib/compare');
6
7
  const { auditProject } = require('./lib/project');
7
8
  const {
8
9
  formatSessionMarkdown,
10
+ formatSessionListMarkdown,
9
11
  formatCompareMarkdown,
10
- formatProjectMarkdown
12
+ formatProjectMarkdown,
11
13
  } = require('./lib/formatter');
12
14
 
15
+ const BOOLEAN_FLAGS = new Set(['json', 'help', 'h']);
16
+ const VALUE_FLAGS = new Set(['source', 'limit', 'data-dir', 'dir', 'home']);
17
+
13
18
  function parseArgs(argv) {
14
19
  const flags = {};
15
20
  const positionals = [];
21
+
16
22
  for (let i = 0; i < argv.length; i++) {
17
23
  const arg = argv[i];
18
- if (arg.startsWith('--')) {
19
- const key = arg.slice(2);
20
- if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
21
- flags[key] = argv[i + 1];
22
- i++;
24
+ if (arg === '-h') {
25
+ flags.help = true;
26
+ } else if (arg.startsWith('--')) {
27
+ const eqIdx = arg.indexOf('=');
28
+ if (eqIdx !== -1) {
29
+ const key = arg.slice(2, eqIdx);
30
+ flags[key] = arg.slice(eqIdx + 1);
23
31
  } else {
24
- flags[key] = true;
32
+ const key = arg.slice(2);
33
+ if (BOOLEAN_FLAGS.has(key)) {
34
+ flags[key] = true;
35
+ } else if (VALUE_FLAGS.has(key) && i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
36
+ flags[key] = argv[i + 1];
37
+ i++;
38
+ } else if (!BOOLEAN_FLAGS.has(key) && i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
39
+ flags[key] = argv[i + 1];
40
+ i++;
41
+ } else {
42
+ flags[key] = true;
43
+ }
25
44
  }
26
45
  } else {
27
46
  positionals.push(arg);
28
47
  }
29
48
  }
49
+
30
50
  return { flags, positionals };
31
51
  }
32
52
 
@@ -35,40 +55,74 @@ function printHelp() {
35
55
  Antigravity 本地账单体检与前后对比工具 (agy-audit CLI · 0 Token 运行)
36
56
 
37
57
  使用说明:
38
- node cli.js session <id-or-prefix-or-path> [--json]
39
- 解剖单个 Antigravity 会话日志(自动搜索 ~/.gemini/antigravity/brain 与 ~/.gemini/antigravity-cli/brain,或直接传入 .jsonl 文件 / brain 目录路径),统计总耗时与最慢步骤 Top 3、read_file 盲读与按行读取统计、实际挂载外部 MCP 服务/前缀列表、每轮上下文净增波动与 Prefix Cache 命中率/断层告警、上下文水位与自动压缩诊断及 Top 5 烧钱步骤。
58
+ node cli.js list [--source all|cli|app|ide] [--limit <N>] [--data-dir <path>] [--json]
59
+ 列出本地最近的 Antigravity 会话(自动检索 ~/.gemini/antigravity、antigravity-cli、antigravity-ide)。
60
+
61
+ node cli.js session [id-or-prefix-or-path | latest | latest~N] [--source all|cli|app|ide] [--data-dir <path>] [--json]
62
+ 解剖单个 Antigravity 会话日志(省略参数默认 latest),统计最慢步骤 Top 3、read_file 盲读与按行读取统计、外部 MCP 空载、Prefix Cache 命中率/断层告警、上下文水位与 Top 5 烧钱步骤。
40
63
 
41
- node cli.js compare <id_or_path_before> <id_or_path_after> [--json]
42
- 对比两个会话的量化指标、缓存命中率与节省比例 (%),输出 Markdown 对比表。
64
+ node cli.js compare <id_or_path_before> <id_or_path_after> [--source all|cli|app|ide] [--data-dir <path>] [--json]
65
+ 对比两个会话的量化指标、缓存命中率与节省比例 (%),支持 latest~1 latest。
43
66
 
44
67
  node cli.js project <dirPath> [--json]
45
- 检查目标项目的常驻规则与 Skill 肥胖度,并扫描全局 ~/.gemini/config/mcp_config.json 与项目 .agents/agents/ 估算每步 MCP 与工具底座空载税及 inheritMcp: false 净身收益。
68
+ 检查目标项目的常驻规则(.agents/.agent/_agents/_agent)与 Skill 肥胖度,并估算全局/工作区 MCP 与工具底座空载税。
46
69
 
47
70
  示例:
48
- node tools/agy-audit/cli.js session 3e4efc2c
49
- node tools/agy-audit/cli.js compare 3e4efc2c e966d1b6
71
+ node tools/agy-audit/cli.js list --source cli
72
+ node tools/agy-audit/cli.js session latest
73
+ node tools/agy-audit/cli.js session 3e4efc2c --json
74
+ node tools/agy-audit/cli.js compare latest~1 latest
50
75
  node tools/agy-audit/cli.js project ./my-project
51
76
  `);
52
77
  }
53
78
 
54
79
  function main() {
55
80
  const argv = process.argv.slice(2);
56
- if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
81
+ if (argv.length === 0) {
57
82
  printHelp();
58
83
  return;
59
84
  }
60
85
 
61
86
  const { flags, positionals } = parseArgs(argv);
87
+ if (flags.help || flags.h) {
88
+ printHelp();
89
+ return;
90
+ }
91
+
62
92
  const cmd = (positionals[0] || '').toLowerCase();
93
+ const commonOptions = {};
94
+ if (typeof flags.source === 'string' && flags.source.trim()) {
95
+ commonOptions.source = flags.source.trim();
96
+ }
97
+ const dataDir = flags['data-dir'] || flags.dir;
98
+ if (typeof dataDir === 'string' && dataDir.trim()) {
99
+ commonOptions.dataDir = dataDir.trim();
100
+ }
101
+ if (typeof flags.home === 'string' && flags.home.trim()) {
102
+ commonOptions.homeDir = flags.home.trim();
103
+ }
63
104
 
64
105
  try {
65
- if (cmd === 'session') {
66
- const id = positionals[1];
67
- if (!id) {
68
- console.error('❌ 请提供会话 ID 或短前缀,例如: node cli.js session 3e4efc2c');
69
- process.exit(1);
106
+ if (cmd === 'list') {
107
+ const limit = flags.limit !== undefined ? parseInt(flags.limit, 10) : 10;
108
+ const sessions = listSessions({
109
+ ...commonOptions,
110
+ limit: Number.isInteger(limit) && limit >= 0 ? limit : 10,
111
+ });
112
+ if (flags.json) {
113
+ console.log(
114
+ JSON.stringify(
115
+ { source: commonOptions.source || 'all', count: sessions.length, sessions },
116
+ null,
117
+ 2
118
+ )
119
+ );
120
+ } else {
121
+ console.log(formatSessionListMarkdown(sessions, commonOptions));
70
122
  }
71
- const report = analyzeSession(id);
123
+ } else if (cmd === 'session') {
124
+ const id = positionals[1] || 'latest';
125
+ const report = analyzeSession(id, commonOptions);
72
126
  if (flags.json) {
73
127
  console.log(JSON.stringify(report, null, 2));
74
128
  } else {
@@ -78,10 +132,10 @@ function main() {
78
132
  const idBefore = positionals[1];
79
133
  const idAfter = positionals[2];
80
134
  if (!idBefore || !idAfter) {
81
- console.error('❌ 请提供两个会话 ID 进行对比,例如: node cli.js compare <before> <after>');
135
+ console.error('❌ 请提供两个会话 ID 进行对比,例如: node cli.js compare latest~1 latest');
82
136
  process.exit(1);
83
137
  }
84
- const cmp = compareSessions(idBefore, idAfter);
138
+ const cmp = compareSessions(idBefore, idAfter, commonOptions);
85
139
  if (flags.json) {
86
140
  console.log(JSON.stringify(cmp, null, 2));
87
141
  } else {
@@ -101,7 +155,7 @@ function main() {
101
155
  console.log(formatProjectMarkdown(report));
102
156
  }
103
157
  } else {
104
- console.error(`❌ 未知子命令 "${cmd}"。支持: session, compare, project`);
158
+ console.error(`❌ 未知子命令 "${cmd}"。支持: list, session, compare, project`);
105
159
  printHelp();
106
160
  process.exit(1);
107
161
  }
@@ -1,7 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('fs');
4
- const { resolveSessionTarget, getConversationMeta, inspectSessionMountedMcp } = require('./paths');
4
+ const {
5
+ resolveSessionTarget,
6
+ getConversationMeta,
7
+ extractFallbackTitleFromTranscript,
8
+ cleanUserPromptTitle,
9
+ inspectSessionMountedMcp,
10
+ } = require('./paths');
5
11
 
6
12
  const COMPACTION_THRESHOLD_256K = 256000;
7
13
  const COMPACTION_THRESHOLD_512K = 512000;
@@ -38,7 +44,8 @@ function hasLineRange(args) {
38
44
  if (!args || typeof args !== 'object') return false;
39
45
  return (
40
46
  parseLineNumber(args.StartLine ?? args.startLine ?? args.start_line) !== null ||
41
- parseLineNumber(args.EndLine ?? args.endLine ?? args.end_line) !== null
47
+ parseLineNumber(args.EndLine ?? args.endLine ?? args.end_line) !== null ||
48
+ parseLineNumber(args.ByteOffset ?? args.byteOffset ?? args.byte_offset) !== null
42
49
  );
43
50
  }
44
51
 
@@ -167,14 +174,18 @@ function formatToolTarget(name, args) {
167
174
  const snippet = innerStr && innerStr !== '{}' ? ` ${innerStr.slice(0, 60)}${innerStr.length > 60 ? '...' : ''}` : '';
168
175
  return `${srv}::${tl}${snippet}`;
169
176
  }
170
- if (args.Path || args.path) {
171
- const p = args.Path || args.path;
177
+ const targetFile = args.Path ?? args.path ?? args.file_path ?? args.AbsolutePath;
178
+ if (targetFile) {
172
179
  const start = args.StartLine ?? args.startLine ?? args.start_line;
173
180
  const end = args.EndLine ?? args.endLine ?? args.end_line;
181
+ const byteOffset = args.ByteOffset ?? args.byteOffset ?? args.byte_offset;
174
182
  if (start !== undefined || end !== undefined) {
175
- return `${p} [L${start ?? 1}-L${end ?? 'EOF'}]`;
183
+ return `${targetFile} [L${start ?? 1}-L${end ?? 'EOF'}]`;
176
184
  }
177
- return p;
185
+ if (byteOffset !== undefined) {
186
+ return `${targetFile} [ByteOffset:${byteOffset}]`;
187
+ }
188
+ return targetFile;
178
189
  }
179
190
  if (args.CommandLine || args.command) {
180
191
  return args.CommandLine || args.command;
@@ -220,6 +231,24 @@ function extractTokenUsage(step) {
220
231
  return { input, output, cacheRead, hasUsage };
221
232
  }
222
233
 
234
+ function extractStepModel(step) {
235
+ if (!step || typeof step !== 'object') return null;
236
+ const candidates = [
237
+ step.model,
238
+ step.model_name,
239
+ step.modelName,
240
+ step.usage && step.usage.model,
241
+ step.metadata && step.metadata.model
242
+ ];
243
+ for (const val of candidates) {
244
+ if (typeof val === 'string') {
245
+ const trimmed = val.trim();
246
+ if (trimmed) return trimmed;
247
+ }
248
+ }
249
+ return null;
250
+ }
251
+
223
252
  function computeIdleSeconds(prevIso, currIso) {
224
253
  if (!prevIso || !currIso) return null;
225
254
  const t1 = Date.parse(prevIso);
@@ -228,8 +257,9 @@ function computeIdleSeconds(prevIso, currIso) {
228
257
  return Math.round((t2 - t1) / 1000);
229
258
  }
230
259
 
231
- function analyzeSession(idOrPrefixOrPath) {
232
- const { conversationId, transcriptInfo: info } = resolveSessionTarget(idOrPrefixOrPath);
260
+ function analyzeSession(idOrPrefixOrPath, options = {}) {
261
+ const target = resolveSessionTarget(idOrPrefixOrPath, options);
262
+ const { conversationId, transcriptInfo: info } = target;
233
263
  if (!info) {
234
264
  throw new Error(`Transcript file not found for conversation: ${idOrPrefixOrPath}`);
235
265
  }
@@ -259,6 +289,7 @@ function analyzeSession(idOrPrefixOrPath) {
259
289
  let lastStepContextTokens = 0;
260
290
  let firstTimestamp = null;
261
291
  let lastTimestamp = null;
292
+ let fallbackTitle = '';
262
293
 
263
294
  const checkpoints = [];
264
295
  let pendingCheckpoint = null;
@@ -266,6 +297,8 @@ function analyzeSession(idOrPrefixOrPath) {
266
297
  let prevUsageStep = null;
267
298
  let sawCheckpointSincePrevUsage = false;
268
299
  let sawSettingsChangeSincePrevUsage = false;
300
+ const modelUsageMap = new Map();
301
+ let modelSwitchCount = 0;
269
302
 
270
303
  const toolCalls = [];
271
304
  const pendingQueue = [];
@@ -336,6 +369,24 @@ function analyzeSession(idOrPrefixOrPath) {
336
369
  totalOutputTokens += usage.output;
337
370
  totalCacheReadTokens += usage.cacheRead;
338
371
 
372
+ const currModel = extractStepModel(step);
373
+ if (currModel) {
374
+ if (!modelUsageMap.has(currModel)) {
375
+ modelUsageMap.set(currModel, {
376
+ model: currModel,
377
+ calls: 0,
378
+ inputTokens: 0,
379
+ cacheReadTokens: 0,
380
+ outputTokens: 0
381
+ });
382
+ }
383
+ const mu = modelUsageMap.get(currModel);
384
+ mu.calls++;
385
+ mu.inputTokens += usage.input;
386
+ mu.cacheReadTokens += usage.cacheRead;
387
+ mu.outputTokens += usage.output;
388
+ }
389
+
339
390
  currentTurnStat.inputTokens += usage.input;
340
391
  currentTurnStat.cacheReadTokens += usage.cacheRead;
341
392
  currentTurnStat.outputTokens += usage.output;
@@ -349,9 +400,15 @@ function analyzeSession(idOrPrefixOrPath) {
349
400
  currentTurnStat.peakContextTokens = stepContextTokens;
350
401
  }
351
402
 
403
+ const prevModel = prevUsageStep ? (prevUsageStep.model || null) : null;
404
+ const isModelSwitched = Boolean(prevModel && currModel && prevModel !== currModel);
405
+
352
406
  if (!prevUsageStep) {
353
407
  coldStartInputTokens = usage.input;
354
408
  } else {
409
+ if (isModelSwitched) {
410
+ modelSwitchCount++;
411
+ }
355
412
  postWarmupInputTokens += usage.input;
356
413
  postWarmupCacheReadTokens += usage.cacheRead;
357
414
 
@@ -369,12 +426,18 @@ function analyzeSession(idOrPrefixOrPath) {
369
426
  usage.input >= uncachedGap * 0.5
370
427
  ) {
371
428
  const idleSeconds = computeIdleSeconds(prevUsageStep.createdAt, step.created_at);
429
+ const isIdleExpired = idleSeconds !== null && idleSeconds >= IDLE_TTL_WARNING_SECONDS;
372
430
  let reasonCode = 'prefix_mutated_or_evicted';
373
431
  let reason = `前缀变动或缓存驱逐 (仅复用 ${(retentionRatio * 100).toFixed(1)}% 历史前缀,排查动态规则/工具变更)`;
374
432
 
375
- if (idleSeconds !== null && idleSeconds >= IDLE_TTL_WARNING_SECONDS) {
433
+ if (isIdleExpired) {
376
434
  reasonCode = 'idle_ttl_expired';
377
- reason = `闲置超时导致缓存过期 (距上一步间隔 ${(idleSeconds / 60).toFixed(1)} 分钟,超出缓存保活窗口)`;
435
+ const switchSuffix = isModelSwitched ? `,且同时切换模型 (${prevModel} → ${currModel})` : '';
436
+ reason = `闲置超时导致缓存过期 (距上一步间隔 ${(idleSeconds / 60).toFixed(1)} 分钟,超出缓存保活窗口${switchSuffix})`;
437
+ } else if (isModelSwitched) {
438
+ reasonCode = 'model_switch';
439
+ const switchSource = sawSettingsChangeSincePrevUsage ? '手动/设置切换模型' : '双模型/Orchestrator 自动切换';
440
+ reason = `${switchSource} (${prevModel} → ${currModel}) 导致跨模型前缀重算`;
378
441
  } else if (sawSettingsChangeSincePrevUsage) {
379
442
  reasonCode = 'settings_or_model_switch';
380
443
  reason = '会话中途切换模型或设置 (USER_SETTINGS_CHANGE) 导致前缀重算';
@@ -388,6 +451,9 @@ function analyzeSession(idOrPrefixOrPath) {
388
451
  turnIndex: Math.max(1, totalTurns),
389
452
  createdAt: step.created_at || null,
390
453
  idleSeconds,
454
+ prevModel,
455
+ currModel,
456
+ isModelSwitch: isModelSwitched,
391
457
  prevContextTokens: prevContext,
392
458
  prevCacheReadTokens: prevUsageStep.cacheRead,
393
459
  currCacheReadTokens: usage.cacheRead,
@@ -419,7 +485,8 @@ function analyzeSession(idOrPrefixOrPath) {
419
485
  input: usage.input,
420
486
  cacheRead: usage.cacheRead,
421
487
  contextTokens: stepContextTokens,
422
- createdAt: step.created_at || null
488
+ createdAt: step.created_at || null,
489
+ model: currModel
423
490
  };
424
491
  sawCheckpointSincePrevUsage = false;
425
492
  sawSettingsChangeSincePrevUsage = false;
@@ -660,7 +727,7 @@ function analyzeSession(idOrPrefixOrPath) {
660
727
  }
661
728
 
662
729
  // Merge session DB `<mcp_servers>` prompt inspection + transcript actual MCP invocations
663
- const dbMcpInfo = inspectSessionMountedMcp(conversationId, info.filePath);
730
+ const dbMcpInfo = inspectSessionMountedMcp(conversationId, info.filePath, options);
664
731
  const mergedMcpMap = new Map();
665
732
 
666
733
  for (const srv of dbMcpInfo.servers) {
@@ -759,12 +826,29 @@ function analyzeSession(idOrPrefixOrPath) {
759
826
  }
760
827
  }
761
828
 
762
- const dbMeta = getConversationMeta(conversationId);
829
+ if (!fallbackTitle) {
830
+ for (const s of steps) {
831
+ if (s && s.type === 'USER_INPUT' && typeof s.content === 'string') {
832
+ const cleaned = cleanUserPromptTitle(s.content);
833
+ if (cleaned) {
834
+ fallbackTitle = cleaned;
835
+ break;
836
+ }
837
+ }
838
+ }
839
+ if (!fallbackTitle) {
840
+ fallbackTitle = extractFallbackTitleFromTranscript(info.filePath);
841
+ }
842
+ }
843
+
844
+ const dbMeta = getConversationMeta(conversationId, options);
763
845
  const meta = {
764
846
  conversationId,
765
847
  shortId: conversationId.slice(0, 8),
766
- title: (dbMeta && dbMeta.title) || 'Untitled Session',
848
+ title: (dbMeta && dbMeta.title) || fallbackTitle || 'Untitled Session',
767
849
  workspace: (dbMeta && dbMeta.workspace) || '',
850
+ source: target.source || 'unknown',
851
+ sourceLabel: target.sourceLabel || '',
768
852
  logType: info.logType,
769
853
  logFile: info.filePath,
770
854
  logBytes: info.bytes,
@@ -790,6 +874,34 @@ function analyzeSession(idOrPrefixOrPath) {
790
874
  ? Number(((postWarmupCacheReadTokens / postWarmupTotal) * 100).toFixed(1))
791
875
  : 0;
792
876
  const cacheRebilledTokens = cacheCliffs.reduce((s, c) => s + c.estRebilledTokens, 0);
877
+ const cacheCliffBreakdown = {
878
+ model_switch: { count: 0, estRebilledTokens: 0 },
879
+ idle_ttl_expired: { count: 0, estRebilledTokens: 0 },
880
+ settings_or_model_switch: { count: 0, estRebilledTokens: 0 },
881
+ prefix_mutated_or_evicted: { count: 0, estRebilledTokens: 0 }
882
+ };
883
+ for (const cliff of cacheCliffs) {
884
+ if (!cacheCliffBreakdown[cliff.reasonCode]) {
885
+ cacheCliffBreakdown[cliff.reasonCode] = { count: 0, estRebilledTokens: 0 };
886
+ }
887
+ cacheCliffBreakdown[cliff.reasonCode].count++;
888
+ cacheCliffBreakdown[cliff.reasonCode].estRebilledTokens += cliff.estRebilledTokens;
889
+ }
890
+ const modelSwitchCacheCliffCount = cacheCliffBreakdown.model_switch.count;
891
+ const modelSwitchCacheRebilledTokens = cacheCliffBreakdown.model_switch.estRebilledTokens;
892
+ const modelBreakdown = Array.from(modelUsageMap.values())
893
+ .map(m => {
894
+ const billed = m.inputTokens + m.cacheReadTokens;
895
+ return {
896
+ model: m.model,
897
+ calls: m.calls,
898
+ inputTokens: m.inputTokens,
899
+ cacheReadTokens: m.cacheReadTokens,
900
+ outputTokens: m.outputTokens,
901
+ cacheHitRatePct: billed > 0 ? Number(((m.cacheReadTokens / billed) * 100).toFixed(1)) : 0
902
+ };
903
+ })
904
+ .sort((a, b) => (b.inputTokens + b.cacheReadTokens) - (a.inputTokens + a.cacheReadTokens) || b.calls - a.calls || a.model.localeCompare(b.model));
793
905
 
794
906
  const netDeltas = turnDeltas.map(t => t.netContextDeltaTokens);
795
907
  const maxTurnNetContextDeltaTokens = netDeltas.length > 0 ? Math.max(...netDeltas) : 0;
@@ -816,6 +928,9 @@ function analyzeSession(idOrPrefixOrPath) {
816
928
  invokedMcpToolCalls: mcpAudit.totalMcpToolCalls,
817
929
  hasUsageMetrics: usageFieldSteps > 0,
818
930
  usageFieldSteps,
931
+ distinctModelCount: modelBreakdown.length,
932
+ modelsUsed: modelBreakdown.map(m => m.model),
933
+ modelSwitchCount,
819
934
  coldStartInputTokens,
820
935
  totalInputTokens,
821
936
  totalOutputTokens,
@@ -827,6 +942,8 @@ function analyzeSession(idOrPrefixOrPath) {
827
942
  postWarmupCacheHitRatePct,
828
943
  cacheCliffCount: cacheCliffs.length,
829
944
  cacheRebilledTokens,
945
+ modelSwitchCacheCliffCount,
946
+ modelSwitchCacheRebilledTokens,
830
947
  peakContextTokens,
831
948
  peakContextPct256k,
832
949
  peakContextPct512k,
@@ -851,6 +968,8 @@ function analyzeSession(idOrPrefixOrPath) {
851
968
  turnDeltas,
852
969
  checkpoints,
853
970
  cacheCliffs,
971
+ modelBreakdown,
972
+ cacheCliffBreakdown,
854
973
  toolBreakdown,
855
974
  topBloats
856
975
  };
@@ -20,9 +20,9 @@ function calcDelta(beforeVal, afterVal) {
20
20
  };
21
21
  }
22
22
 
23
- function compareSessions(idBefore, idAfter) {
24
- const before = analyzeSession(idBefore);
25
- const after = analyzeSession(idAfter);
23
+ function compareSessions(idBefore, idAfter, options = {}) {
24
+ const before = analyzeSession(idBefore, options);
25
+ const after = analyzeSession(idAfter, options);
26
26
 
27
27
  const bMaxChars = before.stats.maxSingleStepOutput ? before.stats.maxSingleStepOutput.outputChars : 0;
28
28
  const aMaxChars = after.stats.maxSingleStepOutput ? after.stats.maxSingleStepOutput.outputChars : 0;
@@ -49,6 +49,8 @@ function compareSessions(idBefore, idAfter) {
49
49
  totalThroughputTokens: calcDelta(before.stats.totalThroughputTokens, after.stats.totalThroughputTokens),
50
50
  cacheHitRatePct: calcDelta(before.stats.cacheHitRatePct, after.stats.cacheHitRatePct),
51
51
  cacheCliffCount: calcDelta(before.stats.cacheCliffCount, after.stats.cacheCliffCount),
52
+ modelSwitchCount: calcDelta(before.stats.modelSwitchCount, after.stats.modelSwitchCount),
53
+ modelSwitchCacheCliffCount: calcDelta(before.stats.modelSwitchCacheCliffCount, after.stats.modelSwitchCacheCliffCount),
52
54
  peakContextTokens: calcDelta(before.stats.peakContextTokens, after.stats.peakContextTokens),
53
55
  peakContextPct256k: calcDelta(before.stats.peakContextPct256k, after.stats.peakContextPct256k),
54
56
  compactionCount: calcDelta(before.stats.compactionCount, after.stats.compactionCount)
@@ -54,6 +54,8 @@ function formatSessionMarkdown(report) {
54
54
  turnDeltas = [],
55
55
  checkpoints = [],
56
56
  cacheCliffs = [],
57
+ modelBreakdown = [],
58
+ cacheCliffBreakdown = null,
57
59
  toolBreakdown,
58
60
  topBloats
59
61
  } = report;
@@ -94,10 +96,17 @@ function formatSessionMarkdown(report) {
94
96
  lines.push(`| **实测 Input Tokens** | **${fmtNum(stats.totalInputTokens)}** | 统计自 ${stats.usageFieldSteps} 次模型调用 |`);
95
97
  lines.push(`| **实测 Cache Read Tokens** | **${fmtNum(stats.totalCacheReadTokens)}** | 历史上下文缓存重复计费滚雪球命中量 |`);
96
98
  lines.push(`| **实测缓存命中率** | **${stats.cacheHitRatePct}%**(预热后 **${stats.postWarmupCacheHitRatePct}%**) | \`cache_read / (input + cache_read)\` |`);
99
+ const cliffSwitchNote = stats.modelSwitchCacheCliffCount > 0
100
+ ? `;其中模型切换 **${fmtNum(stats.modelSwitchCacheCliffCount)}** 次 ~**${fmtNum(stats.modelSwitchCacheRebilledTokens)}**`
101
+ : '';
97
102
  const cliffBadge = stats.cacheCliffCount > 0
98
- ? `⚠️ 检出 **${stats.cacheCliffCount}** 次断层(重算浪费 ~**${fmtNum(stats.cacheRebilledTokens)}** Input)`
103
+ ? `⚠️ 检出 **${stats.cacheCliffCount}** 次断层(重算浪费 ~**${fmtNum(stats.cacheRebilledTokens)}** Input${cliffSwitchNote})`
99
104
  : `✅ **0** 次断层`;
100
105
  lines.push(`| **Prefix Cache 断层告警** | ${cliffBadge} | 检测连续步骤间 \`cache_read\` 骤降且 \`input\` 暴涨 |`);
106
+ if (stats.distinctModelCount > 1) {
107
+ const modelsLabel = Array.isArray(stats.modelsUsed) ? stats.modelsUsed.map(m => `\`${m}\``).join(' ↔ ') : '';
108
+ lines.push(`| **调用模型与切换次数** | **${stats.distinctModelCount}** 个模型 / 切换 **${fmtNum(stats.modelSwitchCount)}** 次 | ${modelsLabel} |`);
109
+ }
101
110
  lines.push(`| **实测 Output Tokens** | **${fmtNum(stats.totalOutputTokens)}** | 模型生成输出 Token |`);
102
111
  lines.push(`| **总 Token 吞吐** | **${fmtNum(stats.totalThroughputTokens)}** | \`input + cache_read + output\` |`);
103
112
  lines.push(`| **峰值上下文水位** | **${fmtNum(stats.peakContextTokens)}**(三代 ~256K 占 **${stats.peakContextPct256k}%** / 四代推测 ~512K 占 **${stats.peakContextPct512k ?? Number(((stats.peakContextTokens / 512000) * 100).toFixed(1))}%**) | Step ${stats.peakContextStepIndex ?? '-'} 达峰;控水位减轮次是降低累计 Cache Read 的核心 |`);
@@ -116,6 +125,24 @@ function formatSessionMarkdown(report) {
116
125
  lines.push(`- **缓存连续性状态**: ✅ 全程未检出异常 Prefix Cache 断层(历史前缀保持严格追加复用)。`);
117
126
  } else {
118
127
  lines.push(`- **缓存断层告警**: ⚠️ 共检出 **${cacheCliffs.length}** 次缓存失效断层,估算多花原价 Input **~${fmtNum(stats.cacheRebilledTokens)}** Tokens:`);
128
+ if (cacheCliffBreakdown) {
129
+ const breakdownOrder = [
130
+ ['model_switch', '模型切换'],
131
+ ['idle_ttl_expired', '闲置超时'],
132
+ ['settings_or_model_switch', '设置/模型变更'],
133
+ ['prefix_mutated_or_evicted', '其他前缀变动']
134
+ ];
135
+ const parts = breakdownOrder
136
+ .map(([key, label]) => {
137
+ const item = cacheCliffBreakdown[key];
138
+ if (!item || !item.count) return null;
139
+ return `${label} **${fmtNum(item.count)}** 次 (~${fmtNum(item.estRebilledTokens)} Input)`;
140
+ })
141
+ .filter(Boolean);
142
+ if (parts.length > 0) {
143
+ lines.push(`- **断层根因拆解**: ${parts.join(' · ')}`);
144
+ }
145
+ }
119
146
  lines.push('');
120
147
  lines.push(`| # | 断层步骤 | 间隔时长 | 前步上下文 → 本步 Cache Read | 本步暴涨 Input | 估算重算浪费 | 疑似根因诊断 |`);
121
148
  lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
@@ -126,7 +153,15 @@ function formatSessionMarkdown(report) {
126
153
  );
127
154
  }
128
155
  lines.push('');
129
- lines.push(`- **止血建议**: ① 若闲置超过 1 小时缓存已过期,重开干净新会话带上精简结论往往比在巨型旧上下文里硬唤醒更省钱;② 严禁在对话中途动态篡改顶部常驻规则、系统提示词或增删 MCP 工具(破坏前缀只追加性)。`);
156
+ lines.push(`- **止血建议**: ① 若闲置超过 1 小时缓存已过期,重开干净新会话带上精简结论往往比在巨型旧上下文里硬唤醒更省钱;② 严禁在对话中途动态篡改顶部常驻规则、系统提示词或增删 MCP 工具(破坏前缀只追加性);③ 若处于 Orchestrator / 双模型规划执行模式,跨模型切换必然触发 KV Cache 重算,建议集中规划后一次移交执行以减少高频往返切换。`);
157
+ }
158
+ if (modelBreakdown.length > 1) {
159
+ lines.push('');
160
+ lines.push(`| 模型 | 调用次数 | Input Tokens | Cache Read Tokens | Output Tokens | 缓存命中率 |`);
161
+ lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- |`);
162
+ for (const m of modelBreakdown) {
163
+ lines.push(`| \`${escapePipe(m.model)}\` | ${fmtNum(m.calls)} | ${fmtNum(m.inputTokens)} | ${fmtNum(m.cacheReadTokens)} | ${fmtNum(m.outputTokens)} | **${m.cacheHitRatePct}%** |`);
164
+ }
130
165
  }
131
166
  lines.push('');
132
167
  }
@@ -308,6 +343,9 @@ function formatCompareMarkdown(cmp) {
308
343
  ['累计 Cache Read Tokens (滚雪球)', fmtNum(metrics.totalCacheReadTokens.before), fmtNum(metrics.totalCacheReadTokens.after), fmtDelta(metrics.totalCacheReadTokens.delta), fmtPct(metrics.totalCacheReadTokens.savedPct)],
309
344
  ['Prefix Cache 命中率 (%)', `${metrics.cacheHitRatePct.before}%`, `${metrics.cacheHitRatePct.after}%`, fmtDelta(metrics.cacheHitRatePct.delta, '%'), '-'],
310
345
  ['Prefix Cache 断层次数', fmtNum(metrics.cacheCliffCount.before), fmtNum(metrics.cacheCliffCount.after), fmtDelta(metrics.cacheCliffCount.delta), fmtPct(metrics.cacheCliffCount.savedPct)],
346
+ ...(metrics.modelSwitchCacheCliffCount && (metrics.modelSwitchCacheCliffCount.before > 0 || metrics.modelSwitchCacheCliffCount.after > 0)
347
+ ? [['└─ 其中模型切换引起', fmtNum(metrics.modelSwitchCacheCliffCount.before), fmtNum(metrics.modelSwitchCacheCliffCount.after), fmtDelta(metrics.modelSwitchCacheCliffCount.delta), fmtPct(metrics.modelSwitchCacheCliffCount.savedPct)]]
348
+ : []),
311
349
  ['累计 Output Tokens', fmtNum(metrics.totalOutputTokens.before), fmtNum(metrics.totalOutputTokens.after), fmtDelta(metrics.totalOutputTokens.delta), fmtPct(metrics.totalOutputTokens.savedPct)],
312
350
  ['总 Token 吞吐 (`input+cache_read+output`)', fmtNum(metrics.totalThroughputTokens.before), fmtNum(metrics.totalThroughputTokens.after), fmtDelta(metrics.totalThroughputTokens.delta), fmtPct(metrics.totalThroughputTokens.savedPct)],
313
351
  [
@@ -337,20 +375,19 @@ function formatCompareMarkdown(cmp) {
337
375
  }
338
376
 
339
377
  function formatProjectMarkdown(report) {
340
- const { projectDir, projectName, thresholds, summary, files, flaggedFiles, mcpAndToolTax } = report;
378
+ const { projectDir, projectName, summary, files, mcpAndToolTax } = report;
341
379
  const lines = [];
342
380
 
343
- lines.push(`## 🩺 项目规则、Skill 与 MCP 底座体检: ${projectName}`);
381
+ lines.push(`## 🩺 项目规则、Skill 与 MCP 底座账单透视: ${projectName}`);
344
382
  lines.push(`- **检查目录**: \`${projectDir}\``);
345
- lines.push(`- **文档诊断阈值**: 常驻规则 (\`AGENTS.md\` / \`GEMINI.md\` / \`rules/*.md\`) > ${thresholds.alwaysOnLineLimit} 行告警;按需技能 (\`SKILL.md\`) > ${thresholds.skillLineLimit} 行告警;单文件高密度体积 > ${fmtBytes(thresholds.alwaysOnByteAdvisory)} (常驻) / > ${fmtBytes(thresholds.skillByteAdvisory)} (技能) 提示精简。`);
346
383
  lines.push('');
347
384
 
348
385
  lines.push(`### 📊 文档负载总览`);
349
386
  lines.push('');
350
- lines.push(`| 加载模式 | 文件数 | 总行数 | 总字节 | 估算 Token 成本 | 说明 |`);
351
- lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- |`);
352
- lines.push(`| **Always-On (每轮常驻)** | ${summary.alwaysOn.count} | ${fmtNum(summary.alwaysOn.lines)} | ${fmtBytes(summary.alwaysOn.bytes)} | **${fmtNum(summary.alwaysOn.estTokens)}** / 轮 | 每轮对话无条件注入上下文 |`);
353
- lines.push(`| **Progressive Disclosure (按需)** | ${summary.progressiveDisclosure.count} | ${fmtNum(summary.progressiveDisclosure.lines)} | ${fmtBytes(summary.progressiveDisclosure.bytes)} | **${fmtNum(summary.progressiveDisclosure.estTokens)}** (全触发) | 平时仅加载 \`description\`,命中时读正文 |`);
387
+ lines.push(`| 加载模式 | 文件数 | 总行数 | 总字节 | 单轮/单次估算 Token | 30 步常驻滚雪球 | 说明 |`);
388
+ lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
389
+ lines.push(`| **Always-On (每轮常驻)** | ${summary.alwaysOn.count} | ${fmtNum(summary.alwaysOn.lines)} | ${fmtBytes(summary.alwaysOn.bytes)} | **~${fmtNum(summary.alwaysOn.estTokens)}** / 轮 | ~${fmtNum(summary.alwaysOn.estTokens * 30)} | 每轮对话无条件注入上下文 |`);
390
+ lines.push(`| **Progressive Disclosure (按需)** | ${summary.progressiveDisclosure.count} | ${fmtNum(summary.progressiveDisclosure.lines)} | ${fmtBytes(summary.progressiveDisclosure.bytes)} | **~${fmtNum(summary.progressiveDisclosure.estTokens)}** (全触发) | *(按需加载)* | 平时仅注入 \`description\`,命中时读正文 |`);
354
391
  lines.push('');
355
392
 
356
393
  if (files.length === 0) {
@@ -359,13 +396,11 @@ function formatProjectMarkdown(report) {
359
396
  } else {
360
397
  lines.push(`### 📁 规则与技能文件明细`);
361
398
  lines.push('');
362
- lines.push(`| 文件路径 | 类别 | 加载模式 | 行数 | 字节数 | 估算 Token | 状态 |`);
399
+ lines.push(`| 文件路径 | 类别 | 加载模式 | 行数 | 字节数 | 单次估算 Token | 30 步常驻滚雪球 |`);
363
400
  lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
364
401
  for (const f of files) {
365
- let badge = '✅ 正常';
366
- if (f.status === 'BLOAT') badge = `🔴 超标 (>${f.lineLimit}行)`;
367
- else if (f.status === 'DENSE') badge = `🟡 高密度偏胖`;
368
- lines.push(`| \`${f.relativePath}\` | ${f.category} | ${f.loadMode} | ${f.lines} | ${fmtBytes(f.bytes)} | ${fmtNum(f.estTokens)} | ${badge} |`);
402
+ const snowball = f.loadMode === 'Always-On' ? `~${fmtNum(f.estTokens * 30)}` : '*(按需触发)*';
403
+ lines.push(`| \`${f.relativePath}\` | ${f.category} | ${f.loadMode} | ${f.lines} | ${fmtBytes(f.bytes)} | ~${fmtNum(f.estTokens)} | ${snowball} |`);
369
404
  }
370
405
  lines.push('');
371
406
  }
@@ -418,31 +453,53 @@ function formatProjectMarkdown(report) {
418
453
  }
419
454
  }
420
455
 
421
- lines.push(`### ✂️ 降维瘦身与净身建议`);
422
- lines.push('');
423
- const hasDocFlags = flaggedFiles.length > 0;
424
456
  const mcpTips = (mcpAndToolTax && mcpAndToolTax.suggestions) || [];
425
-
426
- if (!hasDocFlags && mcpTips.length === 0) {
427
- lines.push(`✅ 所有常驻规则、Skill 与角色工具底座均处于精简状态,无需额外瘦身。`);
428
- } else {
429
- for (const f of flaggedFiles) {
430
- lines.push(`- **\`${f.relativePath}\`** (${f.lines} 行 · ${fmtBytes(f.bytes)} · 约 ${fmtNum(f.estTokens)} Token · ${f.loadMode}):`);
431
- for (const s of f.suggestions) {
432
- lines.push(` - ${s}`);
433
- }
434
- }
457
+ if (mcpTips.length > 0) {
458
+ lines.push(`### 💡 工具底座净身参考`);
459
+ lines.push('');
435
460
  for (const tip of mcpTips) {
436
- lines.push(`- **MCP / 工具底座净身**: ${tip}`);
461
+ lines.push(`- ${tip}`);
437
462
  }
463
+ lines.push('');
438
464
  }
465
+
466
+ return lines.join('\n');
467
+ }
468
+
469
+ function formatSessionListMarkdown(sessions, options = {}) {
470
+ const lines = [];
471
+ const sourceDesc = options.source ? `source=${options.source}` : 'all sources';
472
+ lines.push(`## 📋 最近 Antigravity 会话列表 (${sourceDesc})`);
439
473
  lines.push('');
440
474
 
475
+ if (!sessions || sessions.length === 0) {
476
+ lines.push('*(未找到包含 transcript 日志的会话记录)*');
477
+ lines.push('');
478
+ return lines.join('\n');
479
+ }
480
+
481
+ lines.push(`| # | 短 ID | 来源 | 标题 | 日志 | 大小 | 最后更新时间 |`);
482
+ lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
483
+
484
+ sessions.forEach((s, idx) => {
485
+ const timeStr = s.mtimeIso ? s.mtimeIso.replace('T', ' ').slice(0, 19) : '-';
486
+ lines.push(
487
+ `| ${idx + 1} | \`${s.shortId}\` | ${escapePipe(s.sourceLabel || s.source)} | ${escapePipe(truncateText(s.title, 44))} | \`${s.logType}\` | ${fmtBytes(s.bytes)} | ${timeStr} |`
488
+ );
489
+ });
490
+
491
+ lines.push('');
492
+ lines.push(`> 💡 快捷命令:\`node cli.js session latest\`(最近一次)或 \`node cli.js session ${sessions[0].shortId}\``);
493
+ if (sessions.length >= 2) {
494
+ lines.push(`> ⚖️ 对比最近两次:\`node cli.js compare latest~1 latest\` 或 \`node cli.js compare ${sessions[1].shortId} ${sessions[0].shortId}\``);
495
+ }
496
+ lines.push('');
441
497
  return lines.join('\n');
442
498
  }
443
499
 
444
500
  module.exports = {
445
501
  formatSessionMarkdown,
502
+ formatSessionListMarkdown,
446
503
  formatCompareMarkdown,
447
504
  formatProjectMarkdown
448
505
  };