@aibyzero/cm-workflow 0.16.7 → 0.16.8
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/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +18 -0
- package/README.md +26 -1
- package/VERSION +1 -1
- package/assets/readme/workflow-recovery-detailed.png +0 -0
- package/assets/readme/workflow-stages-detailed.png +0 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +36 -3
- package/docs/user-guide.md +104 -0
- package/package.json +1 -1
- package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +27 -6
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +82 -8
- package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
- package/runtime/js/cm-ai/drive-core.mjs +17 -4
- package/runtime/js/cm-ai/execution-store.mjs +4 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +37 -13
- package/runtime/js/cm-ai/host-session.mjs +46 -6
- package/runtime/js/cm-ai/host-tool-bridge.mjs +15 -3
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
- package/runtime/js/cm-fix/cause-package.mjs +37 -8
- package/runtime/js/cm-fix/diagnosis.mjs +43 -0
- package/runtime/js/cm-fix/execution.mjs +189 -148
- package/runtime/js/cm-fix/investigation.mjs +25 -9
- package/runtime/js/cm-fix/progress.mjs +3 -1
- package/runtime/js/notify-run.mjs +26 -0
- package/runtime/js/notify.mjs +388 -0
- package/runtime/model-efficiency.md +17 -0
- package/scripts/cm-ai-batch-run.mjs +5 -0
- package/scripts/cm-ai-batch-run.test.mjs +9 -1
- package/scripts/cm-ai-drive.mjs +4 -1
- package/scripts/cm-ai-drive.test.mjs +8 -0
- package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
- package/scripts/cm-ai-host.mjs +2 -2
- package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +77 -4
- package/scripts/cm-fix-abandon.test.mjs +89 -3
- package/scripts/cm-fix-cause-package.test.mjs +33 -0
- package/scripts/cm-fix-drive.mjs +9 -1
- package/scripts/cm-fix-host.mjs +1 -1
- package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
- package/scripts/cm-host-qa-executor.test.mjs +121 -0
- package/scripts/cm-log-event.mjs +31 -5
- package/scripts/cm-notify.test.mjs +468 -0
- package/scripts/cm-patrol.mjs +83 -0
- package/scripts/cm-patrol.test.mjs +161 -0
- package/scripts/cm-token-report.mjs +497 -0
- package/scripts/cm-token-report.test.mjs +346 -0
- package/skills/cm-ai/SKILL.md +7 -3
- package/skills/cm-ai/references/N6-qa-eval.md +2 -2
- package/skills/cm-ai/references/js-host-modes.md +90 -0
- package/skills/cm-ai/references/js-host-qa-recovery.md +110 -0
- package/skills/cm-ai/references/js-host-recovery.md +199 -0
- package/skills/cm-ai/references/js-host.md +67 -329
- package/skills/cm-fix/SKILL.md +2 -0
- package/skills/cm-fix/references/js-host.md +16 -9
- package/skills/cm-prd/SKILL.md +2 -0
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 只读 token 用量报告:把 Claude Code / Codex CLI 会话里的 token 记录,按 CM 运行日志的时间窗口归到 工作流 -> 步骤。
|
|
3
|
+
// 隐私:只读取 时间戳/模型/用量数字/cwd/会话 id/是否子代理 这些元数据字段,不读取、不输出、不保存任何消息正文、工具入参或工具结果。
|
|
4
|
+
// 只读:不写任何文件(除非调用方自己把标准输出重定向)。不估算缺失的数字。
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import {pathToFileURL} from 'node:url';
|
|
9
|
+
|
|
10
|
+
export const UNATTRIBUTED = '未归属(会话闲聊/人工操作)';
|
|
11
|
+
export const STEP_KINDS = ['develop', 'review', 'qa', 'check', 'prd-analysis', 'fix-diagnose', 'other'];
|
|
12
|
+
export const DEFAULT_WEIGHTS = {input: 1, cache_write: 1.25, cache_read: 0.1, output: 5};
|
|
13
|
+
const DEFAULT_GAP_MIN = 30;
|
|
14
|
+
|
|
15
|
+
const MAX_LINE = 64 * 1024 * 1024; // 会话转录/Codex 单行上限;超过的行跳过并计数
|
|
16
|
+
const MAX_LOG_LINE = 1024 * 1024; // CM 运行日志单行上限
|
|
17
|
+
const OVERLONG = Symbol('overlong');
|
|
18
|
+
|
|
19
|
+
// 只接受非负安全整数;其余(字符串、小数、负数、数组、对象)一律视为缺失
|
|
20
|
+
const cnt = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
|
|
21
|
+
const ms = (s) => {
|
|
22
|
+
if (typeof s !== 'string' || s.length > 64) return null;
|
|
23
|
+
const t = Date.parse(s);
|
|
24
|
+
return Number.isFinite(t) ? t : null;
|
|
25
|
+
};
|
|
26
|
+
// 只允许出现在报告里的字符串标量:必须是短字符串且符合标识符样式,否则当作缺失
|
|
27
|
+
const safeStr = (v, re, max) => (typeof v === 'string' && v.length > 0 && v.length <= max && re.test(v) ? v : null);
|
|
28
|
+
const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:\/@-]*$/;
|
|
29
|
+
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
30
|
+
const safeModel = (v) => safeStr(v, MODEL_RE, 100);
|
|
31
|
+
const safeId = (v, max = 128) => safeStr(v, ID_RE, max);
|
|
32
|
+
const safeCwd = (v) => (typeof v === 'string' && v.length > 0 && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v) ? v : null);
|
|
33
|
+
const isObj = (o) => o !== null && typeof o === 'object' && !Array.isArray(o);
|
|
34
|
+
const iso = (t) => new Date(t).toISOString().replace('.000Z', 'Z');
|
|
35
|
+
const encodeDir = (p) => p.replace(/[^A-Za-z0-9]/g, '-');
|
|
36
|
+
const within = (cwd, root) => typeof cwd === 'string' && (cwd === root || cwd.startsWith(root.endsWith('/') ? root : root + '/'));
|
|
37
|
+
const insideReal = (real, rootReal) => real === rootReal || real.startsWith(rootReal.endsWith(path.sep) ? rootReal : rootReal + path.sep);
|
|
38
|
+
|
|
39
|
+
// 解析一行:根必须是对象,否则返回 null(调用方计入坏行)
|
|
40
|
+
function parseObj(line) {
|
|
41
|
+
let o;
|
|
42
|
+
try { o = JSON.parse(line); } catch { return null; }
|
|
43
|
+
return isObj(o) ? o : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 自己切行:单行超过 maxLine 时丢弃该行并产出 OVERLONG,不会把超长行读进内存;结束或提前退出都销毁底层流
|
|
47
|
+
export async function* lines(file, maxLine = MAX_LINE) {
|
|
48
|
+
const stream = fs.createReadStream(file);
|
|
49
|
+
try {
|
|
50
|
+
let parts = [], size = 0, over = false;
|
|
51
|
+
for await (const chunk of stream) {
|
|
52
|
+
let pos = 0;
|
|
53
|
+
while (pos < chunk.length) {
|
|
54
|
+
const nl = chunk.indexOf(10, pos);
|
|
55
|
+
const end = nl === -1 ? chunk.length : nl;
|
|
56
|
+
if (!over) {
|
|
57
|
+
size += end - pos;
|
|
58
|
+
if (size > maxLine) { over = true; parts = []; } else parts.push(chunk.subarray(pos, end));
|
|
59
|
+
}
|
|
60
|
+
if (nl === -1) break;
|
|
61
|
+
if (over) yield OVERLONG;
|
|
62
|
+
else if (size > 0) yield Buffer.concat(parts).toString('utf8');
|
|
63
|
+
parts = []; size = 0; over = false;
|
|
64
|
+
pos = nl + 1;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (over) yield OVERLONG;
|
|
68
|
+
else if (size > 0) yield Buffer.concat(parts).toString('utf8');
|
|
69
|
+
} finally {
|
|
70
|
+
stream.destroy();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 列出 root 下的 .jsonl:不跟随目录符号链接;文件符号链接只有解析后仍在 root 内且是普通文件才用;其余跳过并计数
|
|
75
|
+
function walkJsonl(root) {
|
|
76
|
+
const out = [], skipped = {unsafe_links: 0};
|
|
77
|
+
let rootReal;
|
|
78
|
+
try { rootReal = fs.realpathSync(root); } catch { return {files: out, skipped, rootMissing: true}; }
|
|
79
|
+
const walk = (dir) => {
|
|
80
|
+
let entries;
|
|
81
|
+
try { entries = fs.readdirSync(dir, {withFileTypes: true}); } catch { return; }
|
|
82
|
+
for (const e of entries) {
|
|
83
|
+
const p = path.join(dir, e.name);
|
|
84
|
+
if (e.isSymbolicLink()) {
|
|
85
|
+
if (!e.name.endsWith('.jsonl')) { skipped.unsafe_links++; continue; }
|
|
86
|
+
const f = safeRegularFile(p, rootReal);
|
|
87
|
+
if (f) out.push(f); else skipped.unsafe_links++;
|
|
88
|
+
} else if (e.isDirectory()) walk(p);
|
|
89
|
+
else if (e.isFile() && e.name.endsWith('.jsonl')) out.push(p);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
walk(root);
|
|
93
|
+
return {files: out, skipped, rootMissing: false};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// 解析真实路径并要求落在 rootReal 内、且是普通文件;不满足返回 null
|
|
97
|
+
function safeRegularFile(file, rootReal) {
|
|
98
|
+
try {
|
|
99
|
+
const real = fs.realpathSync(file);
|
|
100
|
+
if (!insideReal(real, rootReal)) return null;
|
|
101
|
+
return fs.statSync(real).isFile() ? real : null;
|
|
102
|
+
} catch { return null; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ---------- CM 运行日志 -> 时间窗口 ----------
|
|
106
|
+
const PRD_KIND = {
|
|
107
|
+
requirements_analysis: 'prd-analysis', design_generation: 'prd-analysis', task_split: 'prd-analysis',
|
|
108
|
+
design_review: 'review', spec_review: 'review', spec_validation: 'check', context_load: 'other',
|
|
109
|
+
};
|
|
110
|
+
const AI_PHASE_KIND = {developing: 'develop', checking: 'check', review_starting: 'review'};
|
|
111
|
+
const AI_NODE_KIND = {N3: 'develop', N4: 'review', N6: 'qa'};
|
|
112
|
+
|
|
113
|
+
function stepKind(row) {
|
|
114
|
+
if (row.workflow === 'cm-prd') return PRD_KIND[row.phase_name] || 'other';
|
|
115
|
+
if (row.workflow === 'cm-fix') return 'fix-diagnose';
|
|
116
|
+
return AI_PHASE_KIND[row.phase_name] || AI_NODE_KIND[row.node] || 'other';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function readSpecsLog(specsDir) {
|
|
120
|
+
const file = path.join(specsDir, '运行日志.jsonl');
|
|
121
|
+
const rows = [];
|
|
122
|
+
const info = {rows, bad: 0, overlong: 0, missing: false, unsafe: false, file};
|
|
123
|
+
let specsReal;
|
|
124
|
+
try { specsReal = fs.realpathSync(specsDir); } catch { info.missing = true; return info; }
|
|
125
|
+
if (!fs.existsSync(file)) { info.missing = true; return info; }
|
|
126
|
+
const real = safeRegularFile(file, specsReal); // 符号链接指到 specs 目录之外、或不是普通文件,都不读
|
|
127
|
+
if (!real) { info.unsafe = true; return info; }
|
|
128
|
+
const specs = path.basename(specsDir);
|
|
129
|
+
for await (const l of lines(real, MAX_LOG_LINE)) {
|
|
130
|
+
if (l === OVERLONG) { info.overlong++; continue; }
|
|
131
|
+
if (!l.trim()) continue;
|
|
132
|
+
const o = parseObj(l);
|
|
133
|
+
const t = o ? ms(o.at) : null;
|
|
134
|
+
const run_id = o ? safeId(o.run_id) : null;
|
|
135
|
+
if (t === null || !run_id) { info.bad++; continue; }
|
|
136
|
+
// 只取白名单标量字段,且都必须符合标识符样式
|
|
137
|
+
rows.push({t, run_id, specs, workflow: safeId(o.workflow, 64) || '未知', event: safeId(o.event, 64) || '', phase: safeId(o.phase, 64) || '',
|
|
138
|
+
node: safeId(o.node, 64) || '', phase_name: safeId(o.phase_name, 64) || '', operation_id: safeId(o.operation_id, 200) || ''});
|
|
139
|
+
}
|
|
140
|
+
rows.sort((a, b) => a.t - b.t);
|
|
141
|
+
return info;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// level 0 = 具体步骤窗口;level 1 = 运行外壳(相邻事件间隔不超过 gap 才连在一起)
|
|
145
|
+
export function buildWindows(rows, {gapMs = DEFAULT_GAP_MIN * 60000} = {}) {
|
|
146
|
+
const windows = [];
|
|
147
|
+
const stats = {unpaired_start: 0, orphan_complete: 0};
|
|
148
|
+
const byRun = new Map();
|
|
149
|
+
for (const r of rows) {
|
|
150
|
+
const k = `${r.specs}|${r.workflow}|${r.run_id}`;
|
|
151
|
+
if (!byRun.has(k)) byRun.set(k, []);
|
|
152
|
+
byRun.get(k).push(r);
|
|
153
|
+
}
|
|
154
|
+
for (const [runKey, evs] of byRun) {
|
|
155
|
+
const workflow = evs[0].workflow;
|
|
156
|
+
const specs = evs[0].specs;
|
|
157
|
+
const open = new Map();
|
|
158
|
+
const mk = (kind, start, end, level, uncertain, label) => windows.push({runKey, workflow, specs, kind, start, end, level, uncertain, label, run_id: evs[0].run_id});
|
|
159
|
+
evs.forEach((r, i) => {
|
|
160
|
+
const isStep = r.event === 'progress' || r.event === 'test_run';
|
|
161
|
+
if (isStep && r.phase === 'start') open.set(`${r.event}|${r.operation_id}`, {r, i});
|
|
162
|
+
else if (isStep && (r.phase === 'complete' || (r.event === 'test_run' && r.phase === 'superseded'))) {
|
|
163
|
+
const key = `${r.event}|${r.operation_id}`;
|
|
164
|
+
const s = open.get(key);
|
|
165
|
+
if (!s) { if (r.phase === 'complete') stats.orphan_complete++; return; }
|
|
166
|
+
open.delete(key);
|
|
167
|
+
const kind = r.event === 'test_run' ? 'qa' : stepKind(s.r);
|
|
168
|
+
mk(kind, s.r.t, Math.max(r.t, s.r.t), 0, false, r.event === 'test_run' ? 'qa' : (s.r.phase_name || s.r.node));
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
// 没配对的 start:窗口只到该 run 下一条事件,标不确定
|
|
172
|
+
for (const {r, i} of open.values()) {
|
|
173
|
+
stats.unpaired_start++;
|
|
174
|
+
const next = evs.slice(i + 1).find((e) => e.t > r.t);
|
|
175
|
+
mk(r.event === 'test_run' ? 'qa' : stepKind(r), r.t, next ? next.t : r.t, 0, true, r.phase_name || r.node);
|
|
176
|
+
}
|
|
177
|
+
// 运行外壳
|
|
178
|
+
let segStart = evs[0].t, prev = evs[0].t;
|
|
179
|
+
const shellKind = workflow === 'cm-fix' ? 'fix-diagnose' : 'other';
|
|
180
|
+
for (let i = 1; i < evs.length; i++) {
|
|
181
|
+
if (evs[i].t - prev > gapMs) { mk(shellKind, segStart, prev, 1, false, 'run'); segStart = evs[i].t; }
|
|
182
|
+
prev = evs[i].t;
|
|
183
|
+
}
|
|
184
|
+
mk(shellKind, segStart, prev, 1, false, 'run');
|
|
185
|
+
}
|
|
186
|
+
return {windows, stats};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function attribute(t, windows) {
|
|
190
|
+
// 返回 {window|null, ambiguous}
|
|
191
|
+
let best = null, level0runs = new Set(), allRuns = new Set();
|
|
192
|
+
for (const w of windows) {
|
|
193
|
+
if (w.start > t) continue;
|
|
194
|
+
if (w.end < t) continue;
|
|
195
|
+
allRuns.add(w.runKey);
|
|
196
|
+
if (w.level === 0) level0runs.add(w.runKey);
|
|
197
|
+
if (!best || w.level < best.level || (w.level === best.level && (w.end - w.start) < (best.end - best.start))) best = w;
|
|
198
|
+
}
|
|
199
|
+
return {window: best, ambiguous: (best && best.level === 0 ? level0runs : allRuns).size > 1};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---------- 用量采集 ----------
|
|
203
|
+
// 用量四项里 input/cache_read/output 缺失或不是非负整数 -> 整条记为 incomplete_usage 并排除;cache_write 缺失 -> 记为未知(null),不补 0
|
|
204
|
+
const usageTotal = (r) => r.input + (r.cache_write ?? 0) + r.cache_read + r.output;
|
|
205
|
+
|
|
206
|
+
export async function collectClaude(projectsDir, project, {sinceMs = null} = {}) {
|
|
207
|
+
const enc = encodeDir(project);
|
|
208
|
+
const stats = {files: 0, lines_with_usage: 0, unique: 0, duplicates_removed: 0, synthetic_skipped: 0, incomplete_usage: 0, cache_write_unknown: 0,
|
|
209
|
+
outside_cwd: 0, no_cwd: 0, no_timestamp: 0, bad_lines: 0, overlong_lines: 0, unsafe_links_skipped: 0, read_errors: 0, dir_missing: false};
|
|
210
|
+
const byId = new Map();
|
|
211
|
+
let dirs = [];
|
|
212
|
+
try { dirs = fs.readdirSync(projectsDir, {withFileTypes: true}).filter((d) => d.isDirectory() && d.name.includes(enc)); } catch { stats.dir_missing = true; }
|
|
213
|
+
for (const d of dirs) {
|
|
214
|
+
const w = walkJsonl(path.join(projectsDir, d.name));
|
|
215
|
+
stats.unsafe_links_skipped += w.skipped.unsafe_links;
|
|
216
|
+
for (const file of w.files) {
|
|
217
|
+
stats.files++;
|
|
218
|
+
let lastCwd = null;
|
|
219
|
+
try {
|
|
220
|
+
for await (const l of lines(file)) {
|
|
221
|
+
if (l === OVERLONG) { stats.overlong_lines++; continue; }
|
|
222
|
+
if (!l.includes('"usage"')) continue;
|
|
223
|
+
const o = parseObj(l);
|
|
224
|
+
if (!o) { stats.bad_lines++; continue; }
|
|
225
|
+
const m = o.message;
|
|
226
|
+
if (o.type !== 'assistant' || !isObj(m) || !isObj(m.usage)) continue;
|
|
227
|
+
stats.lines_with_usage++;
|
|
228
|
+
const u = m.usage;
|
|
229
|
+
if (m.model === '<synthetic>') { stats.synthetic_skipped++; continue; }
|
|
230
|
+
const c = safeCwd(o.cwd);
|
|
231
|
+
const cwd = c ? (lastCwd = c) : lastCwd;
|
|
232
|
+
if (!cwd) { stats.no_cwd++; continue; }
|
|
233
|
+
if (!within(cwd, project)) { stats.outside_cwd++; continue; }
|
|
234
|
+
const t = ms(o.timestamp);
|
|
235
|
+
const input = cnt(u.input_tokens), cw = cnt(u.cache_creation_input_tokens), cr = cnt(u.cache_read_input_tokens), out = cnt(u.output_tokens);
|
|
236
|
+
if (input === null || cr === null || out === null) { stats.incomplete_usage++; continue; }
|
|
237
|
+
const rec = {src: 'claude', t, model: safeModel(m.model) || '未知', cwd, session: safeId(o.sessionId), side: o.isSidechain === true, input, cache_write: cw, cache_read: cr, output: out};
|
|
238
|
+
const id = safeId(m.id, 200) || safeId(o.requestId, 200) || safeId(o.uuid, 200);
|
|
239
|
+
if (!id) { byId.set(Symbol('noid'), rec); continue; }
|
|
240
|
+
const old = byId.get(id);
|
|
241
|
+
if (!old) byId.set(id, rec);
|
|
242
|
+
else {
|
|
243
|
+
stats.duplicates_removed++;
|
|
244
|
+
// 保留更大的用量;相同则保留更早的时间戳
|
|
245
|
+
if (usageTotal(rec) > usageTotal(old) || (usageTotal(rec) === usageTotal(old) && rec.t !== null && (old.t === null || rec.t < old.t))) byId.set(id, rec);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
} catch { stats.read_errors++; }
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const recs = [...byId.values()];
|
|
252
|
+
for (const r of recs) { if (r.t === null) stats.no_timestamp++; if (r.cache_write === null) stats.cache_write_unknown++; }
|
|
253
|
+
stats.unique = recs.length;
|
|
254
|
+
return {records: recs.filter((r) => sinceMs === null || r.t === null || r.t >= sinceMs), stats};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export async function collectCodex(sessionsDir, project, {sinceMs = null} = {}) {
|
|
258
|
+
const stats = {files: 0, files_scanned: 0, sessions_matched: 0, token_events: 0, duplicates_removed: 0, null_info: 0, incomplete_usage: 0, cache_write_unknown: 0,
|
|
259
|
+
no_timestamp: 0, bad_lines: 0, overlong_lines: 0, unsafe_links_skipped: 0, read_errors: 0, dir_missing: false, matched_without_token_events: 0};
|
|
260
|
+
const records = [];
|
|
261
|
+
const w = walkJsonl(sessionsDir);
|
|
262
|
+
if (w.rootMissing) { stats.dir_missing = true; return {records, stats}; }
|
|
263
|
+
stats.unsafe_links_skipped = w.skipped.unsafe_links;
|
|
264
|
+
stats.files = w.files.length;
|
|
265
|
+
for (const file of w.files) {
|
|
266
|
+
// --since 只按事件时间戳过滤:文件修改时间不能保证晚于其中的事件。
|
|
267
|
+
stats.files_scanned++;
|
|
268
|
+
let first = true, cwd = null, model = '未知', sessionId = null, matched = false, maxTotal = -1, events = 0;
|
|
269
|
+
try {
|
|
270
|
+
for await (const l of lines(file)) {
|
|
271
|
+
if (l === OVERLONG) { if (first) break; stats.overlong_lines++; continue; }
|
|
272
|
+
if (first) {
|
|
273
|
+
first = false;
|
|
274
|
+
const o = parseObj(l);
|
|
275
|
+
const p = o && isObj(o.payload) ? o.payload : null;
|
|
276
|
+
const metaCwd = p ? safeCwd(p.cwd) : null;
|
|
277
|
+
if (!p) { stats.bad_lines++; break; }
|
|
278
|
+
sessionId = safeId(p.id) || safeId(p.session_id);
|
|
279
|
+
if (!within(metaCwd, project)) break;
|
|
280
|
+
cwd = metaCwd; matched = true; stats.sessions_matched++;
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (l.includes('"turn_context"')) {
|
|
284
|
+
const o = parseObj(l);
|
|
285
|
+
if (!o) { stats.bad_lines++; continue; }
|
|
286
|
+
if (o.type === 'turn_context' && isObj(o.payload)) {
|
|
287
|
+
model = safeModel(o.payload.model) || model;
|
|
288
|
+
cwd = safeCwd(o.payload.cwd) || cwd;
|
|
289
|
+
}
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (!l.includes('"token_count"')) continue;
|
|
293
|
+
const o = parseObj(l);
|
|
294
|
+
if (!o) { stats.bad_lines++; continue; }
|
|
295
|
+
const p = o.payload;
|
|
296
|
+
if (o.type !== 'event_msg' || !isObj(p) || p.type !== 'token_count') continue;
|
|
297
|
+
stats.token_events++; events++;
|
|
298
|
+
const info = p.info;
|
|
299
|
+
if (!isObj(info) || !isObj(info.last_token_usage) || !isObj(info.total_token_usage)) { stats.null_info++; continue; }
|
|
300
|
+
const tot = cnt(info.total_token_usage.total_tokens);
|
|
301
|
+
if (tot !== null) {
|
|
302
|
+
if (tot <= maxTotal) { stats.duplicates_removed++; continue; }
|
|
303
|
+
maxTotal = tot;
|
|
304
|
+
}
|
|
305
|
+
const u = info.last_token_usage;
|
|
306
|
+
const inp = cnt(u.input_tokens), cached = cnt(u.cached_input_tokens), out = cnt(u.output_tokens), cw = cnt(u.cache_write_input_tokens);
|
|
307
|
+
// 缺少缓存命中字段就无法把输入拆成「未缓存/缓存读」,不能当 0:整条排除并计数
|
|
308
|
+
if (inp === null || cached === null || out === null || cached > inp) { stats.incomplete_usage++; continue; }
|
|
309
|
+
if (!within(cwd, project)) continue;
|
|
310
|
+
const t = ms(o.timestamp);
|
|
311
|
+
if (t === null) stats.no_timestamp++;
|
|
312
|
+
if (cw === null) stats.cache_write_unknown++;
|
|
313
|
+
// Codex 的 input_tokens 含缓存命中部分,这里拆成 未缓存输入 + 缓存读;output 已含推理 token,不再另加
|
|
314
|
+
records.push({src: 'codex', t, model, cwd, session: sessionId, side: false, input: inp - cached, cache_write: cw, cache_read: cached, output: out});
|
|
315
|
+
}
|
|
316
|
+
} catch { stats.read_errors++; }
|
|
317
|
+
if (matched && events === 0) stats.matched_without_token_events++;
|
|
318
|
+
}
|
|
319
|
+
return {records: records.filter((r) => sinceMs === null || r.t === null || r.t >= sinceMs), stats};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ---------- 汇总 ----------
|
|
323
|
+
const blank = () => ({calls: 0, input: 0, cache_write: 0, cache_read: 0, output: 0});
|
|
324
|
+
const addTo = (a, r) => { a.calls++; a.input += r.input; a.cache_write += r.cache_write ?? 0; a.cache_read += r.cache_read; a.output += r.output; };
|
|
325
|
+
export const weighted = (a, w) => a.input * w.input + a.cache_write * w.cache_write + a.cache_read * w.cache_read + a.output * w.output;
|
|
326
|
+
const cwdClass = (cwd, project) => (cwd === project ? '项目根目录' : /[\/\\]\.work[\/\\]/.test(cwd) ? '.work 工作树(CM 派出的会话)' : '项目子目录');
|
|
327
|
+
|
|
328
|
+
export function summarize({records, windows, project, weights = DEFAULT_WEIGHTS, topN = 10}) {
|
|
329
|
+
const tree = new Map(); // workflow -> kind -> sums
|
|
330
|
+
// 无原型字典:目录名或模型名是 constructor 之类时不会命中继承属性。
|
|
331
|
+
const dict = () => Object.create(null);
|
|
332
|
+
const total = blank(), bySrc = dict(), byModel = dict(), byCwd = dict(), byDir = dict(), bySession = dict();
|
|
333
|
+
const top = [];
|
|
334
|
+
const flags = {ambiguous_calls: 0, no_timestamp_calls: 0, uncertain_window_calls: 0, cache_write_unknown_calls: 0};
|
|
335
|
+
const sorted = windows.slice().sort((a, b) => a.start - b.start);
|
|
336
|
+
for (const r of records) {
|
|
337
|
+
let wf = UNATTRIBUTED, kind = '-', win = null;
|
|
338
|
+
if (r.t === null) flags.no_timestamp_calls++;
|
|
339
|
+
else {
|
|
340
|
+
const a = attribute(r.t, sorted);
|
|
341
|
+
if (a.window) { win = a.window; wf = win.workflow; kind = win.kind; if (a.ambiguous) flags.ambiguous_calls++; if (win.uncertain) flags.uncertain_window_calls++; }
|
|
342
|
+
}
|
|
343
|
+
if (r.cache_write === null) flags.cache_write_unknown_calls++;
|
|
344
|
+
const cell = ((tree.get(wf) || tree.set(wf, new Map()).get(wf)).get(kind) || (tree.get(wf).set(kind, blank()), tree.get(wf).get(kind)));
|
|
345
|
+
addTo(cell, r); addTo(total, r);
|
|
346
|
+
addTo(bySrc[r.src] || (bySrc[r.src] = blank()), r);
|
|
347
|
+
addTo(byModel[r.model] || (byModel[r.model] = blank()), r);
|
|
348
|
+
addTo(byCwd[cwdClass(r.cwd, project)] || (byCwd[cwdClass(r.cwd, project)] = blank()), r);
|
|
349
|
+
const rel = r.cwd === project ? '.' : r.cwd.slice(project.length + 1);
|
|
350
|
+
addTo(byDir[rel] || (byDir[rel] = blank()), r);
|
|
351
|
+
// 按完整会话 ID 分组,只在展示时截断。
|
|
352
|
+
const sk = `${r.src}:${r.session ? String(r.session) : '未知'}`;
|
|
353
|
+
addTo(bySession[sk] || (bySession[sk] = {...blank(), dir: rel, unattributed: 0}), r);
|
|
354
|
+
if (wf === UNATTRIBUTED) bySession[sk].unattributed++;
|
|
355
|
+
const w = r.input * weights.input + (r.cache_write ?? 0) * weights.cache_write + r.cache_read * weights.cache_read + r.output * weights.output;
|
|
356
|
+
top.push({t: r.t, src: r.src, model: r.model, workflow: wf, step: kind, run_id: win ? win.run_id : null, input: r.input, cache_write: r.cache_write ?? 0, cache_write_unknown: r.cache_write === null, cache_read: r.cache_read, output: r.output, weighted: w, side: r.side});
|
|
357
|
+
if (top.length > topN * 4) { top.sort((x, y) => y.weighted - x.weighted); top.length = topN; }
|
|
358
|
+
}
|
|
359
|
+
top.sort((x, y) => y.weighted - x.weighted);
|
|
360
|
+
const rows = [];
|
|
361
|
+
for (const [wf, kinds] of tree) {
|
|
362
|
+
const sum = blank();
|
|
363
|
+
for (const c of kinds.values()) { sum.calls += c.calls; sum.input += c.input; sum.cache_write += c.cache_write; sum.cache_read += c.cache_read; sum.output += c.output; }
|
|
364
|
+
rows.push({workflow: wf, ...sum, weighted: weighted(sum, weights), steps: [...kinds.entries()]
|
|
365
|
+
.sort((a, b) => (STEP_KINDS.indexOf(a[0]) + 100 * (a[0] === '-')) - (STEP_KINDS.indexOf(b[0]) + 100 * (b[0] === '-')))
|
|
366
|
+
.map(([kind, c]) => ({kind, ...c, weighted: weighted(c, weights)}))});
|
|
367
|
+
}
|
|
368
|
+
rows.sort((a, b) => (a.workflow === UNATTRIBUTED) - (b.workflow === UNATTRIBUTED) || b.weighted - a.weighted);
|
|
369
|
+
const wrap = (o) => Object.fromEntries(Object.entries(o).map(([k, c]) => [k, {...c, weighted: weighted(c, weights)}]));
|
|
370
|
+
return {total: {...total, weighted: weighted(total, weights)}, by_workflow: rows, by_source: wrap(bySrc), by_model: wrap(byModel), by_cwd_class: wrap(byCwd),
|
|
371
|
+
by_dir_top: Object.entries(wrap(byDir)).sort((a, b) => b[1].weighted - a[1].weighted).slice(0, 15).map(([dir, c]) => ({dir, ...c})),
|
|
372
|
+
by_session_top: Object.entries(wrap(bySession)).sort((a, b) => b[1].weighted - a[1].weighted).slice(0, 10).map(([session, c]) => ({session, ...c})), top_calls: top.slice(0, topN), flags};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export async function buildReport({project, specsDirs = [], sinceIso = null, claudeProjects, codexSessions, weights = DEFAULT_WEIGHTS, gapMin = DEFAULT_GAP_MIN}) {
|
|
376
|
+
const sinceMs = sinceIso ? ms(sinceIso) : null;
|
|
377
|
+
if (sinceIso && sinceMs === null) throw new Error(`--since 不是有效的 ISO 时间: ${sinceIso}`);
|
|
378
|
+
let rows = [], logInfo = [];
|
|
379
|
+
for (const d of specsDirs) {
|
|
380
|
+
const lg = await readSpecsLog(d);
|
|
381
|
+
logInfo.push({specs: d, rows: lg.rows.length, bad_rows: lg.bad, overlong_lines: lg.overlong, missing: lg.missing, unsafe: lg.unsafe});
|
|
382
|
+
rows = rows.concat(lg.rows);
|
|
383
|
+
}
|
|
384
|
+
const {windows: allWindows, stats: winStats} = buildWindows(rows, {gapMs: gapMin * 60000});
|
|
385
|
+
const windows = sinceMs === null ? allWindows : allWindows.filter((w) => w.end >= sinceMs);
|
|
386
|
+
const claude = await collectClaude(claudeProjects, project, {sinceMs});
|
|
387
|
+
const codex = await collectCodex(codexSessions, project, {sinceMs});
|
|
388
|
+
const records = claude.records.concat(codex.records);
|
|
389
|
+
let tMin = null, tMax = null;
|
|
390
|
+
for (const r of records) if (r.t !== null) { if (tMin === null || r.t < tMin) tMin = r.t; if (tMax === null || r.t > tMax) tMax = r.t; }
|
|
391
|
+
const s = summarize({records, windows, project, weights});
|
|
392
|
+
return {
|
|
393
|
+
project, since: sinceIso, weights, gap_min: gapMin,
|
|
394
|
+
span: tMin !== null ? {from: iso(tMin), to: iso(tMax)} : null,
|
|
395
|
+
cm_logs: logInfo, windows: {count: windows.length, step_level: windows.filter((w) => w.level === 0).length, ...winStats},
|
|
396
|
+
claude_stats: claude.stats, codex_stats: codex.stats, ...s,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---------- 输出 ----------
|
|
401
|
+
const fmt = (n) => Math.round(n).toLocaleString('en-US');
|
|
402
|
+
const pct = (a, b) => (b ? (100 * a / b).toFixed(1) + '%' : '-');
|
|
403
|
+
const tableRow = (cols) => '| ' + cols.map((c) => String(c).replace(/\|/g, '\\|')).join(' | ') + ' |';
|
|
404
|
+
|
|
405
|
+
export function renderMarkdown(rep) {
|
|
406
|
+
const L = [];
|
|
407
|
+
const w = rep.weights;
|
|
408
|
+
const hdr = ['调用次数', '输入(未缓存)', '缓存写入', '缓存读取', '输出', '加权合计', '平均上下文/次'];
|
|
409
|
+
const cells = (c) => [fmt(c.calls), fmt(c.input), fmt(c.cache_write), fmt(c.cache_read), fmt(c.output), fmt(c.weighted), fmt((c.input + c.cache_write + c.cache_read) / (c.calls || 1))];
|
|
410
|
+
L.push('# CM token 用量报告(只读)', '');
|
|
411
|
+
L.push(`- 项目:${rep.project}`);
|
|
412
|
+
L.push(`- 用量时间范围:${rep.span ? rep.span.from + ' ~ ' + rep.span.to : '无记录'}${rep.since ? `(--since ${rep.since})` : ''}`);
|
|
413
|
+
L.push(`- 总调用 ${fmt(rep.total.calls)} 次;输入(未缓存) ${fmt(rep.total.input)},缓存写入 ${fmt(rep.total.cache_write)},缓存读取 ${fmt(rep.total.cache_read)},输出 ${fmt(rep.total.output)}`);
|
|
414
|
+
L.push(`- 占比(按原始 token 数):缓存读取 ${pct(rep.total.cache_read, rep.total.input + rep.total.cache_write + rep.total.cache_read + rep.total.output)},缓存写入 ${pct(rep.total.cache_write, rep.total.input + rep.total.cache_write + rep.total.cache_read + rep.total.output)},未缓存输入 ${pct(rep.total.input, rep.total.input + rep.total.cache_write + rep.total.cache_read + rep.total.output)},输出 ${pct(rep.total.output, rep.total.input + rep.total.cache_write + rep.total.cache_read + rep.total.output)}`);
|
|
415
|
+
L.push(`- 加权合计的权重(相对未缓存输入 1 的假定比例,不是价格):输入 ${w.input},缓存写入 ${w.cache_write},缓存读取 ${w.cache_read},输出 ${w.output}。缓存写入不区分 5 分钟/1 小时档位,Codex 与 Claude 用同一组权重,模型之间的单价差异未折算。`);
|
|
416
|
+
L.push('', '## 按工作流 -> 步骤', '');
|
|
417
|
+
L.push(tableRow(['工作流 / 步骤', ...hdr]), tableRow(['---', ...hdr.map(() => '---:')]));
|
|
418
|
+
for (const wf of rep.by_workflow) {
|
|
419
|
+
L.push(tableRow([`**${wf.workflow}**`, ...cells(wf)]));
|
|
420
|
+
if (wf.workflow === UNATTRIBUTED) continue;
|
|
421
|
+
for (const st of wf.steps) L.push(tableRow([` ${st.kind}`, ...cells(st)]));
|
|
422
|
+
}
|
|
423
|
+
L.push(tableRow(['**合计**', ...cells(rep.total)]));
|
|
424
|
+
L.push('', '步骤归类:cm-ai 的 N3 developing=develop、N3 checking=check、N4=review、N6 测试=qa;cm-prd 的 需求/设计/拆任务=prd-analysis、设计/规格审查=review、规格校验=check、context_load=other;cm-fix 整段=fix-diagnose;步骤窗口之外但在同一运行的相邻事件之间(间隔不超过 ' + rep.gap_min + ' 分钟)=other。');
|
|
425
|
+
const section = (title, obj) => {
|
|
426
|
+
L.push('', `## ${title}`, '', tableRow(['类别', ...hdr]), tableRow(['---', ...hdr.map(() => '---:')]));
|
|
427
|
+
for (const [k, c] of Object.entries(obj).sort((a, b) => b[1].weighted - a[1].weighted)) L.push(tableRow([k, ...cells(c)]));
|
|
428
|
+
};
|
|
429
|
+
section('按来源', rep.by_source);
|
|
430
|
+
section('按模型', rep.by_model);
|
|
431
|
+
section('按会话工作目录类型', rep.by_cwd_class);
|
|
432
|
+
L.push('', '## 按会话工作目录(相对项目,前 15)', '', tableRow(['目录', ...hdr]), tableRow(['---', ...hdr.map(() => '---:')]));
|
|
433
|
+
for (const d of rep.by_dir_top) L.push(tableRow([d.dir, ...cells(d)]));
|
|
434
|
+
L.push('', '## 最重的 10 个会话(来源:会话 id 前 8 位)', '', tableRow(['会话', '首个工作目录(会话中途可能换目录)', '其中未归属调用', ...hdr]), tableRow(['---', '---', '---:', ...hdr.map(() => '---:')]));
|
|
435
|
+
// 展示时才截断会话 ID:来源前缀 + ID 前 8 位。
|
|
436
|
+
const shortSession = (k) => { const i = k.indexOf(':'); return i < 0 ? k.slice(0, 16) : `${k.slice(0, i)}:${k.slice(i + 1, i + 9)}`; };
|
|
437
|
+
for (const d of rep.by_session_top) L.push(tableRow([shortSession(d.session), d.dir, fmt(d.unattributed), ...cells(d)]));
|
|
438
|
+
L.push('', '## 单次最重的 10 次调用(按加权合计)', '');
|
|
439
|
+
L.push(tableRow(['时间(UTC)', '来源', '模型', '工作流/步骤', '子代理', '输入', '缓存写入', '缓存读取', '输出', '加权']), tableRow(['---', '---', '---', '---', '---', '---:', '---:', '---:', '---:', '---:']));
|
|
440
|
+
for (const c of rep.top_calls) L.push(tableRow([c.t === null ? '时间缺失' : iso(c.t), c.src, c.model, c.step === '-' ? c.workflow : `${c.workflow}/${c.step}`, c.side ? '是' : '否', fmt(c.input), fmt(c.cache_write), fmt(c.cache_read), fmt(c.output), fmt(c.weighted)]));
|
|
441
|
+
L.push('', '## 数据质量与不确定项', '');
|
|
442
|
+
const cs = rep.claude_stats, xs = rep.codex_stats;
|
|
443
|
+
L.push(`- Claude 转录:扫描 ${cs.files} 个文件;含用量的行 ${fmt(cs.lines_with_usage)},按 message.id 去重后 ${fmt(cs.unique)} 条,去掉重复 ${fmt(cs.duplicates_removed)} 行;跳过合成消息 ${cs.synthetic_skipped}、cwd 不在项目内 ${cs.outside_cwd}、cwd 缺失 ${cs.no_cwd}、用量字段缺失或不合法 ${cs.incomplete_usage}(整条排除,不估算)、时间缺失 ${cs.no_timestamp}${cs.dir_missing ? ';转录目录不存在' : ''}。`);
|
|
444
|
+
L.push(`- Claude 转录读取问题:无法解析的行 ${cs.bad_lines}、超长被跳过的行 ${cs.overlong_lines}、指向根目录之外或非普通文件而被跳过的符号链接 ${cs.unsafe_links_skipped}、读文件出错 ${cs.read_errors};缓存写入字段缺失 ${cs.cache_write_unknown} 条(未知,未计入缓存写入,不是 0)。`);
|
|
445
|
+
L.push(`- Codex 会话:共 ${xs.files} 个文件,实际扫描 ${xs.files_scanned} 个,首行 cwd 匹配项目的 ${xs.sessions_matched} 个;用量事件 ${fmt(xs.token_events)} 个,按累计值去重 ${fmt(xs.duplicates_removed)},info 为空 ${xs.null_info},缓存命中等字段缺失或不合法 ${xs.incomplete_usage}(整条排除,不当 0),匹配但没有任何用量事件的会话 ${xs.matched_without_token_events}${xs.dir_missing ? ';Codex 会话目录不存在' : ''}。只按会话首行 cwd 判断是否属于本项目,先在别处启动、后来才切进项目的会话会漏掉。`);
|
|
446
|
+
L.push(`- Codex 读取问题:无法解析的行 ${xs.bad_lines}、超长被跳过的行 ${xs.overlong_lines}、被跳过的不安全符号链接 ${xs.unsafe_links_skipped}、读文件出错 ${xs.read_errors};缓存写入字段缺失 ${xs.cache_write_unknown} 条(未知,未计入)。`);
|
|
447
|
+
for (const l of rep.cm_logs) L.push(`- CM 运行日志 ${l.specs}:${l.unsafe ? '符号链接指到 specs 目录之外或不是普通文件,未读取' : l.missing ? '文件不存在' : `${l.rows} 行可用,${l.bad_rows} 行无法解析/不是对象/缺时间被忽略,${l.overlong_lines} 行超长被跳过`}。`);
|
|
448
|
+
L.push(`- 时间窗口 ${rep.windows.count} 个(步骤级 ${rep.windows.step_level});没有结束事件的开始 ${rep.windows.unpaired_start}(窗口只延伸到下一条事件,标为不确定);没有开始的结束 ${rep.windows.orphan_complete}(忽略)。`);
|
|
449
|
+
L.push(`- 归属方式是按时间窗口,不是按会话:同一时间多个运行并行、或人在别的会话里干活,都会被算进窗口。落在多个不同运行的窗口里的调用 ${fmt(rep.flags.ambiguous_calls)} 次(已按最内层步骤归属,视为不确定);落在不确定窗口里的 ${fmt(rep.flags.uncertain_window_calls)} 次;时间缺失无法归属 ${fmt(rep.flags.no_timestamp_calls)} 次。`);
|
|
450
|
+
return L.join('\n') + '\n';
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ---------- CLI ----------
|
|
454
|
+
export function parseArgs(argv) {
|
|
455
|
+
const a = {specs: [], json: false, since: null, project: null, claudeProjects: path.join(os.homedir(), '.claude', 'projects'),
|
|
456
|
+
codexSessions: path.join(os.homedir(), '.codex', 'sessions'), weights: {...DEFAULT_WEIGHTS}, gapMin: DEFAULT_GAP_MIN, help: false};
|
|
457
|
+
const need = (i, name) => { if (i + 1 >= argv.length) throw new Error(`${name} 缺少参数值`); return argv[i + 1]; };
|
|
458
|
+
for (let i = 0; i < argv.length; i++) {
|
|
459
|
+
const k = argv[i];
|
|
460
|
+
if (k === '--project') a.project = need(i++, k);
|
|
461
|
+
else if (k === '--specs') a.specs.push(...need(i++, k).split(',').filter(Boolean));
|
|
462
|
+
else if (k === '--since') a.since = need(i++, k);
|
|
463
|
+
else if (k === '--json') a.json = true;
|
|
464
|
+
else if (k === '--claude-projects') a.claudeProjects = need(i++, k);
|
|
465
|
+
else if (k === '--codex-sessions') a.codexSessions = need(i++, k);
|
|
466
|
+
else if (k === '--gap-min') { a.gapMin = Number(need(i++, k)); if (!(a.gapMin > 0)) throw new Error('--gap-min 必须是正数'); }
|
|
467
|
+
else if (k === '--weights') {
|
|
468
|
+
for (const part of need(i++, k).split(',')) {
|
|
469
|
+
const [name, val] = part.split('=');
|
|
470
|
+
const map = {in: 'input', cw: 'cache_write', cr: 'cache_read', out: 'output'};
|
|
471
|
+
if (!map[name] || !(Number(val) >= 0) || val === '') throw new Error(`--weights 格式应为 in=1,cw=1.25,cr=0.1,out=5,收到 ${part}`);
|
|
472
|
+
a.weights[map[name]] = Number(val);
|
|
473
|
+
}
|
|
474
|
+
} else if (k === '--help' || k === '-h') a.help = true;
|
|
475
|
+
else throw new Error(`未知参数 ${k}`);
|
|
476
|
+
}
|
|
477
|
+
return a;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const USAGE = '用法: node scripts/cm-token-report.mjs --project <项目根目录> --specs <specs 目录>[,<更多 specs 目录>] [--since ISO] [--json] [--weights in=1,cw=1.25,cr=0.1,out=5] [--gap-min 30]\n 只读;--claude-projects / --codex-sessions 可改用量目录(默认 ~/.claude/projects 与 ~/.codex/sessions)。';
|
|
481
|
+
|
|
482
|
+
export async function main(argv, io = {stdout: process.stdout, stderr: process.stderr}) {
|
|
483
|
+
let a;
|
|
484
|
+
try { a = parseArgs(argv); } catch (e) { io.stderr.write(`错误: ${e.message}\n${USAGE}\n`); return 2; }
|
|
485
|
+
if (a.help) { io.stdout.write(USAGE + '\n'); return 0; }
|
|
486
|
+
if (!a.project || !a.specs.length) { io.stderr.write(`错误: 需要 --project 和 --specs\n${USAGE}\n`); return 2; }
|
|
487
|
+
try {
|
|
488
|
+
const rep = await buildReport({project: path.resolve(a.project), specsDirs: a.specs.map((s) => path.resolve(s)), sinceIso: a.since,
|
|
489
|
+
claudeProjects: a.claudeProjects, codexSessions: a.codexSessions, weights: a.weights, gapMin: a.gapMin});
|
|
490
|
+
io.stdout.write(a.json ? JSON.stringify(rep, null, 2) + '\n' : renderMarkdown(rep));
|
|
491
|
+
return 0;
|
|
492
|
+
} catch (e) { io.stderr.write(`错误: ${e.message}\n`); return 1; }
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
496
|
+
main(process.argv.slice(2)).then((c) => { process.exitCode = c; });
|
|
497
|
+
}
|