tokless 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +205 -0
- package/README.md +240 -2
- package/agents/tokless-coder.md +17 -0
- package/agents/tokless-reviewer.md +16 -0
- package/assets/logo.svg +15 -0
- package/bin/tokless.js +106 -0
- package/hooks.json +17 -0
- package/index.js +76 -0
- package/install.js +116 -0
- package/lib/audit.js +15 -0
- package/lib/read-guard.js +3 -0
- package/lib/skeleton.js +3 -0
- package/package.json +66 -4
- package/plugin.json +12 -0
- package/rules/AGENTS.md +20 -0
- package/scripts/read-guard-hook.js +266 -0
- package/skills/code-skeleton/SKILL.md +34 -0
- package/skills/token-audit/SKILL.md +38 -0
- package/targets/antigravity.js +150 -0
- package/targets/claude-code.js +245 -0
- package/targets/codex.js +100 -0
- package/targets/index.js +75 -0
- package/targets/shared.js +103 -0
- package/tools/agy-audit/cli.js +114 -0
- package/tools/agy-audit/lib/analyzer.js +864 -0
- package/tools/agy-audit/lib/compare.js +66 -0
- package/tools/agy-audit/lib/formatter.js +448 -0
- package/tools/agy-audit/lib/paths.js +437 -0
- package/tools/agy-audit/lib/project.js +497 -0
- package/tools/repo-skeleton/cli.js +109 -0
- package/tools/repo-skeleton/lib/skeleton.js +1511 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { analyzeSession } = require('./analyzer');
|
|
4
|
+
|
|
5
|
+
function calcDelta(beforeVal, afterVal) {
|
|
6
|
+
const b = beforeVal || 0;
|
|
7
|
+
const a = afterVal || 0;
|
|
8
|
+
const delta = Number((a - b).toFixed(1));
|
|
9
|
+
let savedPct = null;
|
|
10
|
+
if (b > 0) {
|
|
11
|
+
savedPct = Number((((b - a) / b) * 100).toFixed(1));
|
|
12
|
+
} else if (a === 0) {
|
|
13
|
+
savedPct = 0;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
before: b,
|
|
17
|
+
after: a,
|
|
18
|
+
delta,
|
|
19
|
+
savedPct
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function compareSessions(idBefore, idAfter) {
|
|
24
|
+
const before = analyzeSession(idBefore);
|
|
25
|
+
const after = analyzeSession(idAfter);
|
|
26
|
+
|
|
27
|
+
const bMaxChars = before.stats.maxSingleStepOutput ? before.stats.maxSingleStepOutput.outputChars : 0;
|
|
28
|
+
const aMaxChars = after.stats.maxSingleStepOutput ? after.stats.maxSingleStepOutput.outputChars : 0;
|
|
29
|
+
const bMaxTokens = before.stats.maxSingleStepOutput ? before.stats.maxSingleStepOutput.outputEstTokens : 0;
|
|
30
|
+
const aMaxTokens = after.stats.maxSingleStepOutput ? after.stats.maxSingleStepOutput.outputEstTokens : 0;
|
|
31
|
+
|
|
32
|
+
const metrics = {
|
|
33
|
+
durationSec: calcDelta(before.stats.durationSec, after.stats.durationSec),
|
|
34
|
+
totalTurns: calcDelta(before.stats.totalTurns, after.stats.totalTurns),
|
|
35
|
+
totalSteps: calcDelta(before.stats.totalSteps, after.stats.totalSteps),
|
|
36
|
+
plannerSteps: calcDelta(before.stats.plannerSteps, after.stats.plannerSteps),
|
|
37
|
+
totalToolCalls: calcDelta(before.stats.totalToolCalls, after.stats.totalToolCalls),
|
|
38
|
+
readTotalCount: calcDelta(before.stats.readTotalCount, after.stats.readTotalCount),
|
|
39
|
+
blindReadCount: calcDelta(before.stats.blindReadCount, after.stats.blindReadCount),
|
|
40
|
+
rangedReadCount: calcDelta(before.stats.rangedReadCount, after.stats.rangedReadCount),
|
|
41
|
+
totalToolOutputChars: calcDelta(before.stats.totalToolOutputChars, after.stats.totalToolOutputChars),
|
|
42
|
+
totalToolOutputBytes: calcDelta(before.stats.totalToolOutputBytes, after.stats.totalToolOutputBytes),
|
|
43
|
+
totalToolOutputEstTokens: calcDelta(before.stats.totalToolOutputEstTokens, after.stats.totalToolOutputEstTokens),
|
|
44
|
+
maxStepBloatChars: calcDelta(bMaxChars, aMaxChars),
|
|
45
|
+
maxStepBloatEstTokens: calcDelta(bMaxTokens, aMaxTokens),
|
|
46
|
+
totalInputTokens: calcDelta(before.stats.totalInputTokens, after.stats.totalInputTokens),
|
|
47
|
+
totalCacheReadTokens: calcDelta(before.stats.totalCacheReadTokens, after.stats.totalCacheReadTokens),
|
|
48
|
+
totalOutputTokens: calcDelta(before.stats.totalOutputTokens, after.stats.totalOutputTokens),
|
|
49
|
+
totalThroughputTokens: calcDelta(before.stats.totalThroughputTokens, after.stats.totalThroughputTokens),
|
|
50
|
+
cacheHitRatePct: calcDelta(before.stats.cacheHitRatePct, after.stats.cacheHitRatePct),
|
|
51
|
+
cacheCliffCount: calcDelta(before.stats.cacheCliffCount, after.stats.cacheCliffCount),
|
|
52
|
+
peakContextTokens: calcDelta(before.stats.peakContextTokens, after.stats.peakContextTokens),
|
|
53
|
+
peakContextPct256k: calcDelta(before.stats.peakContextPct256k, after.stats.peakContextPct256k),
|
|
54
|
+
compactionCount: calcDelta(before.stats.compactionCount, after.stats.compactionCount)
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
before,
|
|
59
|
+
after,
|
|
60
|
+
metrics
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = {
|
|
65
|
+
compareSessions
|
|
66
|
+
};
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function fmtNum(n) {
|
|
4
|
+
return (n ?? 0).toLocaleString('en-US');
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function fmtBytes(bytes) {
|
|
8
|
+
if (!bytes || bytes < 1024) return `${bytes || 0} B`;
|
|
9
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function fmtDuration(seconds) {
|
|
13
|
+
if (seconds === null || seconds === undefined) return '-';
|
|
14
|
+
if (seconds <= 0) return '< 1s';
|
|
15
|
+
const h = Math.floor(seconds / 3600);
|
|
16
|
+
const m = Math.floor((seconds % 3600) / 60);
|
|
17
|
+
const s = seconds % 60;
|
|
18
|
+
const parts = [];
|
|
19
|
+
if (h > 0) parts.push(`${h}h`);
|
|
20
|
+
if (m > 0) parts.push(`${m}m`);
|
|
21
|
+
if (s > 0 || parts.length === 0) parts.push(`${s}s`);
|
|
22
|
+
return parts.join(' ');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function truncateText(str, maxLen = 72) {
|
|
26
|
+
if (!str) return '-';
|
|
27
|
+
const singleLine = String(str).replace(/\r?\n/g, ' ').trim();
|
|
28
|
+
if (singleLine.length <= maxLen) return singleLine;
|
|
29
|
+
return singleLine.slice(0, maxLen - 3) + '...';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function escapePipe(str) {
|
|
33
|
+
return String(str || '').replace(/\|/g, '\\|');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function fmtDurationWithSec(seconds) {
|
|
37
|
+
const sec = seconds ?? 0;
|
|
38
|
+
const mins = (sec / 60).toFixed(1);
|
|
39
|
+
return `${fmtNum(sec)}s (${mins}m)`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function fmtDelta(delta, suffix = '') {
|
|
43
|
+
const d = delta ?? 0;
|
|
44
|
+
const sign = d > 0 ? '+' : '';
|
|
45
|
+
return `${sign}${fmtNum(d)}${suffix}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function formatSessionMarkdown(report) {
|
|
49
|
+
const {
|
|
50
|
+
meta,
|
|
51
|
+
stats,
|
|
52
|
+
slowestSteps = [],
|
|
53
|
+
mcpAudit,
|
|
54
|
+
turnDeltas = [],
|
|
55
|
+
checkpoints = [],
|
|
56
|
+
cacheCliffs = [],
|
|
57
|
+
toolBreakdown,
|
|
58
|
+
topBloats
|
|
59
|
+
} = report;
|
|
60
|
+
const lines = [];
|
|
61
|
+
|
|
62
|
+
lines.push(`## 🔍 会话账单体检: ${meta.title} (\`${meta.shortId}\`)`);
|
|
63
|
+
lines.push(`- **完整 ID**: \`${meta.conversationId}\``);
|
|
64
|
+
if (meta.workspace) lines.push(`- **工作空间**: \`${meta.workspace}\``);
|
|
65
|
+
lines.push(`- **日志来源**: \`${meta.logType}\` (${fmtBytes(meta.logBytes)}) | **耗时**: ${fmtDurationWithSec(stats.durationSec)}`);
|
|
66
|
+
lines.push('');
|
|
67
|
+
|
|
68
|
+
lines.push(`### 📊 核心量化指标`);
|
|
69
|
+
lines.push('');
|
|
70
|
+
lines.push(`| 指标 | 数值 | 说明 |`);
|
|
71
|
+
lines.push(`| :--- | :--- | :--- |`);
|
|
72
|
+
lines.push(`| **会话总耗时** | ${fmtDurationWithSec(stats.durationSec)} | 首步至末步 \`created_at\` 差值 |`);
|
|
73
|
+
lines.push(`| **总轮次 / 总步数** | ${fmtNum(stats.totalTurns)} 轮 / ${fmtNum(stats.totalSteps)} 步 | 模型响应 ${fmtNum(stats.plannerSteps)} 次,工具调用 ${fmtNum(stats.totalToolCalls)} 次 |`);
|
|
74
|
+
lines.push(`| **\`read_file\` 读取模式** | 总计 **${fmtNum(stats.readTotalCount)}** 次(盲读 **${fmtNum(stats.blindReadCount)}** / 按行 **${fmtNum(stats.rangedReadCount)}**) | 无行号全量盲读 vs 带 \`StartLine\`/\`EndLine\` 精准读取 |`);
|
|
75
|
+
|
|
76
|
+
if (mcpAudit) {
|
|
77
|
+
let mcpBadge = `✅ **0** 个外部 MCP(已净身 / 无全局继承)`;
|
|
78
|
+
if (mcpAudit.mountedCount > 0) {
|
|
79
|
+
const srvList = mcpAudit.servers
|
|
80
|
+
.map(s => `\`${s.name}\` (${s.callCount > 0 ? `调用 ${s.callCount} 次` : '0 调用空载'})`)
|
|
81
|
+
.join(', ');
|
|
82
|
+
mcpBadge = `${mcpAudit.unusedServerNames.length > 0 ? '⚠️' : '🔌'} 挂载 **${mcpAudit.mountedCount}** 个: ${srvList}`;
|
|
83
|
+
} else if (!mcpAudit.detectedFromSessionDb) {
|
|
84
|
+
mcpBadge = `**0** 次外部 MCP 调用 *(纯日志模式)*`;
|
|
85
|
+
}
|
|
86
|
+
lines.push(`| **实际挂载外部 MCP 服务** | ${mcpBadge} | 前缀: ${mcpAudit.prefixes.length > 0 ? mcpAudit.prefixes.map(p => `\`${p}\``).join(', ') : '无'} |`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
lines.push(`| **工具输入 (参数) 总量** | ${fmtNum(stats.totalToolInputChars)} 字符 (${fmtBytes(stats.totalToolInputBytes)}) | 估算 **${fmtNum(stats.totalToolInputEstTokens)}** Token (\`ceil(chars/3.5)\`) |`);
|
|
90
|
+
lines.push(`| **工具输出 (上下文注入) 总量** | ${fmtNum(stats.totalToolOutputChars)} 字符 (${fmtBytes(stats.totalToolOutputBytes)}) | 估算 **${fmtNum(stats.totalToolOutputEstTokens)}** Token (\`ceil(chars/3.5)\`) |`);
|
|
91
|
+
|
|
92
|
+
if (stats.hasUsageMetrics) {
|
|
93
|
+
lines.push(`| **首步冷启动底座 Input** | **${fmtNum(stats.coldStartInputTokens)}** | 第 1 步加载规则、技能描述、内置工具与 MCP Schema |`);
|
|
94
|
+
lines.push(`| **实测 Input Tokens** | **${fmtNum(stats.totalInputTokens)}** | 统计自 ${stats.usageFieldSteps} 次模型调用 |`);
|
|
95
|
+
lines.push(`| **实测 Cache Read Tokens** | **${fmtNum(stats.totalCacheReadTokens)}** | 历史上下文缓存重复计费滚雪球命中量 |`);
|
|
96
|
+
lines.push(`| **实测缓存命中率** | **${stats.cacheHitRatePct}%**(预热后 **${stats.postWarmupCacheHitRatePct}%**) | \`cache_read / (input + cache_read)\` |`);
|
|
97
|
+
const cliffBadge = stats.cacheCliffCount > 0
|
|
98
|
+
? `⚠️ 检出 **${stats.cacheCliffCount}** 次断层(重算浪费 ~**${fmtNum(stats.cacheRebilledTokens)}** Input)`
|
|
99
|
+
: `✅ **0** 次断层`;
|
|
100
|
+
lines.push(`| **Prefix Cache 断层告警** | ${cliffBadge} | 检测连续步骤间 \`cache_read\` 骤降且 \`input\` 暴涨 |`);
|
|
101
|
+
lines.push(`| **实测 Output Tokens** | **${fmtNum(stats.totalOutputTokens)}** | 模型生成输出 Token |`);
|
|
102
|
+
lines.push(`| **总 Token 吞吐** | **${fmtNum(stats.totalThroughputTokens)}** | \`input + cache_read + output\` |`);
|
|
103
|
+
lines.push(`| **峰值上下文水位** | **${fmtNum(stats.peakContextTokens)}**(三代 ~256K 占 **${stats.peakContextPct256k}%** / 四代推测 ~512K 占 **${stats.peakContextPct512k ?? Number(((stats.peakContextTokens / 512000) * 100).toFixed(1))}%**) | Step ${stats.peakContextStepIndex ?? '-'} 达峰;控水位减轮次是降低累计 Cache Read 的核心 |`);
|
|
104
|
+
} else {
|
|
105
|
+
lines.push(`| **实测 Usage 字段** | *(日志无 usage 字段)* | 以字符估算 Token 为准 |`);
|
|
106
|
+
}
|
|
107
|
+
const cpBadge = stats.compactionCount > 0 ? `⚠️ 触发 **${stats.compactionCount}** 次` : `✅ **0** 次`;
|
|
108
|
+
lines.push(`| **自动压缩 (CHECKPOINT)** | ${cpBadge} | 三代常见约 256K 触发,四代实测 440K 未触发(推测约 512K) |`);
|
|
109
|
+
lines.push('');
|
|
110
|
+
|
|
111
|
+
if (stats.hasUsageMetrics) {
|
|
112
|
+
lines.push(`### ⚡ Prefix Cache 命中率与断层诊断`);
|
|
113
|
+
lines.push('');
|
|
114
|
+
lines.push(`- **整体缓存命中率**: **${stats.cacheHitRatePct}%**(剔除首步冷启动后命中率 **${stats.postWarmupCacheHitRatePct}%**,首步底座冷启动 **${fmtNum(stats.coldStartInputTokens)}** Tokens)`);
|
|
115
|
+
if (cacheCliffs.length === 0) {
|
|
116
|
+
lines.push(`- **缓存连续性状态**: ✅ 全程未检出异常 Prefix Cache 断层(历史前缀保持严格追加复用)。`);
|
|
117
|
+
} else {
|
|
118
|
+
lines.push(`- **缓存断层告警**: ⚠️ 共检出 **${cacheCliffs.length}** 次缓存失效断层,估算多花原价 Input **~${fmtNum(stats.cacheRebilledTokens)}** Tokens:`);
|
|
119
|
+
lines.push('');
|
|
120
|
+
lines.push(`| # | 断层步骤 | 间隔时长 | 前步上下文 → 本步 Cache Read | 本步暴涨 Input | 估算重算浪费 | 疑似根因诊断 |`);
|
|
121
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
|
|
122
|
+
for (const c of cacheCliffs) {
|
|
123
|
+
const gapStr = c.idleSeconds !== null ? fmtDuration(c.idleSeconds) : '-';
|
|
124
|
+
lines.push(
|
|
125
|
+
`| ${c.index} | Step ${c.prevStepIndex}→${c.stepIndex} | ${gapStr} | ${fmtNum(c.prevContextTokens)} → **${fmtNum(c.currCacheReadTokens)}** (${c.retentionPct}%) | **${fmtNum(c.currInputTokens)}** | ~${fmtNum(c.estRebilledTokens)} | ${escapePipe(c.reason)} |`
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
lines.push('');
|
|
129
|
+
lines.push(`- **止血建议**: ① 若闲置超过 1 小时缓存已过期,重开干净新会话带上精简结论往往比在巨型旧上下文里硬唤醒更省钱;② 严禁在对话中途动态篡改顶部常驻规则、系统提示词或增删 MCP 工具(破坏前缀只追加性)。`);
|
|
130
|
+
}
|
|
131
|
+
lines.push('');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (checkpoints.length > 0 || stats.hasUsageMetrics) {
|
|
135
|
+
lines.push(`### 🧠 上下文水位与自动压缩诊断`);
|
|
136
|
+
lines.push('');
|
|
137
|
+
if (stats.hasUsageMetrics) {
|
|
138
|
+
const pct512k = stats.peakContextPct512k ?? Number(((stats.peakContextTokens / 512000) * 100).toFixed(1));
|
|
139
|
+
lines.push(`- **峰值上下文**: **${fmtNum(stats.peakContextTokens)}** Tokens(出现在 Step ${stats.peakContextStepIndex ?? '-'};占三代常见 ~256K 压缩线 **${stats.peakContextPct256k}%**,占四代推测 ~512K 压缩线 **${pct512k}%**)`);
|
|
140
|
+
lines.push(`- **压缩阈值背景**: 三代模型常见在 ~256K 触发历史截断压缩,四代模型实测跑上 440K 仍未触发(推测约 512K);无论是否触发压缩,控制上下文水位与减少轮次始终是降低累计 \`Cache Read\` 滚雪球的核心。`);
|
|
141
|
+
}
|
|
142
|
+
if (checkpoints.length === 0) {
|
|
143
|
+
lines.push(`- **自动压缩状态**: ✅ 全程未触发 \`CHECKPOINT\` 自动压缩(上下文未触及失忆截断)。`);
|
|
144
|
+
} else {
|
|
145
|
+
lines.push(`- **自动压缩触发次数**: ⚠️ 共触发 **${checkpoints.length}** 次 \`CHECKPOINT\`(\`# Resuming from a compaction\`):`);
|
|
146
|
+
lines.push('');
|
|
147
|
+
lines.push(`| # | 触发 Step | 压缩前上下文 Tokens | 压缩后剩余 Tokens | 压缩摘要估算 |`);
|
|
148
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- |`);
|
|
149
|
+
for (const cp of checkpoints) {
|
|
150
|
+
const pre = cp.preCompactionTokens > 0 ? fmtNum(cp.preCompactionTokens) : '-';
|
|
151
|
+
const post = cp.postCompactionTokens !== null ? fmtNum(cp.postCompactionTokens) : '-';
|
|
152
|
+
lines.push(`| ${cp.index} | Step ${cp.stepIndex} | ${pre} | ${post} | ~${fmtNum(cp.summaryEstTokens)} (${fmtNum(cp.summaryChars)} chars) |`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
lines.push('');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
lines.push(`### ⏱️ 最慢步骤 Top 3 (耗时瓶颈)`);
|
|
159
|
+
lines.push('');
|
|
160
|
+
if (slowestSteps.length === 0) {
|
|
161
|
+
lines.push(`*(本会话无工具耗时记录)*`);
|
|
162
|
+
} else {
|
|
163
|
+
lines.push(`| # | Step | 工具 | 目标文件 / 命令摘要 | 步骤总耗时 | 工具纯执行耗时 | 输出体积 |`);
|
|
164
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
|
|
165
|
+
for (const s of slowestSteps) {
|
|
166
|
+
const stepLabel = s.resultStepIndex !== null ? `${s.stepIndex}→${s.resultStepIndex}` : `${s.stepIndex}`;
|
|
167
|
+
const execStr = s.execDurationSec !== null && s.execDurationSec !== undefined ? `${s.execDurationSec}s` : '-';
|
|
168
|
+
lines.push(
|
|
169
|
+
`| ${s.rank} | ${stepLabel} | \`${s.toolName}\` | \`${escapePipe(truncateText(s.target, 56))}\` | **${s.durationSec}s** | ${execStr} | ${fmtBytes(s.outputBytes)} |`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
lines.push('');
|
|
174
|
+
|
|
175
|
+
if (mcpAudit) {
|
|
176
|
+
lines.push(`### 🔌 外部 MCP 挂载与继承审计`);
|
|
177
|
+
lines.push('');
|
|
178
|
+
if (mcpAudit.mountedCount === 0) {
|
|
179
|
+
lines.push(
|
|
180
|
+
mcpAudit.detectedFromSessionDb
|
|
181
|
+
? `- **挂载状态**: ✅ 本会话未挂载任何外部 MCP 服务(\`inheritMcp: false\` 净身已生效或全局未开启)。`
|
|
182
|
+
: `- **挂载状态**: 本会话日志未检出任何外部 MCP 工具调用。`
|
|
183
|
+
);
|
|
184
|
+
} else {
|
|
185
|
+
lines.push(`- **实际挂载外部 MCP 服务 (${mcpAudit.mountedCount} 个)**: ${mcpAudit.servers.map(s => `\`${s.name}\``).join(', ')}(工具前缀: ${mcpAudit.prefixes.map(p => `\`${p}\``).join(', ')})`);
|
|
186
|
+
if (mcpAudit.unusedServerNames.length > 0) {
|
|
187
|
+
lines.push(`- **空载继承告警**: ⚠️ 检出 **[${mcpAudit.unusedServerNames.join(', ')}]** 全程 **0 次调用**却随每步常驻挂载,累计产生约 **~${fmtNum(mcpAudit.estSessionTaxTokens)}** Token 空载底座税(建议非浏览器会话设 \`inheritMcp: false\`)。`);
|
|
188
|
+
}
|
|
189
|
+
lines.push('');
|
|
190
|
+
lines.push(`| MCP 服务名 | 工具前缀 | 工具规模 (Eager / Lazy) | 实际调用次数 | 估算单步底座税 |`);
|
|
191
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- |`);
|
|
192
|
+
for (const srv of mcpAudit.servers) {
|
|
193
|
+
const scale = srv.eagerToolCount || srv.lazyToolCount
|
|
194
|
+
? `${srv.eagerToolCount} / ${srv.lazyToolCount}`
|
|
195
|
+
: (srv.invokedTools.length > 0 ? `已调: ${srv.invokedTools.slice(0, 3).join(', ')}` : '-');
|
|
196
|
+
lines.push(
|
|
197
|
+
`| \`${srv.name}\` | \`${srv.prefix}\` | ${scale} | **${srv.callCount}** | ~${fmtNum(srv.estTokensPerStep)} |`
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
lines.push('');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (stats.hasUsageMetrics && turnDeltas.length > 0) {
|
|
205
|
+
lines.push(`### 📈 每轮上下文净增波动与缓存命中率`);
|
|
206
|
+
lines.push('');
|
|
207
|
+
lines.push(`- **单轮净增极值**: 最高单轮净增 **${fmtDelta(stats.maxTurnNetContextDeltaTokens)}** Tokens | 平均每轮净增 **${fmtDelta(stats.avgTurnNetContextDeltaTokens)}** Tokens`);
|
|
208
|
+
lines.push('');
|
|
209
|
+
lines.push(`| 轮次 | Step 范围 | 模型响应 / 工具 | 轮末上下文水位 | 本轮上下文净增 | 本轮 Input / Cache Read | 本轮缓存命中率 |`);
|
|
210
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
|
|
211
|
+
const displayTurns = turnDeltas.length > 15
|
|
212
|
+
? [...turnDeltas.slice(0, 8), null, ...turnDeltas.slice(-6)]
|
|
213
|
+
: turnDeltas;
|
|
214
|
+
for (const t of displayTurns) {
|
|
215
|
+
if (!t) {
|
|
216
|
+
lines.push(`| ... | *(省略中间 ${turnDeltas.length - 14} 轮)* | ... | ... | ... | ... | ... |`);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const stepSpan = t.firstStepIndex !== null ? `${t.firstStepIndex}→${t.lastStepIndex}` : '-';
|
|
220
|
+
const cpNote = t.compactionsInTurn > 0 ? ` *(含压缩)*` : '';
|
|
221
|
+
lines.push(
|
|
222
|
+
`| Turn ${t.turnIndex} | ${stepSpan} | ${t.plannerSteps} 次 / ${t.toolCalls} 次 | ${fmtNum(t.endContextTokens)} | **${fmtDelta(t.netContextDeltaTokens)}**${cpNote} | ${fmtNum(t.inputTokens)} / ${fmtNum(t.cacheReadTokens)} | **${t.cacheHitRatePct}%** |`
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
lines.push('');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
lines.push(`### 🔥 单步上下文塞入 Top 5 烧钱步骤`);
|
|
229
|
+
lines.push('');
|
|
230
|
+
if (topBloats.length === 0) {
|
|
231
|
+
lines.push(`*(本会话无工具调用记录)*`);
|
|
232
|
+
} else {
|
|
233
|
+
lines.push(`| # | Step | 工具 | 目标文件 / 命令 | 塞入字节 / 字符 | 估算 Token | 后续剩余轮次 / 调用 | 估算缓存滚雪球 |`);
|
|
234
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
|
|
235
|
+
for (const b of topBloats) {
|
|
236
|
+
const modeTag = b.isReadFile ? (b.isBlindRead ? ' [盲读]' : ' [分段]') : '';
|
|
237
|
+
const stepLabel = b.resultStepIndex !== null ? `${b.stepIndex}→${b.resultStepIndex}` : `${b.stepIndex}`;
|
|
238
|
+
lines.push(
|
|
239
|
+
`| ${b.rank} | ${stepLabel} | \`${b.toolName}\`${modeTag} | \`${escapePipe(truncateText(b.target, 56))}\` | ${fmtBytes(b.outputBytes)} (${fmtNum(b.outputChars)} chars) | **${fmtNum(b.outputEstTokens)}** | ${b.remainingTurns} 轮 / ${b.remainingPlannerSteps} 次 | ~${fmtNum(b.estSnowballTokens)} |`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
lines.push('');
|
|
244
|
+
|
|
245
|
+
const toolsSorted = Object.entries(toolBreakdown).sort((a, b) => b[1].outputBytes - a[1].outputBytes);
|
|
246
|
+
if (toolsSorted.length > 0) {
|
|
247
|
+
lines.push(`### 🛠️ 工具维度分布`);
|
|
248
|
+
lines.push('');
|
|
249
|
+
lines.push(`| 工具名 | 次数 | 传入估算 Token | 注入输出字节 | 注入估算 Token |`);
|
|
250
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- |`);
|
|
251
|
+
for (const [name, bd] of toolsSorted) {
|
|
252
|
+
lines.push(`| \`${name}\` | ${bd.count} | ${fmtNum(bd.inputEstTokens)} | ${fmtBytes(bd.outputBytes)} | ${fmtNum(bd.outputEstTokens)} |`);
|
|
253
|
+
}
|
|
254
|
+
lines.push('');
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return lines.join('\n');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function fmtPct(savedPct, invertMeaning = false) {
|
|
261
|
+
if (savedPct === null || savedPct === undefined) return '-';
|
|
262
|
+
if (savedPct > 0) return invertMeaning ? `-${savedPct}%` : `**-${savedPct}%** (省)`;
|
|
263
|
+
if (savedPct < 0) return `+${Math.abs(savedPct)}%`;
|
|
264
|
+
return '0%';
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function formatCompareMarkdown(cmp) {
|
|
268
|
+
const { before, after, metrics } = cmp;
|
|
269
|
+
const lines = [];
|
|
270
|
+
|
|
271
|
+
lines.push(`## ⚖️ 会话优化前后对比报告`);
|
|
272
|
+
lines.push(`- **对照组 (Baseline)**: \`${before.meta.shortId}\` — ${before.meta.title} (${fmtDurationWithSec(before.stats.durationSec)})`);
|
|
273
|
+
lines.push(`- **实验组 (Tokless)**: \`${after.meta.shortId}\` — ${after.meta.title} (${fmtDurationWithSec(after.stats.durationSec)})`);
|
|
274
|
+
lines.push('');
|
|
275
|
+
|
|
276
|
+
lines.push(`| 对比维度 | 对照组 (${before.meta.shortId}) | 实验组 (${after.meta.shortId}) | 差值 | 节省比例 |`);
|
|
277
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- |`);
|
|
278
|
+
|
|
279
|
+
const rows = [
|
|
280
|
+
[
|
|
281
|
+
'总耗时 (秒 / 分钟)',
|
|
282
|
+
fmtDurationWithSec(metrics.durationSec.before),
|
|
283
|
+
fmtDurationWithSec(metrics.durationSec.after),
|
|
284
|
+
fmtDelta(metrics.durationSec.delta, 's'),
|
|
285
|
+
fmtPct(metrics.durationSec.savedPct)
|
|
286
|
+
],
|
|
287
|
+
['总轮次 (Turns)', fmtNum(metrics.totalTurns.before), fmtNum(metrics.totalTurns.after), fmtDelta(metrics.totalTurns.delta), fmtPct(metrics.totalTurns.savedPct)],
|
|
288
|
+
['总步数 (Steps)', fmtNum(metrics.totalSteps.before), fmtNum(metrics.totalSteps.after), fmtDelta(metrics.totalSteps.delta), fmtPct(metrics.totalSteps.savedPct)],
|
|
289
|
+
['模型调用次数 (Planner)', fmtNum(metrics.plannerSteps.before), fmtNum(metrics.plannerSteps.after), fmtDelta(metrics.plannerSteps.delta), fmtPct(metrics.plannerSteps.savedPct)],
|
|
290
|
+
['工具调用总次数', fmtNum(metrics.totalToolCalls.before), fmtNum(metrics.totalToolCalls.after), fmtDelta(metrics.totalToolCalls.delta), fmtPct(metrics.totalToolCalls.savedPct)],
|
|
291
|
+
['`read_file` 总次数', fmtNum(metrics.readTotalCount.before), fmtNum(metrics.readTotalCount.after), fmtDelta(metrics.readTotalCount.delta), fmtPct(metrics.readTotalCount.savedPct)],
|
|
292
|
+
['├─ 无行号全量盲读', fmtNum(metrics.blindReadCount.before), fmtNum(metrics.blindReadCount.after), fmtDelta(metrics.blindReadCount.delta), fmtPct(metrics.blindReadCount.savedPct)],
|
|
293
|
+
['└─ 带 `StartLine`/`EndLine` 精准读取', fmtNum(metrics.rangedReadCount.before), fmtNum(metrics.rangedReadCount.after), fmtDelta(metrics.rangedReadCount.delta), fmtPct(metrics.rangedReadCount.savedPct, true)],
|
|
294
|
+
['工具注入总字符数', fmtNum(metrics.totalToolOutputChars.before), fmtNum(metrics.totalToolOutputChars.after), fmtDelta(metrics.totalToolOutputChars.delta), fmtPct(metrics.totalToolOutputChars.savedPct)],
|
|
295
|
+
['工具注入估算新增 Token', fmtNum(metrics.totalToolOutputEstTokens.before), fmtNum(metrics.totalToolOutputEstTokens.after), fmtDelta(metrics.totalToolOutputEstTokens.delta), fmtPct(metrics.totalToolOutputEstTokens.savedPct)],
|
|
296
|
+
[
|
|
297
|
+
'最大单步膨胀 (字符 / Est Token)',
|
|
298
|
+
`${fmtNum(metrics.maxStepBloatChars.before)} / ${fmtNum(metrics.maxStepBloatEstTokens.before)}`,
|
|
299
|
+
`${fmtNum(metrics.maxStepBloatChars.after)} / ${fmtNum(metrics.maxStepBloatEstTokens.after)}`,
|
|
300
|
+
fmtDelta(metrics.maxStepBloatEstTokens.delta),
|
|
301
|
+
fmtPct(metrics.maxStepBloatEstTokens.savedPct)
|
|
302
|
+
]
|
|
303
|
+
];
|
|
304
|
+
|
|
305
|
+
if (before.stats.hasUsageMetrics || after.stats.hasUsageMetrics) {
|
|
306
|
+
rows.push(
|
|
307
|
+
['累计 Input Tokens', fmtNum(metrics.totalInputTokens.before), fmtNum(metrics.totalInputTokens.after), fmtDelta(metrics.totalInputTokens.delta), fmtPct(metrics.totalInputTokens.savedPct)],
|
|
308
|
+
['累计 Cache Read Tokens (滚雪球)', fmtNum(metrics.totalCacheReadTokens.before), fmtNum(metrics.totalCacheReadTokens.after), fmtDelta(metrics.totalCacheReadTokens.delta), fmtPct(metrics.totalCacheReadTokens.savedPct)],
|
|
309
|
+
['Prefix Cache 命中率 (%)', `${metrics.cacheHitRatePct.before}%`, `${metrics.cacheHitRatePct.after}%`, fmtDelta(metrics.cacheHitRatePct.delta, '%'), '-'],
|
|
310
|
+
['Prefix Cache 断层次数', fmtNum(metrics.cacheCliffCount.before), fmtNum(metrics.cacheCliffCount.after), fmtDelta(metrics.cacheCliffCount.delta), fmtPct(metrics.cacheCliffCount.savedPct)],
|
|
311
|
+
['累计 Output Tokens', fmtNum(metrics.totalOutputTokens.before), fmtNum(metrics.totalOutputTokens.after), fmtDelta(metrics.totalOutputTokens.delta), fmtPct(metrics.totalOutputTokens.savedPct)],
|
|
312
|
+
['总 Token 吞吐 (`input+cache_read+output`)', fmtNum(metrics.totalThroughputTokens.before), fmtNum(metrics.totalThroughputTokens.after), fmtDelta(metrics.totalThroughputTokens.delta), fmtPct(metrics.totalThroughputTokens.savedPct)],
|
|
313
|
+
[
|
|
314
|
+
'峰值上下文水位 (占 ~256K 参考线)',
|
|
315
|
+
`${fmtNum(metrics.peakContextTokens.before)} (${metrics.peakContextPct256k.before}%)`,
|
|
316
|
+
`${fmtNum(metrics.peakContextTokens.after)} (${metrics.peakContextPct256k.after}%)`,
|
|
317
|
+
fmtDelta(metrics.peakContextTokens.delta),
|
|
318
|
+
fmtPct(metrics.peakContextTokens.savedPct)
|
|
319
|
+
]
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
rows.push([
|
|
324
|
+
'自动压缩 (Compaction) 触发次数',
|
|
325
|
+
fmtNum(metrics.compactionCount.before),
|
|
326
|
+
fmtNum(metrics.compactionCount.after),
|
|
327
|
+
fmtDelta(metrics.compactionCount.delta),
|
|
328
|
+
fmtPct(metrics.compactionCount.savedPct)
|
|
329
|
+
]);
|
|
330
|
+
|
|
331
|
+
for (const r of rows) {
|
|
332
|
+
lines.push(`| ${r.join(' | ')} |`);
|
|
333
|
+
}
|
|
334
|
+
lines.push('');
|
|
335
|
+
|
|
336
|
+
return lines.join('\n');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function formatProjectMarkdown(report) {
|
|
340
|
+
const { projectDir, projectName, thresholds, summary, files, flaggedFiles, mcpAndToolTax } = report;
|
|
341
|
+
const lines = [];
|
|
342
|
+
|
|
343
|
+
lines.push(`## 🩺 项目规则、Skill 与 MCP 底座体检: ${projectName}`);
|
|
344
|
+
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
|
+
lines.push('');
|
|
347
|
+
|
|
348
|
+
lines.push(`### 📊 文档负载总览`);
|
|
349
|
+
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\`,命中时读正文 |`);
|
|
354
|
+
lines.push('');
|
|
355
|
+
|
|
356
|
+
if (files.length === 0) {
|
|
357
|
+
lines.push(`*(该项目目录下未发现 AGENTS.md、GEMINI.md、.agents/rules/*.md 或 .agents/skills/*/SKILL.md)*`);
|
|
358
|
+
lines.push('');
|
|
359
|
+
} else {
|
|
360
|
+
lines.push(`### 📁 规则与技能文件明细`);
|
|
361
|
+
lines.push('');
|
|
362
|
+
lines.push(`| 文件路径 | 类别 | 加载模式 | 行数 | 字节数 | 估算 Token | 状态 |`);
|
|
363
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- | :--- |`);
|
|
364
|
+
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} |`);
|
|
369
|
+
}
|
|
370
|
+
lines.push('');
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (mcpAndToolTax) {
|
|
374
|
+
lines.push(`### 🔌 MCP 与工具底座空载税估算`);
|
|
375
|
+
lines.push('');
|
|
376
|
+
lines.push(`| 底座构成项 | 数量 / 状态 | 单步固定底座估算 | 30 步会话累计滚雪球 | 说明 |`);
|
|
377
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- |`);
|
|
378
|
+
lines.push(
|
|
379
|
+
`| **默认全量内置工具** | 全量工具集 | ~**${fmtNum(mcpAndToolTax.builtinDefaultToolsEstTokensPerStep)}** Token/步 | ~${fmtNum(mcpAndToolTax.builtinDefaultToolsEstTokensPerStep * 30)} | 未指定精简 \`tools\` 时的默认内置工具 Schema |`
|
|
380
|
+
);
|
|
381
|
+
lines.push(
|
|
382
|
+
`| **活跃 MCP Servers** | 启用 **${mcpAndToolTax.enabledMcpCount}** / 共 ${mcpAndToolTax.totalMcpCount} 个 | ~**${fmtNum(mcpAndToolTax.activeMcpEstTokensPerStep)}** Token/步 | ~${fmtNum(mcpAndToolTax.activeMcpEstTokensPerStep * 30)} | 全局 \`~/.gemini/config/mcp_config.json\` 及插件/工作区 |`
|
|
383
|
+
);
|
|
384
|
+
lines.push(
|
|
385
|
+
`| **默认会话合计空载税** | 未净身默认态 | **~${fmtNum(mcpAndToolTax.defaultSessionEstTokensPerStep)}** Token/步 | **~${fmtNum(mcpAndToolTax.est30StepSnowballTokens)}** | 尚未发任何业务代码前每步必背的工具底座 |`
|
|
386
|
+
);
|
|
387
|
+
lines.push('');
|
|
388
|
+
|
|
389
|
+
if (mcpAndToolTax.mcpServers.length > 0) {
|
|
390
|
+
lines.push(`#### 已发现的 MCP Server 清单`);
|
|
391
|
+
lines.push('');
|
|
392
|
+
lines.push(`| Server 名称 | 来源范围 | 传输方式 | 状态 | 单步开销估算 |`);
|
|
393
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- |`);
|
|
394
|
+
for (const s of mcpAndToolTax.mcpServers) {
|
|
395
|
+
const stateLabel = s.enabled ? '🟢 已启用' : '⚪ 已禁用';
|
|
396
|
+
lines.push(
|
|
397
|
+
`| \`${escapePipe(s.name)}\` | \`${escapePipe(s.source)}\` | \`${s.transport}\` | ${stateLabel} | ~${fmtNum(s.estTokensPerStep)} Token |`
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
lines.push('');
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (mcpAndToolTax.agents.length > 0) {
|
|
404
|
+
lines.push(`#### 项目专属 Agent 角色净身状态 (\`agents/*.md\`)`);
|
|
405
|
+
lines.push('');
|
|
406
|
+
lines.push(`| 角色名 | 配置文件 | \`inheritMcp\` | 工具授权 (\`tools\`) | 单步工具+MCP底座 | 相比默认每步立省 |`);
|
|
407
|
+
lines.push(`| :--- | :--- | :--- | :--- | :--- | :--- |`);
|
|
408
|
+
for (const a of mcpAndToolTax.agents) {
|
|
409
|
+
const mcpBadge = a.inheritMcp ? '🟡 `true` (继承)' : '✅ `false` (已净身)';
|
|
410
|
+
const toolsLabel = a.hasExplicitTools
|
|
411
|
+
? (a.toolCount === 0 ? '`[]` (0工具纯文本)' : `${a.toolCount} 个 (\`${a.tools.join(', ')}\`)`)
|
|
412
|
+
: '*(未显式收敛)*';
|
|
413
|
+
lines.push(
|
|
414
|
+
`| \`${escapePipe(a.name)}\` | \`${escapePipe(a.relativePath)}\` | ${mcpBadge} | ${toolsLabel} | ~**${fmtNum(a.toolAndMcpPerStep)}** Token | **-${fmtNum(a.savedPerStepTokens)}** Token/步 |`
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
lines.push('');
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
lines.push(`### ✂️ 降维瘦身与净身建议`);
|
|
422
|
+
lines.push('');
|
|
423
|
+
const hasDocFlags = flaggedFiles.length > 0;
|
|
424
|
+
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
|
+
}
|
|
435
|
+
for (const tip of mcpTips) {
|
|
436
|
+
lines.push(`- **MCP / 工具底座净身**: ${tip}`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
lines.push('');
|
|
440
|
+
|
|
441
|
+
return lines.join('\n');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
module.exports = {
|
|
445
|
+
formatSessionMarkdown,
|
|
446
|
+
formatCompareMarkdown,
|
|
447
|
+
formatProjectMarkdown
|
|
448
|
+
};
|