tokless 0.5.1 → 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.
package/index.js CHANGED
@@ -56,12 +56,14 @@ module.exports = {
56
56
  generateRepoMap: skeleton.generateRepoMap,
57
57
  generateSkeleton: skeleton.generateSkeleton,
58
58
  estimateTokens: audit.estimateTokens,
59
+ listSessions: audit.listSessions,
59
60
  analyzeSession: audit.analyzeSession,
60
61
  compareSessions: audit.compareSessions,
61
62
  auditProject: audit.auditProject,
62
63
  auditMcpAndTools: audit.auditMcpAndTools,
63
64
  parseAgentMarkdown: audit.parseAgentMarkdown,
64
65
  formatSessionMarkdown: audit.formatSessionMarkdown,
66
+ formatSessionListMarkdown: audit.formatSessionListMarkdown,
65
67
  formatCompareMarkdown: audit.formatCompareMarkdown,
66
68
  formatProjectMarkdown: audit.formatProjectMarkdown,
67
69
  COMPACTION_THRESHOLD_256K: audit.COMPACTION_THRESHOLD_256K,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokless",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Token optimizer, AST codebase skeletonizer, optional PreToolUse blind-read guard, lightweight role templates, and cache/compaction auditor for AI coding agents.",
5
5
  "license": "MIT",
6
6
  "main": "./index.js",
@@ -39,6 +39,8 @@
39
39
  "uninstall-plugin": "node ./install.js --uninstall",
40
40
  "audit": "node ./tools/agy-audit/cli.js",
41
41
  "skeleton": "node ./tools/repo-skeleton/cli.js",
42
+ "bump": "node ./scripts/bump-version.js",
43
+ "version": "node ./scripts/bump-version.js --sync-from-pkg && git add plugin.json",
42
44
  "test": "node ./tests/run-all.js",
43
45
  "prepublishOnly": "npm test"
44
46
  },
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-tokless",
3
3
  "displayName": "AGY Tokless — Antigravity 省流护栏与账单透视套件",
4
- "version": "0.5.1",
4
+ "version": "0.5.2",
5
5
  "description": "专为 AI 编程打造的省流导航与账单审计插件:提供代码语法骨架提取(repo-skeleton)、可选超大文件盲读骨架导航钩子(PreToolUse Hook,--with-guard 启用)、轻量净身角色模板(agents)以及 Prefix Cache 断层与 MCP 底座税体检工具(agy-audit)。",
6
6
  "disabled": false,
7
7
  "suggestedPrompts": [
package/rules/AGENTS.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # AI 编程省流读取、净身角色与缓存保护规范 (tokless)
2
2
 
3
3
  ## 1. 先看代码骨架,再按行号精准读取 (`tokless skeleton` / `repo-skeleton`)
4
- - **拒绝无行号盲读大代码文件**:探索陌生模块或大源码文件时先提取语法骨架定位行号,避免不带起止行号(`StartLine`/`EndLine` 或 `offset`/`limit`)直接全量盲读大文件(可选启用 `--with-guard` 读前护栏后,仅对 `>800` 行无行号盲读自动返回全文骨架辅助导航,凡传入显式行号参数一律放行)。
4
+ - **拒绝无行号盲读与“伪精准”大区间硬读**:探索陌生模块或中大型代码文件(约 `>200` 行)前必须先提取语法骨架定位行号;严禁不抽骨架直接无行号盲读,或用 `StartLine=1, EndLine=800` 等泛大跨度区间伪装按行读取来跳过骨架导航(可选启用 `--with-guard` 读前护栏后,仅对 `>800` 行无行号盲读自动返回全文骨架辅助导航,凡传入显式行号参数一律放行)。
5
5
  - **两步精准定位法**:
6
6
  1. 探索陌生目录或大文件时,先用 `tokless skeleton`(兼容 `repo-skeleton`)提取语法签名与 `[L起-L止]` 行号(0 模型 Token,比盲读全文省 85%~97% 探索开销):
7
7
  - 全局 CLI(推荐): `tokless skeleton <目录或文件路径> --depth 2`
8
8
  - macOS / Linux: `node "$HOME/.gemini/config/plugins/agy-tokless/tools/repo-skeleton/cli.js" <目录或文件路径> --depth 2`
9
9
  - Windows (PowerShell): `node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\repo-skeleton\cli.js" <目录或文件路径> --depth 2`
10
- 2. 根据骨架中的 `[L起-L止]` 行号,调用 `read_file(Path, StartLine, EndLine)`(或 `Read(file_path, offset, limit)`)按需完整读取目标函数或逻辑块(无单次行数跨度硬限制,只要有明确目标区间即可一次读完)。
10
+ 2. 根据骨架中的 `[L起-L止]` 行号,调用 `read_file(Path, StartLine, EndLine)`(或 `Read(file_path, offset, limit)`)按需完整读取目标函数或逻辑块(针对骨架已定位的明确目标区间无单次跨度硬限制,可一次读完;未定位前禁止用 `1-800` 等满额区间批量扫读多个陌生文件)。
11
11
 
12
12
  ## 2. 轻量角色净身(卸除无关 MCP 与工具底座税)
13
13
  - 纯代码编写或只读代码审查会话优先启用 `inheritMcp: false` 及最小 `tools` 清单(如内置净身角色 `tokless-coder`、`tokless-reviewer`),剥离用不上的浏览器/外部 MCP Schema 每步固定底座税。
14
14
 
15
15
  ## 3. 本地账单透视、Prefix Cache 保护与控水位减轮次 (`tokless audit` / `agy-audit`)
16
- - **0 Token 账单与底座税体检**(支持 `session <ID>` 查缓存断层与 Top 5 膨胀步、`compare <前ID> <后ID>`、`project <项目目录>` 查规则肥胖度与 MCP 空载税):
17
- - 全局 CLI(推荐): `tokless audit <session|compare|project> <参数>`
18
- - macOS / Linux: `node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" <session|compare|project> <参数>`
19
- - Windows (PowerShell): `node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" <session|compare|project> <参数>`
16
+ - **0 Token 账单与底座税体检**(支持 `list` 列最近会话、`session <ID|latest>` 查缓存断层/模型切换归因与 Top 5 膨胀步、`compare <前ID> <后ID>`、`project <项目目录>` 查常驻规则与 MCP 底座账单):
17
+ - 全局 CLI(推荐): `tokless audit <list|session|compare|project> <参数>`
18
+ - macOS / Linux: `node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" <list|session|compare|project> <参数>`
19
+ - Windows (PowerShell): `node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" <list|session|compare|project> <参数>`
20
20
  - **严控终端输出与保护 Prefix Cache**:`run_command` 必须主动限制长日志输出规模;对话中途保持顶部规则稳定只追加,控制上下文水位与对话轮次以降低累计 `Cache Read` 滚雪球并避免触发历史自动压缩(三代模型常见约 256K,四代模型实测跑上 440K 未触发、推测约 512K)。
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ const REPO_ROOT = path.resolve(__dirname, '..');
8
+ const PKG_PATH = path.join(REPO_ROOT, 'package.json');
9
+ const PLUGIN_PATH = path.join(REPO_ROOT, 'plugin.json');
10
+ const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
11
+
12
+ function readJson(filePath) {
13
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
14
+ }
15
+
16
+ function writeJson(filePath, obj) {
17
+ fs.writeFileSync(filePath, JSON.stringify(obj, null, 2) + '\n', 'utf8');
18
+ }
19
+
20
+ function bumpVersion(rawTarget, options = {}) {
21
+ const rootDir = options.rootDir || REPO_ROOT;
22
+ const pkgPath = path.join(rootDir, 'package.json');
23
+ const pluginPath = path.join(rootDir, 'plugin.json');
24
+
25
+ const pkg = readJson(pkgPath);
26
+ const plugin = readJson(pluginPath);
27
+
28
+ const normalized = options.syncFromPkg
29
+ ? String(pkg.version || '').trim()
30
+ : String(rawTarget || '').trim().replace(/^v/i, '');
31
+
32
+ if (!SEMVER_RE.test(normalized)) {
33
+ throw new Error(
34
+ `Invalid semver version "${rawTarget || ''}". Usage: npm run bump -- <major.minor.patch>`
35
+ );
36
+ }
37
+
38
+ const prevPkg = pkg.version;
39
+ const prevPlugin = plugin.version;
40
+
41
+ pkg.version = normalized;
42
+ plugin.version = normalized;
43
+
44
+ writeJson(pkgPath, pkg);
45
+ writeJson(pluginPath, plugin);
46
+
47
+ return {
48
+ version: normalized,
49
+ updated: [
50
+ { file: 'package.json', from: prevPkg, to: normalized },
51
+ { file: 'plugin.json', from: prevPlugin, to: normalized },
52
+ ],
53
+ };
54
+ }
55
+
56
+ function main() {
57
+ const args = process.argv.slice(2);
58
+ const syncFromPkg = args.includes('--sync-from-pkg');
59
+ const positional = args.find((a) => !a.startsWith('-'));
60
+
61
+ if (!syncFromPkg && !positional) {
62
+ console.error('Usage: npm run bump -- <version> (e.g. npm run bump -- 0.5.2)');
63
+ process.exit(1);
64
+ }
65
+
66
+ try {
67
+ const result = bumpVersion(positional, { syncFromPkg });
68
+ for (const item of result.updated) {
69
+ console.log(`[bump] ${item.file}: ${item.from} -> ${item.to}`);
70
+ }
71
+ } catch (err) {
72
+ console.error(`[bump] ${err.message}`);
73
+ process.exit(1);
74
+ }
75
+ }
76
+
77
+ if (require.main === module) {
78
+ main();
79
+ }
80
+
81
+ module.exports = { bumpVersion };
@@ -4,27 +4,17 @@
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
 
7
+ const { SUPPORTED_EXTS } = require('../tools/repo-skeleton/lib/core/registry');
8
+
7
9
  const READ_GUARD_SCRIPT_PATH = __filename;
8
10
  const HOOKS_CONFIG_PATH = path.resolve(__dirname, '../hooks.json');
9
11
  const PLUGIN_MANIFEST_PATH = path.resolve(__dirname, '../plugin.json');
12
+ const MAX_SKELETON_ITEMS = 120;
13
+ const MAX_FALLBACK_SEGMENTS = 20;
10
14
 
11
- const GUARDED_CODE_EXTS = new Set([
12
- '.js',
13
- '.mjs',
14
- '.cjs',
15
- '.ts',
16
- '.tsx',
17
- '.jsx',
18
- '.py',
19
- '.go',
20
- '.rs',
21
- '.java',
22
- '.c',
23
- '.cpp',
24
- '.cs',
25
- '.vue',
26
- '.svelte',
27
- ]);
15
+ const GUARDED_CODE_EXTS = new Set(
16
+ [...SUPPORTED_EXTS].filter((ext) => ext !== '.md' && ext !== '.mdx')
17
+ );
28
18
 
29
19
  function loadSkeletonGenerator() {
30
20
  const localLib = path.resolve(__dirname, '../tools/repo-skeleton/lib/skeleton.js');
@@ -50,6 +40,56 @@ function parseLineArg(val) {
50
40
  return Number.isFinite(parsed) ? Math.floor(parsed) : null;
51
41
  }
52
42
 
43
+ function buildFallbackSegments(filePath, totalLines, maxLines) {
44
+ let lines = [];
45
+ try {
46
+ const content = fs.readFileSync(filePath, 'utf8');
47
+ lines = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
48
+ } catch (_) {
49
+ return `(未识别到显式函数/类签名,全文件共 ${totalLines} 行)`;
50
+ }
51
+
52
+ const step = Math.max(200, Math.min(maxLines, 400));
53
+ const out = [`(未识别到显式函数/类签名,按每段 ${step} 行提供首行定位预览:)`];
54
+ let segmentCount = 0;
55
+ for (let start = 1; start <= totalLines; start += step) {
56
+ if (segmentCount >= MAX_FALLBACK_SEGMENTS) {
57
+ out.push(`... (后段 [L${start}-L${totalLines}] 省略,请按区间继续分段读取)`);
58
+ break;
59
+ }
60
+ const end = Math.min(totalLines, start + step - 1);
61
+ let preview = '(空行/注释)';
62
+ for (let idx = start - 1; idx < end && idx < lines.length; idx++) {
63
+ const t = lines[idx].trim();
64
+ if (t) {
65
+ preview = t.length > 60 ? t.slice(0, 57) + '...' : t;
66
+ break;
67
+ }
68
+ }
69
+ out.push(`[L${start}-L${end}] ${preview}`);
70
+ segmentCount++;
71
+ }
72
+ return out.join('\n');
73
+ }
74
+
75
+ function formatBoundedSkeleton(skeleton, filePath, maxLines) {
76
+ if (!skeleton.items || skeleton.items.length === 0) {
77
+ return buildFallbackSegments(filePath, skeleton.totalLines, maxLines);
78
+ }
79
+ if (skeleton.items.length <= MAX_SKELETON_ITEMS) {
80
+ return skeleton.formatted;
81
+ }
82
+ const headLines = skeleton.items.slice(0, MAX_SKELETON_ITEMS).map((item) => {
83
+ const indent = ' '.repeat(item.depth || 0);
84
+ return `${indent}[L${item.startLine}-L${item.endLine}] ${item.signature}`;
85
+ });
86
+ const remaining = skeleton.items.length - MAX_SKELETON_ITEMS;
87
+ headLines.push(
88
+ `... (共 ${skeleton.items.length} 条声明,已截断显示前 ${MAX_SKELETON_ITEMS} 条,剩余 ${remaining} 条请运行 tokless skeleton CLI 或 grep 定位)`
89
+ );
90
+ return headLines.join('\n');
91
+ }
92
+
53
93
  function isClaudeCodePayload(payload, toolName) {
54
94
  if (!payload || typeof payload !== 'object') return false;
55
95
  if (toolName === 'Read') return true;
@@ -140,8 +180,11 @@ function evaluateReadGuard(payloadOrJson, options = {}) {
140
180
 
141
181
  const hasStart = startNum !== null;
142
182
  const hasEnd = endNum !== null;
143
- // 陷阱: 凡传入了显式行号参数一律直接放行(禁设单次跨度上限或拦截 L1~EOF,避免报错重试+拆轮反噬数十万 Cache Read)
144
- if (hasStart || hasEnd) {
183
+ const byteOffsetVal = args.ByteOffset ?? args.byteOffset ?? args.byte_offset;
184
+ const hasByteOffset =
185
+ byteOffsetVal !== undefined && byteOffsetVal !== null && byteOffsetVal !== '';
186
+ // 陷阱: 凡传入了显式行号参数或字节偏移一律直接放行(禁设单次跨度上限或拦截 L1~EOF,避免报错重试+拆轮反噬数十万 Cache Read)
187
+ if (hasStart || hasEnd || hasByteOffset) {
145
188
  return { decision: 'allow', host };
146
189
  }
147
190
 
@@ -156,11 +199,12 @@ function evaluateReadGuard(payloadOrJson, options = {}) {
156
199
  const rangeHint = isClaude
157
200
  ? '重新调用 Read 并传入目标区间的 offset 与 limit'
158
201
  : '重新调用 read_file 并传入目标区间的 StartLine 和 EndLine';
202
+ const skelBody = formatBoundedSkeleton(skeleton, resolvedPath, maxLines);
159
203
 
160
204
  const reason =
161
205
  `[tokless 省流护栏] 目标文件共 ${skeleton.totalLines} 行(超过 ${maxLines} 行无行号读取阈值),已返回语法骨架辅助定位。\n` +
162
206
  `请根据下方该文件的语法骨架与 [L起-L止] 行号范围,${rangeHint}精准读取所需片段:\n\n` +
163
- `${skeleton.formatted}`;
207
+ `${skelBody}`;
164
208
 
165
209
  return { decision: 'deny', reason, host };
166
210
  } catch (_) {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: code-skeleton
3
- description: 提取代码文件或目录的紧凑语法骨架(仅保留类名、函数签名、导出接口与精确 [L起-L止] 行号,剥离具体实现代码)。在探索代码库、排查 Bug 或读取中大型文件前使用此技能快速定位行号,可减少 85%~97% 的探索期 Token 消耗。
3
+ description: 提取代码文件或目录的紧凑语法骨架(仅保留类名、函数签名、导出接口与精确 [L起-L止] 行号,剥离具体实现代码)。支持 C/C++ 大头文件与源码(.c/.h/.cpp/.hpp 的宏、typedef、struct、extern "C" 与条件编译平衡)。在探索代码库、排查 Bug 或读取中大型文件前使用此技能快速定位行号,可减少 85%~97% 的探索期 Token 消耗。
4
4
  ---
5
5
 
6
6
  # 代码骨架极速提取指南 (code-skeleton)
@@ -17,18 +17,18 @@ description: 提取代码文件或目录的紧凑语法骨架(仅保留类名
17
17
  # 1. 扫描源码目录(自动排除 node_modules/.git/dist/target 等,默认深度 2),一步拿到全局函数与行号地图
18
18
  node "$HOME/.gemini/config/plugins/agy-tokless/tools/repo-skeleton/cli.js" <目录路径> --depth 2
19
19
 
20
- # 2. 提取单个大文件的函数/类签名与起止行号
20
+ # 2. 提取单个大文件(含 C/C++ .c/.h/.cpp/.hpp)的函数/类/typedef/宏签名与起止行号
21
21
  node "$HOME/.gemini/config/plugins/agy-tokless/tools/repo-skeleton/cli.js" <文件路径>
22
22
  ```
23
23
 
24
24
  ### Windows (PowerShell)
25
25
 
26
26
  ```powershell
27
- # 1. 扫描源码目录(自动排除 node_modules/.git/dist/target 等,默认深度 2),一步拿到全局函数与行号地图
27
+ # 1. 扫描源码目录(自动排除 node_modules/.git/dist/target/Objects/cmake-build-* 等,默认深度 2;支持 --exclude 指定额外忽略目录)
28
28
  node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\repo-skeleton\cli.js" <目录路径> --depth 2
29
29
 
30
- # 2. 提取单个大文件的函数/类签名与起止行号
30
+ # 2. 提取单个大文件(含 C/C++ .c/.h/.cpp/.hpp)的函数/类/typedef/宏签名与起止行号
31
31
  node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\repo-skeleton\cli.js" <文件路径>
32
32
  ```
33
33
 
34
- 拿到目标函数的 `[L起-L止]` 行号后,直接调用 `read_file(Path, StartLine, EndLine)`(或 Claude Code `Read(file_path, offset, limit)`)按需完整读取对应代码段(无单次行数跨度限制,凡传入显式行号一律放行;若启用 `--with-guard` 护栏,仅对 `>800` 行无行号盲读返回全文骨架辅助导航)。
34
+ 拿到目标函数的 `[L起-L止]` 行号后,直接调用 `read_file(Path, StartLine, EndLine)`(或 Claude Code `Read(file_path, offset, limit)`)按需完整读取对应代码段(针对骨架已定位的目标区间无单次跨度硬限制;但探索陌生中大型文件(`>200` 行)前必须先跑骨架,严禁直接传 `1-800` 等泛大跨度区间批量硬读代替骨架导航;若启用 `--with-guard` 护栏,仅对 `>800` 行无行号盲读返回全文骨架辅助导航)。
@@ -14,11 +14,14 @@ description: 审计与对比 Antigravity 会话的真实 Token 账单(Input /
14
14
  ### macOS / Linux (bash / zsh)
15
15
 
16
16
  ```bash
17
- # 1. 解剖单个会话(支持短 ID 前缀或日志路径),查看缓存断层、最慢步骤 Top 3、MCP 空载继承与 Top 5 烧钱步骤
18
- node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" session <会话ID或前缀>
17
+ # 0. 列出最近会话(兼容 antigravity / antigravity-cli / antigravity-ide,支持 --source cli|app|ide|all)
18
+ node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" list --source cli
19
+
20
+ # 1. 解剖单个会话(支持 latest、latest~1、短 ID 前缀或日志路径),查看缓存断层、模型切换型缓存断层归因、最慢步骤 Top 3、MCP 空载继承与 Top 5 烧钱步骤
21
+ node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" session latest
19
22
 
20
23
  # 2. 优化前后双会话 A/B 对比(对比总 Token、Cache Read 滚雪球、缓存命中率、盲读次数与节省比例)
21
- node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" compare <优化前会话ID> <优化后会话ID>
24
+ node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" compare latest~1 latest
22
25
 
23
26
  # 3. 诊断指定项目的常驻规则/Skill 肥胖度,以及全局/工作区 MCP 与工具底座空载税
24
27
  node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" project <项目目录路径>
@@ -27,11 +30,14 @@ node "$HOME/.gemini/config/plugins/agy-tokless/tools/agy-audit/cli.js" project <
27
30
  ### Windows (PowerShell)
28
31
 
29
32
  ```powershell
30
- # 1. 解剖单个会话(支持短 ID 前缀或日志路径),查看缓存断层、最慢步骤 Top 3、MCP 空载继承与 Top 5 烧钱步骤
31
- node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" session <会话ID或前缀>
33
+ # 0. 列出最近 agy CLI 会话
34
+ node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" list --source cli
35
+
36
+ # 1. 解剖单个会话(支持 latest、latest~1、短 ID 前缀或日志路径),查看缓存断层、模型切换型缓存断层归因、最慢步骤 Top 3、MCP 空载继承与 Top 5 烧钱步骤
37
+ node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" session latest
32
38
 
33
39
  # 2. 优化前后双会话 A/B 对比(对比总 Token、Cache Read 滚雪球、缓存命中率、盲读次数与节省比例)
34
- node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" compare <优化前会话ID> <优化后会话ID>
40
+ node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" compare latest~1 latest
35
41
 
36
42
  # 3. 诊断指定项目的常驻规则/Skill 肥胖度,以及全局/工作区 MCP 与工具底座空载税
37
43
  node "$env:USERPROFILE\.gemini\config\plugins\agy-tokless\tools\agy-audit\cli.js" project <项目目录路径>
@@ -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
  }