@yeison.restrepo.r/code-conductor 1.41.0 → 1.43.0

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.
@@ -0,0 +1,387 @@
1
+ // scripts/session-metrics.mjs
2
+ // FEAT-046: offline token and time metrics over Claude Code's local session logs.
3
+ // Zero-dep, strictly read-only: it opens files for reading only and prints one report.
4
+ // Every failure degrades to a named note on stdout and exit 0, never a wrong number.
5
+ import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
6
+ import { createInterface } from 'node:readline';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { homedir } from 'node:os';
9
+ import { basename, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ export const THRESHOLDS = { repeatReads: 5, unboundedReadTokens: 2000, contextPeak: 150000, cacheHitPct: 80 };
13
+ const TOP = 5;
14
+ const NONE = '(none)';
15
+ // Every map keyed by log text has no prototype, so a key like __proto__ is an ordinary row.
16
+ const table = (entries = {}) => Object.assign(Object.create(null), entries);
17
+ const PHASES = table({
18
+ 'cc-spec': 'Define', 'cc-plan': 'Define',
19
+ 'cc-implement': 'Build', 'cc-refactor': 'Build', 'cc-debug': 'Build',
20
+ 'cc-review': 'Verify', 'cc-test': 'Verify',
21
+ });
22
+ const COMMAND_TAG = /<command-name>\/?([^<\s]+)<\/command-name>/;
23
+ const ITEM_IN_BRANCH = /(feat|bug|arch)[-_]?(\d{3})/i;
24
+
25
+ // Claude Code names a project's log directory after its path, with every non-alphanumeric as '-'.
26
+ export function slugOf(path) {
27
+ return path.replace(/[^A-Za-z0-9]/g, '-');
28
+ }
29
+
30
+ export function resolveLogDir({ dir, env, root, home }) {
31
+ if (dir) return dir;
32
+ const base = env.CLAUDE_CONFIG_DIR || join(home, '.claude');
33
+ return join(base, 'projects', slugOf(root));
34
+ }
35
+
36
+ export function listLogFiles(dir) {
37
+ const files = [];
38
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
39
+ if (entry.isFile() && entry.name.endsWith('.jsonl')) files.push(join(dir, entry.name));
40
+ if (!entry.isDirectory()) continue;
41
+ const sub = join(dir, entry.name, 'subagents');
42
+ if (!existsSync(sub)) continue;
43
+ for (const name of readdirSync(sub)) if (name.endsWith('.jsonl')) files.push(join(sub, name));
44
+ }
45
+ return files.sort();
46
+ }
47
+
48
+ // A session still being written ends mid-line; that line is skipped, never guessed at.
49
+ export function parseLine(line) {
50
+ if (!line.trim()) return null;
51
+ try {
52
+ const record = JSON.parse(line);
53
+ return record && typeof record === 'object' && !Array.isArray(record) ? record : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ export function createTotals() {
60
+ return {
61
+ files: 0, subagentFiles: 0, bytes: 0, requests: 0, unparsable: 0, notMeasured: 0, compactions: 0,
62
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
63
+ groups: { tool: table(), command: table(), phase: table(), branch: table(), session: table() },
64
+ seen: new Set(), pending: new Map(), command: NONE,
65
+ reads: table(), unboundedReads: [], peaks: table(), sessionCompactions: table(), activeMs: table(),
66
+ };
67
+ }
68
+
69
+ function bump(group, key, field, amount) {
70
+ group[key] ??= { tokens: 0, calls: 0, estTokens: 0, wallMs: 0 };
71
+ group[key][field] += amount;
72
+ }
73
+
74
+ function blocksOf(record) {
75
+ const content = record.message?.content;
76
+ return Array.isArray(content) ? content : [];
77
+ }
78
+
79
+ function textOf(record) {
80
+ const content = record.message?.content;
81
+ if (typeof content === 'string') return content;
82
+ return blocksOf(record).filter((b) => b.type === 'text').map((b) => b.text).join('');
83
+ }
84
+
85
+ function sessionKey(record) {
86
+ const id = String(record.sessionId ?? '?').slice(0, 8);
87
+ return record.agentId ? `${id}/${record.agentId}` : id;
88
+ }
89
+
90
+ // Image and document blocks are not text the model reads as tokens at chars/4; they are skipped.
91
+ export function estimateTokens(content) {
92
+ if (typeof content === 'string') return Math.round(content.length / 4);
93
+ if (!Array.isArray(content)) return 0;
94
+ const chars = content.filter((b) => b.type === 'text').reduce((sum, b) => sum + (typeof b.text === 'string' ? b.text.length : 0), 0);
95
+ return Math.round(chars / 4);
96
+ }
97
+
98
+ export function addRecord(totals, record) {
99
+ if (record.type === 'assistant') return addAssistant(totals, record);
100
+ if (record.type === 'user') return addUser(totals, record);
101
+ if (record.type === 'system') return addSystem(totals, record);
102
+ }
103
+
104
+ function addAssistant(totals, record) {
105
+ for (const block of blocksOf(record)) if (block.type === 'tool_use') openTool(totals, record, block);
106
+ const usage = record.message?.usage;
107
+ if (!usage || !record.requestId) { totals.notMeasured++; return; }
108
+ // One API response spans several records sharing a requestId, each repeating the same usage.
109
+ if (totals.seen.has(record.requestId)) return;
110
+ totals.seen.add(record.requestId);
111
+ addUsage(totals, record, usage);
112
+ }
113
+
114
+ function openTool(totals, record, block) {
115
+ totals.pending.set(block.id, { name: block.name, ts: Date.parse(record.timestamp), input: block.input ?? {} });
116
+ if (block.name === 'Skill' && block.input?.skill) totals.command = String(block.input.skill);
117
+ }
118
+
119
+ function addUsage(totals, record, usage) {
120
+ const n = (k) => Number(usage[k]) || 0;
121
+ const input = n('input_tokens'), output = n('output_tokens');
122
+ const cacheRead = n('cache_read_input_tokens'), cacheWrite = n('cache_creation_input_tokens');
123
+ const all = input + output + cacheRead + cacheWrite;
124
+ const t = totals.tokens;
125
+ t.input += input; t.output += output; t.cacheRead += cacheRead; t.cacheWrite += cacheWrite;
126
+ totals.requests++;
127
+ const session = sessionKey(record);
128
+ totals.peaks[session] = Math.max(totals.peaks[session] ?? 0, input + cacheRead + cacheWrite);
129
+ const g = totals.groups;
130
+ bump(g.command, totals.command, 'tokens', all);
131
+ bump(g.phase, PHASES[totals.command] ?? NONE, 'tokens', all);
132
+ bump(g.branch, record.gitBranch || NONE, 'tokens', all);
133
+ bump(g.session, session, 'tokens', all);
134
+ }
135
+
136
+ function addUser(totals, record) {
137
+ const command = textOf(record).match(COMMAND_TAG);
138
+ if (command) totals.command = command[1];
139
+ else if (record.promptSource === 'typed') totals.command = NONE;
140
+ for (const block of blocksOf(record)) if (block.type === 'tool_result') closeTool(totals, record, block);
141
+ }
142
+
143
+ function closeTool(totals, record, block) {
144
+ const call = totals.pending.get(block.tool_use_id);
145
+ if (!call) return;
146
+ totals.pending.delete(block.tool_use_id);
147
+ const tool = totals.groups.tool;
148
+ const est = estimateTokens(block.content);
149
+ const ms = Date.parse(record.timestamp) - call.ts;
150
+ bump(tool, call.name, 'calls', 1);
151
+ bump(tool, call.name, 'estTokens', est);
152
+ // A result stamped before its call is a clock or log fault, so its time is unknown, not negative.
153
+ if (Number.isFinite(ms) && ms >= 0) bump(tool, call.name, 'wallMs', ms);
154
+ else totals.notMeasured++;
155
+ if (call.name === 'Read') trackRead(totals, call.input, est);
156
+ }
157
+
158
+ function trackRead(totals, input, est) {
159
+ const file = String(input.file_path ?? '?');
160
+ totals.reads[file] ??= { count: 0, estTokens: 0 };
161
+ totals.reads[file].count++;
162
+ totals.reads[file].estTokens += est;
163
+ if (!input.limit && est > THRESHOLDS.unboundedReadTokens) totals.unboundedReads.push({ file, est });
164
+ }
165
+
166
+ function addSystem(totals, record) {
167
+ const session = sessionKey(record);
168
+ if (record.subtype === 'compact_boundary') {
169
+ totals.compactions++;
170
+ totals.sessionCompactions[session] = (totals.sessionCompactions[session] ?? 0) + 1;
171
+ }
172
+ if (record.subtype === 'turn_duration' && Number.isFinite(record.durationMs)) {
173
+ totals.activeMs[session] = (totals.activeMs[session] ?? 0) + record.durationMs;
174
+ }
175
+ }
176
+
177
+ // A tool call cut off by the end of its transcript is still a call; only its time is unknown.
178
+ export function finishFile(totals) {
179
+ for (const call of totals.pending.values()) {
180
+ bump(totals.groups.tool, call.name, 'calls', 1);
181
+ totals.notMeasured++;
182
+ }
183
+ totals.pending.clear();
184
+ totals.command = NONE;
185
+ }
186
+
187
+ export async function readLog(totals, file) {
188
+ totals.files++;
189
+ totals.bytes += statSync(file).size;
190
+ if (file.includes('subagents')) totals.subagentFiles++;
191
+ const lines = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
192
+ for await (const line of lines) {
193
+ const record = parseLine(line);
194
+ if (record) addRecord(totals, record);
195
+ else if (line.trim()) totals.unparsable++;
196
+ }
197
+ finishFile(totals);
198
+ }
199
+
200
+ export function itemOf(branch) {
201
+ const m = String(branch).match(ITEM_IN_BRANCH);
202
+ return m ? `${m[1].toUpperCase()}-${m[2]}` : null;
203
+ }
204
+
205
+ export function pillarMap(backlogText) {
206
+ const map = table();
207
+ let pillar = null;
208
+ for (const line of backlogText.split(/\r?\n/)) {
209
+ const heading = line.match(/^## PILLAR (\d+)/i);
210
+ if (heading) pillar = `P${heading[1]}`;
211
+ const item = line.match(/^### \[.\] `\[([A-Z]+-\d+)\]`/);
212
+ if (item && pillar) map[item[1]] = pillar;
213
+ }
214
+ return map;
215
+ }
216
+
217
+ export function pillarTotals(branchGroup, pillars) {
218
+ const out = table();
219
+ for (const [branch, v] of Object.entries(branchGroup)) {
220
+ const key = pillars[itemOf(branch)] ?? '(unattributed)';
221
+ out[key] = (out[key] ?? 0) + v.tokens;
222
+ }
223
+ return out;
224
+ }
225
+
226
+ export function fmt(n) {
227
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
228
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
229
+ return String(n);
230
+ }
231
+
232
+ export function cacheHitPct(tokens) {
233
+ const input = tokens.input + tokens.cacheRead + tokens.cacheWrite;
234
+ return input ? (100 * tokens.cacheRead) / input : null;
235
+ }
236
+
237
+ function repeatedReadLine(totals) {
238
+ const hot = Object.entries(totals.reads).filter(([, r]) => r.count >= THRESHOLDS.repeatReads);
239
+ if (!hot.length) return null;
240
+ const [file, r] = hot.sort((a, b) => b[1].count - a[1].count)[0];
241
+ const more = hot.length > 1 ? ` (+${hot.length - 1} more files)` : '';
242
+ return `R1 ${basename(file)} Read ${r.count}x (~${fmt(r.estTokens)} est tok)${more}: grep before reading, or keep the fact in memory`;
243
+ }
244
+
245
+ function unboundedReadLine(totals) {
246
+ const reads = totals.unboundedReads;
247
+ if (!reads.length) return null;
248
+ const top = [...reads].sort((a, b) => b.est - a.est)[0];
249
+ return `R2 ${reads.length} Read(s) without limit returned >${fmt(THRESHOLDS.unboundedReadTokens)} est tok (largest ~${fmt(top.est)} in ${basename(top.file)}): pass offset/limit`;
250
+ }
251
+
252
+ function contextPeakLine(totals) {
253
+ const high = Object.entries(totals.peaks).filter(([, p]) => p > THRESHOLDS.contextPeak);
254
+ if (!high.length) return null;
255
+ const [session, peak] = high.sort((a, b) => b[1] - a[1])[0];
256
+ const compactions = totals.sessionCompactions[session] ?? 0;
257
+ const more = high.length > 1 ? ` (+${high.length - 1} more sessions)` : '';
258
+ return `R3 session ${session} peaked at ${fmt(peak)} context with ${compactions} compaction(s)${more}: run /cc-compact earlier`;
259
+ }
260
+
261
+ function cacheMissLine(totals) {
262
+ const pct = cacheHitPct(totals.tokens);
263
+ if (pct === null || pct >= THRESHOLDS.cacheHitPct) return null;
264
+ const t = totals.tokens;
265
+ return `R4 cache hit ${pct.toFixed(1)}% (cacheR ${fmt(t.cacheRead)} of ${fmt(t.input + t.cacheRead + t.cacheWrite)} input tok): keep the prompt prefix stable`;
266
+ }
267
+
268
+ export function recommend(totals) {
269
+ return [repeatedReadLine, unboundedReadLine, contextPeakLine, cacheMissLine]
270
+ .map((rule) => rule(totals))
271
+ .filter(Boolean);
272
+ }
273
+
274
+ function topRows(group, field) {
275
+ return Object.entries(group).sort((a, b) => b[1][field] - a[1][field]).slice(0, TOP);
276
+ }
277
+
278
+ function shareRow(entries, total) {
279
+ return entries.map(([k, v]) => `${k} ${fmt(v)} ${total ? Math.round((100 * v) / total) : 0}%`).join(' | ');
280
+ }
281
+
282
+ function headerLines(totals) {
283
+ const t = totals.tokens;
284
+ const pct = cacheHitPct(t);
285
+ return [
286
+ `cc-metrics: ${totals.files} logs (${totals.subagentFiles} subagent), ${fmt(totals.bytes)}B, ${totals.requests} requests, ` +
287
+ `${totals.unparsable} unparsable lines, ${totals.notMeasured} not measured, ${totals.compactions} compactions`,
288
+ `tokens: in ${fmt(t.input)} out ${fmt(t.output)} cacheR ${fmt(t.cacheRead)} cacheW ${fmt(t.cacheWrite)} | ` +
289
+ `cache hit ${pct === null ? 'n/a' : `${pct.toFixed(1)}%`}`,
290
+ ];
291
+ }
292
+
293
+ function toolLines(totals) {
294
+ const rows = topRows(totals.groups.tool, 'calls').map(([name, v]) =>
295
+ ` ${name.padEnd(12)} ${String(v.calls).padStart(6)} ${fmt(v.estTokens).padStart(8)} ${String(Math.round(v.wallMs / 1000)).padStart(7)}`);
296
+ return ['by tool (calls, est result tok, wall s):', ...rows];
297
+ }
298
+
299
+ function groupLine(label, group, total) {
300
+ const entries = topRows(group, 'tokens').map(([k, v]) => [k, v.tokens]);
301
+ return `by ${label} (tokens): ${shareRow(entries, total)}`;
302
+ }
303
+
304
+ function branchLines(totals, pillars) {
305
+ const rows = topRows(totals.groups.branch, 'tokens').map(([branch, v]) => {
306
+ const item = itemOf(branch);
307
+ const tags = item ? ` ${item} ${pillars?.[item] ?? ''}`.trimEnd() : '';
308
+ return ` ${branch.slice(0, 34).padEnd(34)} ${fmt(v.tokens).padStart(8)}${tags}`;
309
+ });
310
+ return ['by branch (tokens):', ...rows];
311
+ }
312
+
313
+ function sessionLines(totals) {
314
+ const rows = topRows(totals.groups.session, 'tokens').map(([s, v]) => {
315
+ const ms = totals.activeMs[s];
316
+ const active = ms === undefined ? '—' : String(Math.round(ms / 60000));
317
+ return ` ${s.padEnd(20)} ${fmt(v.tokens).padStart(8)} ${active.padStart(6)}`;
318
+ });
319
+ return ['by session (tokens, active min):', ...rows];
320
+ }
321
+
322
+ function pillarLine(totals, pillars, total) {
323
+ if (!pillars) return 'pillar: no AGENT-READABLE BACKLOG.md';
324
+ const entries = Object.entries(pillarTotals(totals.groups.branch, pillars)).sort((a, b) => b[1] - a[1]);
325
+ return `by pillar (tokens): ${shareRow(entries, total)}`;
326
+ }
327
+
328
+ export function formatReport(totals, pillars) {
329
+ const total = Object.values(totals.groups.session).reduce((s, v) => s + v.tokens, 0);
330
+ const recs = recommend(totals);
331
+ const th = THRESHOLDS;
332
+ return [
333
+ ...headerLines(totals),
334
+ ...toolLines(totals),
335
+ groupLine('command', totals.groups.command, total),
336
+ groupLine('phase', totals.groups.phase, total),
337
+ ...branchLines(totals, pillars),
338
+ pillarLine(totals, pillars, total),
339
+ ...sessionLines(totals),
340
+ 'recommendations:',
341
+ ...(recs.length ? recs.map((r) => ` - ${r}`) : [' - none fired']),
342
+ `thresholds: R1>=${th.repeatReads} reads, R2>${fmt(th.unboundedReadTokens)} tok, R3>${fmt(th.contextPeak)} ctx, R4<${th.cacheHitPct}% cache`,
343
+ ].join('\n');
344
+ }
345
+
346
+ function readPillars(root) {
347
+ const file = join(root, 'AGENT-READABLE BACKLOG.md');
348
+ return existsSync(file) ? pillarMap(readFileSync(file, 'utf8')) : null;
349
+ }
350
+
351
+ export async function run({ dir, root, env = process.env, home = homedir() }) {
352
+ const logDir = resolveLogDir({ dir, env, root, home });
353
+ if (!existsSync(logDir)) return `cc-metrics: no session logs at ${logDir}`;
354
+ const files = listLogFiles(logDir);
355
+ if (!files.length) return `cc-metrics: no session logs at ${logDir}`;
356
+ const totals = createTotals();
357
+ for (const file of files) await readLog(totals, file);
358
+ return formatReport(totals, readPillars(root));
359
+ }
360
+
361
+ function projectRoot() {
362
+ try {
363
+ const top = execFileSync('git', ['rev-parse', '--show-toplevel'],
364
+ { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
365
+ if (top) return top;
366
+ } catch { /* not a git checkout: fall back to cwd */ }
367
+ return process.cwd();
368
+ }
369
+
370
+ // The command passes $ARGUMENTS as one quoted word so a path with spaces survives the shell,
371
+ // so everything after --dir is the path, whether it arrives as one argv entry or several.
372
+ export function parseArgs(argv) {
373
+ const m = argv.join(' ').match(/(?:^|\s)--dir\s+(.+)$/);
374
+ if (!m) return { dir: undefined };
375
+ return { dir: m[1].trim().replace(/^(["'])(.*)\1$/, '$2') };
376
+ }
377
+
378
+ async function main() {
379
+ try {
380
+ const { dir } = parseArgs(process.argv.slice(2));
381
+ process.stdout.write(`${await run({ dir, root: projectRoot() })}\n`);
382
+ } catch (e) {
383
+ process.stdout.write(`cc-metrics: failed: ${(e && e.message) || e}\n`);
384
+ }
385
+ }
386
+
387
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main();