@gtheys/pi-flow 0.0.0-stage → 0.2.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.
Files changed (164) hide show
  1. package/README.md +833 -2
  2. package/adhoc/tracker.ts +360 -0
  3. package/aven/client.ts +996 -0
  4. package/aven/status.ts +395 -0
  5. package/brainstorm/args.ts +24 -0
  6. package/brainstorm/artifact.ts +67 -0
  7. package/brainstorm/paths.ts +43 -0
  8. package/brainstorm/prompt.ts +172 -0
  9. package/brainstorm/refs.ts +41 -0
  10. package/config.schema.json +161 -0
  11. package/config.ts +577 -0
  12. package/feedback/args.ts +21 -0
  13. package/feedback/prompt.ts +177 -0
  14. package/feedback/triage.ts +88 -0
  15. package/flow/agent-role.ts +46 -0
  16. package/flow/answer-wake.ts +212 -0
  17. package/flow/answer.ts +183 -0
  18. package/flow/args.ts +48 -0
  19. package/flow/ask-emitter.ts +331 -0
  20. package/flow/attribution.ts +145 -0
  21. package/flow/aven-resolve-exec.ts +95 -0
  22. package/flow/aven-resolve.ts +80 -0
  23. package/flow/awaiting-approval.ts +32 -0
  24. package/flow/binding-heal.ts +68 -0
  25. package/flow/cost-autopush.ts +162 -0
  26. package/flow/cost-command.ts +122 -0
  27. package/flow/cost-rows-journal.ts +296 -0
  28. package/flow/cost-rows-push.ts +112 -0
  29. package/flow/cost-rows-rows.ts +209 -0
  30. package/flow/cost-rows.ts +228 -0
  31. package/flow/cost.ts +173 -0
  32. package/flow/durable-refs.ts +287 -0
  33. package/flow/effect-gate.ts +137 -0
  34. package/flow/ensure-labels.ts +44 -0
  35. package/flow/frame.ts +172 -0
  36. package/flow/gates.ts +211 -0
  37. package/flow/jira-ref.ts +212 -0
  38. package/flow/label-gate.ts +149 -0
  39. package/flow/land-gate.ts +98 -0
  40. package/flow/lifecycle-policy.ts +162 -0
  41. package/flow/live-wait.ts +52 -0
  42. package/flow/liveness.ts +408 -0
  43. package/flow/loop-deps.ts +210 -0
  44. package/flow/loop-settle.ts +531 -0
  45. package/flow/loop.ts +437 -0
  46. package/flow/orchestrate.ts +45 -0
  47. package/flow/phase-command.ts +287 -0
  48. package/flow/phase-emoji.ts +13 -0
  49. package/flow/phase-prompts.ts +251 -0
  50. package/flow/picker.ts +307 -0
  51. package/flow/push.ts +475 -0
  52. package/flow/reconcile-command.ts +253 -0
  53. package/flow/reconcile-deps.ts +329 -0
  54. package/flow/reconcile.ts +738 -0
  55. package/flow/ref-kind.ts +80 -0
  56. package/flow/resume-picker.ts +222 -0
  57. package/flow/resume.ts +116 -0
  58. package/flow/run-health.ts +252 -0
  59. package/flow/run-liveness.ts +33 -0
  60. package/flow/state-metrics.ts +559 -0
  61. package/flow/status.ts +105 -0
  62. package/flow/step-output.ts +416 -0
  63. package/flow/steps.ts +73 -0
  64. package/flow/terminal-purge.ts +281 -0
  65. package/flow/turn-generation.ts +19 -0
  66. package/flow/v2-emission.ts +381 -0
  67. package/flow/v2-resume.ts +100 -0
  68. package/flow/vocabulary.ts +261 -0
  69. package/flow/widget.ts +448 -0
  70. package/flow/worktree-context.ts +136 -0
  71. package/flow-diagram/assemble.ts +27 -0
  72. package/flow-diagram/command.ts +252 -0
  73. package/flow-diagram/translate.ts +862 -0
  74. package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
  75. package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
  76. package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
  77. package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
  78. package/flow-diagram/vendor/harness-profiler/view.html +436 -0
  79. package/gates.ts +20 -0
  80. package/herdr/sync.ts +355 -0
  81. package/herdr/viewer.ts +432 -0
  82. package/implement/args.ts +21 -0
  83. package/implement/prompt.ts +98 -0
  84. package/implement/retry.ts +57 -0
  85. package/implement/routing.ts +31 -0
  86. package/index.ts +3206 -0
  87. package/mode-profile.ts +56 -0
  88. package/package.json +205 -4
  89. package/phase-state.ts +18 -0
  90. package/plan/args.ts +20 -0
  91. package/plan/prompt.ts +251 -0
  92. package/plan/size-check.ts +46 -0
  93. package/plan-tools/helpers.ts +177 -0
  94. package/plan-tools/jira-branch-tool.ts +54 -0
  95. package/plan-tools/jira-branch.ts +109 -0
  96. package/plan-tools/jira-issue.ts +85 -0
  97. package/plan-tools/resolve-feature-path.ts +30 -0
  98. package/plan-tools/resolve-notes-path.ts +37 -0
  99. package/plan-tools/resolve-spec-path.ts +31 -0
  100. package/pr-quality/index.ts +908 -0
  101. package/review/LICENSE +19 -0
  102. package/review/deviation.ts +252 -0
  103. package/review/review.ts +3053 -0
  104. package/review/sem-guidance.d.mts +8 -0
  105. package/review/sem-guidance.mjs +89 -0
  106. package/review/verdict.ts +13 -0
  107. package/run-state.ts +2046 -0
  108. package/run-title.ts +91 -0
  109. package/server/consumer.ts +146 -0
  110. package/server/daemon.ts +1094 -0
  111. package/server/lifecycle.ts +679 -0
  112. package/server/pending.ts +267 -0
  113. package/server/staleness.ts +320 -0
  114. package/server/writer.ts +86 -0
  115. package/shared/diff-base.ts +138 -0
  116. package/shared/flow-base.ts +210 -0
  117. package/shared/sonarqube-utils.ts +415 -0
  118. package/shared/stable-range.ts +102 -0
  119. package/slugify.ts +13 -0
  120. package/sonarqube/sonarqube.ts +821 -0
  121. package/spec-review/approve.ts +91 -0
  122. package/spec-review/args.ts +21 -0
  123. package/spec-review/aven-spec.ts +142 -0
  124. package/spec-review/commands.ts +336 -0
  125. package/spec-review/escape-regexp.ts +7 -0
  126. package/spec-review/open-in-pane.ts +166 -0
  127. package/spec-review/picker.ts +74 -0
  128. package/spec-review/prompt.ts +72 -0
  129. package/spec-review/publish-args.ts +33 -0
  130. package/spec-review/publish.ts +210 -0
  131. package/telemetry/attributes.ts +118 -0
  132. package/telemetry/content.ts +140 -0
  133. package/telemetry/dispatch.ts +521 -0
  134. package/telemetry/exporter.ts +124 -0
  135. package/telemetry/index.ts +776 -0
  136. package/telemetry/loki.ts +224 -0
  137. package/tools/code-review-parse.ts +518 -0
  138. package/tools/code-review.ts +312 -0
  139. package/tools/deviation.ts +737 -0
  140. package/tools/flow-submit.ts +302 -0
  141. package/tools/land.ts +608 -0
  142. package/tools/phase-complete.ts +476 -0
  143. package/tools/result.ts +18 -0
  144. package/tools/review-deps.ts +44 -0
  145. package/tools/run-attempt.ts +312 -0
  146. package/tools/spec-approve.ts +265 -0
  147. package/validate/args.ts +22 -0
  148. package/validate/deviation-gate.ts +229 -0
  149. package/validate/gate-target.ts +371 -0
  150. package/validate/gate.ts +79 -0
  151. package/validate/paths.ts +20 -0
  152. package/validate/personal.ts +104 -0
  153. package/validate/prompt.ts +525 -0
  154. package/validate/review-gate.ts +134 -0
  155. package/validate/subtask-range.ts +113 -0
  156. package/work-mode.ts +19 -0
  157. package/worktree/bootstrap.ts +243 -0
  158. package/worktree/branch.ts +168 -0
  159. package/worktree/herdr.ts +447 -0
  160. package/worktree/index.ts +1447 -0
  161. package/worktree/orphan.ts +384 -0
  162. package/worktree/remove-guards.ts +99 -0
  163. package/worktree/residue.ts +216 -0
  164. package/worktree/sweep.ts +526 -0
@@ -0,0 +1,960 @@
1
+ #!/usr/bin/env node
2
+ // harness-profiler: records every tool call of a coding agent session and
3
+ // prints the calls as a tree. One file, no dependencies, Node 18+.
4
+ //
5
+ // hp capture <harness> hook entry point: reads one payload on stdin
6
+ // hp tree [id-prefix] [--branch <name>] [--verbose] [--format text|html]
7
+ // hp init claude commits the hook into this repo (Claude Code on the web)
8
+ // hp doctor says whether capture works here and why not
9
+ 'use strict';
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const os = require('os');
14
+
15
+ const SCHEMA_VERSION = 2;
16
+ const TRACE_DIR = '.harness-profile';
17
+ const TOOL_EVENTS = ['PostToolUse', 'PostToolUseFailure'];
18
+ const SESSION_EVENTS = ['PreCompact', 'PostCompact', 'SessionStart', 'SubagentStop'];
19
+ const LAUNCHED = 'async_launched';
20
+ const CAPTURED_EVENTS = [...TOOL_EVENTS, ...SESSION_EVENTS];
21
+ const COPY_AGENT_TYPE = 'fork';
22
+ const MAIN = 'main';
23
+ const VIEW_TEMPLATE = 'view.html';
24
+ const SHOW_SKILL = path.join('skills', 'show-profile');
25
+ const DATA_SLOT = '/*DATA*/null';
26
+ const DUPLICATE_EVENT_MS = 5000;
27
+ const TRANSCRIPT_TAIL_BYTES = 512 * 1024;
28
+ const ANSI_COLORS = [36, 33, 35, 32, 34, 31];
29
+ const PARENT_TOOLS = ['Skill', 'Agent'];
30
+ const HANDBACK = 'SubagentHandback';
31
+ const DEFAULT_AGENT = 'general-purpose';
32
+ const NAME_LIMIT = 80;
33
+ const ARGS_LIMIT = 200;
34
+ const RESULT_LIMIT = 300;
35
+ const LINE_LIMIT = 4096;
36
+ const TREE_WIDTH = 160;
37
+ const CONTEXT_WIDTH = 6;
38
+ const SESSION_WIDTH = 8;
39
+ const SHORT_SHA = 7;
40
+ const NEWLINE = ' ⏎ ';
41
+ const ELLIPSIS = '…';
42
+ const SECRETS = [
43
+ [/\b(Bearer|Basic|token)\s+[\w.~+/=-]{8,}/gi, '$1 [redacted]'],
44
+ [/\b((?:api[_-]?key|access[_-]?token|token|secret|password|passwd|authorization)["']?\s*[:=]\s*["']?)[^\s"'&]+/gi, '$1[redacted]'],
45
+ [/\b(?:gh[pousr]_|github_pat_|sk-|xox[abp]-)[\w-]{10,}/g, '[redacted]'],
46
+ ];
47
+ const SECRET_KEY = /token|secret|password|api_?key|authorization|credential/i;
48
+ const LAUNCHER = 'hp.sh';
49
+ // Before 0.2.0 the launcher was `hp`, and a committed hook ran it by that name.
50
+ const OLD_LAUNCHER = 'hp';
51
+ const hookCommand = (launcher) => `sh "$CLAUDE_PROJECT_DIR/.claude/harness-profiler/${launcher}" capture claude`;
52
+ const HOOK_COMMAND = hookCommand(LAUNCHER);
53
+ const OLD_HOOK_COMMAND = hookCommand(OLD_LAUNCHER);
54
+ const HOOK_TIMEOUT_S = 5;
55
+ const HOOK_DIR = path.join('.claude', 'harness-profiler');
56
+ const HOOK_FILES = [LAUNCHER, 'hp.js', VIEW_TEMPLATE];
57
+
58
+ // ---------- text helpers ----------
59
+
60
+ function mask(text) {
61
+ return SECRETS.reduce((out, [pattern, replacement]) => out.replace(pattern, replacement), text);
62
+ }
63
+
64
+ function clip(text, limit) {
65
+ return text.length <= limit ? text : text.slice(0, Math.max(limit - 1, 0)) + ELLIPSIS;
66
+ }
67
+
68
+ function oneLine(text) {
69
+ return String(text).trim().split(/\r?\n/).map((l) => l.trim()).filter(Boolean).join(NEWLINE);
70
+ }
71
+
72
+ function firstLine(text) {
73
+ return String(text).split(/\r?\n/).map((l) => l.trim()).find(Boolean) || '';
74
+ }
75
+
76
+ // ---------- git, without spawning git ----------
77
+
78
+ function gitRoot(start) {
79
+ let dir = path.resolve(start);
80
+ for (;;) {
81
+ if (fs.existsSync(path.join(dir, '.git'))) return dir;
82
+ const up = path.dirname(dir);
83
+ if (up === dir) return null;
84
+ dir = up;
85
+ }
86
+ }
87
+
88
+ // A worktree's `.git` is a file pointing at its own git dir.
89
+ function gitDir(root) {
90
+ const dotGit = path.join(root, '.git');
91
+ if (fs.statSync(dotGit).isDirectory()) return dotGit;
92
+ const target = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/m)[1].trim();
93
+ return path.resolve(root, target);
94
+ }
95
+
96
+ // Worktrees share `info/exclude` with the main repository.
97
+ function commonGitDir(dir) {
98
+ const pointer = path.join(dir, 'commondir');
99
+ return fs.existsSync(pointer) ? path.resolve(dir, fs.readFileSync(pointer, 'utf8').trim()) : dir;
100
+ }
101
+
102
+ function branchOf(start) {
103
+ try {
104
+ const root = gitRoot(start);
105
+ if (!root) return undefined;
106
+ const head = fs.readFileSync(path.join(gitDir(root), 'HEAD'), 'utf8').trim();
107
+ const ref = head.match(/^ref:\s*refs\/heads\/(.+)$/);
108
+ return ref ? ref[1] : head.slice(0, SHORT_SHA);
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ }
113
+
114
+ function excludeTraces(projectDir) {
115
+ const root = gitRoot(projectDir);
116
+ if (!root) return;
117
+ const exclude = path.join(commonGitDir(gitDir(root)), 'info', 'exclude');
118
+ const current = fs.existsSync(exclude) ? fs.readFileSync(exclude, 'utf8') : '';
119
+ if (current.split(/\r?\n/).includes(`${TRACE_DIR}/`)) return;
120
+ fs.mkdirSync(path.dirname(exclude), { recursive: true });
121
+ fs.appendFileSync(exclude, `${current && !current.endsWith('\n') ? '\n' : ''}${TRACE_DIR}/\n`);
122
+ }
123
+
124
+ // Claude Code sets CLAUDE_PROJECT_DIR to the launch directory, which can sit
125
+ // below the git root. Traces go to the git root so `hp tree` finds them from
126
+ // anywhere in the repository.
127
+ function projectDir(cwd, env = hookEnv()) {
128
+ const start = env.CLAUDE_PROJECT_DIR || cwd;
129
+ return gitRoot(start) || start;
130
+ }
131
+
132
+ // The one variable the hook needs. The plugin directory's scan holds a plugin
133
+ // that hands the whole environment around.
134
+ function hookEnv() {
135
+ return { CLAUDE_PROJECT_DIR: process.env.CLAUDE_PROJECT_DIR };
136
+ }
137
+
138
+ // ---------- capture ----------
139
+
140
+ function toolOf(name) {
141
+ return name.startsWith('mcp__') ? 'mcp' : name;
142
+ }
143
+
144
+ function nameOf(payload) {
145
+ const input = payload.tool_input || {};
146
+ switch (payload.tool_name) {
147
+ case 'Skill': return input.skill;
148
+ case 'Agent': return input.subagent_type || DEFAULT_AGENT;
149
+ case 'Bash': return firstLine(input.command || '').replace(/^cd\s+("[^"]*"|'[^']*'|\S+)\s*&&\s*/, '');
150
+ default:
151
+ return payload.tool_name.startsWith('mcp__') ? payload.tool_name.split('__').pop() : undefined;
152
+ }
153
+ }
154
+
155
+ function argsOf(payload) {
156
+ const input = payload.tool_input || {};
157
+ switch (payload.tool_name) {
158
+ case 'Skill': return input.args;
159
+ case 'Agent': return [input.description, firstLine(input.prompt || '')].filter(Boolean).join(': ');
160
+ case 'Bash': return input.command;
161
+ case HANDBACK: return undefined;
162
+ default: {
163
+ const safe = {};
164
+ for (const [key, value] of Object.entries(input)) safe[key] = SECRET_KEY.test(key) ? '[redacted]' : value;
165
+ return Object.keys(safe).length ? JSON.stringify(safe) : undefined;
166
+ }
167
+ }
168
+ }
169
+
170
+ function responseText(response) {
171
+ if (response == null) return '';
172
+ if (typeof response === 'string') return response;
173
+ if (typeof response.result === 'string') return response.result;
174
+ if (Array.isArray(response.content)) {
175
+ return response.content.map((part) => (part && typeof part.text === 'string' ? part.text : '')).join('\n');
176
+ }
177
+ return [response.stdout, response.stderr].filter((s) => typeof s === 'string').join('\n');
178
+ }
179
+
180
+ // Claude Code may open a subagent's reply with the tools it used:
181
+ // <tools-used-before-summary>Bash</tools-used-before-summary>\nS => S
182
+ const TOOLS_USED = /^\s*<tools-used-before-summary>[\s\S]*?<\/tools-used-before-summary>/;
183
+
184
+ // Claude Code's reply to a call it started in the background:
185
+ // Agent {"status":"async_launched","agentId":"a1"}
186
+ // Skill {"status":"forked","background":true,"agentId":"a1","result":"Running in the background as @validator"}
187
+ function isBackground(response) {
188
+ return Boolean(response) && (response.status === LAUNCHED || response.background === true);
189
+ }
190
+
191
+ // A background subagent reports to its caller with a SubagentHandback call:
192
+ // tool_input {"message":"Both verdicts are PASS.\n\n- **Implementation:** ..."}
193
+ // tool_response "Report delivered to your caller."
194
+ // The stop that follows has an empty last_assistant_message.
195
+ function resultOf(payload) {
196
+ const response = payload.tool_response;
197
+ if (payload.tool_name === HANDBACK) return firstLine((payload.tool_input || {}).message || '') || undefined;
198
+ if (payload.tool_name === 'Skill' && !(response && response.agentId)) return undefined;
199
+ if (isBackground(response)) return undefined;
200
+ const text = firstLine(responseText(response).replace(TOOLS_USED, '')) || firstLine(payload.error || '');
201
+ return text || undefined;
202
+ }
203
+
204
+ // How full the calling context was when the model asked for this call: the
205
+ // usage on the assistant message that holds the tool_use, read from the tail
206
+ // of Claude Code's transcript. A subagent writes its own transcript:
207
+ // <session>.jsonl main
208
+ // <session>/subagents/agent-<id>.jsonl subagent <id>
209
+ // The transcript format is Claude Code's own and undocumented, so any miss
210
+ // leaves the field out.
211
+ function contextTokensOf(payload) {
212
+ try {
213
+ if (!payload.transcript_path || !payload.tool_use_id) return undefined;
214
+ const file = payload.agent_id ? subagentTranscript(payload.transcript_path, payload.agent_id) : payload.transcript_path;
215
+ const size = fs.statSync(file).size;
216
+ const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
217
+ const buffer = Buffer.alloc(length);
218
+ const fd = fs.openSync(file, 'r');
219
+ try { fs.readSync(fd, buffer, 0, length, size - length); } finally { fs.closeSync(fd); }
220
+ const lines = buffer.toString('utf8').split('\n');
221
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
222
+ if (!lines[i].includes(payload.tool_use_id)) continue;
223
+ const found = usageByToolUse(lines[i]).get(payload.tool_use_id);
224
+ if (found !== undefined) return found;
225
+ }
226
+ } catch { /* no transcript, or not the format we know */ }
227
+ return undefined;
228
+ }
229
+
230
+ // tool_use id -> context tokens, for one transcript line.
231
+ function usageByToolUse(line) {
232
+ const found = new Map();
233
+ let entry;
234
+ try { entry = JSON.parse(line); } catch { return found; }
235
+ const message = (entry && entry.message) || {};
236
+ const usage = message.usage;
237
+ if (!usage || !Array.isArray(message.content)) return found;
238
+ const total = (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0);
239
+ for (const c of message.content) if (c && c.type === 'tool_use' && c.id) found.set(c.id, total);
240
+ return found;
241
+ }
242
+
243
+ function subagentTranscript(main, id) {
244
+ return path.join(main.replace(/\.jsonl$/, ''), 'subagents', `agent-${id}.jsonl`);
245
+ }
246
+
247
+ // Every transcript a trace names: main's, recorded on SessionStart, and each
248
+ // subagent's next to it.
249
+ function transcriptFiles(records) {
250
+ const files = [];
251
+ for (const main of new Set(records.filter((r) => r.transcript).map((r) => r.transcript))) {
252
+ files.push({ ctx: MAIN, file: main });
253
+ const dir = path.join(main.replace(/\.jsonl$/, ''), 'subagents');
254
+ let names = [];
255
+ try { names = fs.readdirSync(dir); } catch { /* no subagents */ }
256
+ for (const f of names) {
257
+ const id = /^agent-(.+)\.jsonl$/.exec(f);
258
+ if (id) files.push({ ctx: id[1], file: path.join(dir, f) });
259
+ }
260
+ }
261
+ return files;
262
+ }
263
+
264
+ function readText(file) {
265
+ try { return fs.readFileSync(file, 'utf8'); } catch { return undefined; }
266
+ }
267
+
268
+ // An async hook can run before Claude Code flushes the transcript, so calls
269
+ // recorded without context_tokens get them from the transcripts at render time,
270
+ // if those files still exist.
271
+ function fillContextTokens(records) {
272
+ const missing = records.filter((r) => r.tool && r.tool_use_id && r.context_tokens === undefined);
273
+ if (!missing.length) return records;
274
+ const found = new Map();
275
+ for (const { file } of transcriptFiles(records)) {
276
+ const text = readText(file);
277
+ if (text === undefined) continue;
278
+ for (const line of text.split('\n')) {
279
+ if (line.includes('"tool_use"')) for (const [id, n] of usageByToolUse(line)) found.set(id, n);
280
+ }
281
+ }
282
+ return records.map((r) => (r.tool && r.context_tokens === undefined && found.has(r.tool_use_id) ? { ...r, context_tokens: found.get(r.tool_use_id) } : r));
283
+ }
284
+
285
+ // What a context spent, summed over its model calls. Each call sends the whole
286
+ // history again: what the prompt cache already held is `cached`, the rest
287
+ // (plain input and cache writes) is `new`, and the reply is `out`. They cost
288
+ // different amounts, so they stay apart. One response can span several
289
+ // transcript lines with the same message id.
290
+ function spentTokens(text) {
291
+ const seen = new Set();
292
+ const spend = { new: 0, cached: 0, out: 0, calls: 0 };
293
+ for (const line of text.split('\n')) {
294
+ if (!line.includes('"usage"')) continue;
295
+ let entry;
296
+ try { entry = JSON.parse(line); } catch { continue; }
297
+ const message = entry && entry.type === 'assistant' && entry.message;
298
+ if (!message || !message.usage) continue;
299
+ if (message.id && seen.has(message.id)) continue;
300
+ if (message.id) seen.add(message.id);
301
+ const u = message.usage;
302
+ spend.new += (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0);
303
+ spend.cached += u.cache_read_input_tokens || 0;
304
+ spend.out += u.output_tokens || 0;
305
+ spend.calls += 1;
306
+ }
307
+ return spend.calls ? spend : undefined;
308
+ }
309
+
310
+ function spentByChild(payload, childId) {
311
+ if (!payload.transcript_path || !childId) return undefined;
312
+ const text = readText(subagentTranscript(payload.transcript_path, childId));
313
+ return text === undefined ? undefined : spentTokens(text);
314
+ }
315
+
316
+ // context id -> { new, cached, out, calls }: from the transcripts while they exist,
317
+ // otherwise what capture recorded for each subagent.
318
+ function contextSpend(records) {
319
+ const spend = new Map();
320
+ for (const r of uniqueCalls(records)) {
321
+ if (r.child_agent_id && r.child_spend) spend.set(r.child_agent_id, r.child_spend);
322
+ }
323
+ for (const stop of subagentStops(records).values()) {
324
+ if (stop.spend) spend.set(stop.agent_id, stop.spend);
325
+ }
326
+ for (const { ctx, file } of transcriptFiles(records)) {
327
+ const text = readText(file);
328
+ const spent = text === undefined ? undefined : spentTokens(text);
329
+ if (spent) spend.set(ctx, spent);
330
+ }
331
+ return spend;
332
+ }
333
+
334
+ // Record fields in schema order; absent values are left out.
335
+ function buildRecord(payload, harness, now = new Date()) {
336
+ const response = payload.tool_response || {};
337
+ const isParent = PARENT_TOOLS.includes(payload.tool_name);
338
+ const name = nameOf(payload);
339
+ const args = argsOf(payload);
340
+ const result = resultOf(payload);
341
+ const childId = isParent ? response.agentId : undefined;
342
+ // A background subagent is still at work: its end, result and spend come with
343
+ // its SubagentStop.
344
+ const background = isBackground(response);
345
+ const spent = background ? undefined : spentByChild(payload, childId);
346
+ const input = payload.tool_input || {};
347
+ const record = {
348
+ v: SCHEMA_VERSION,
349
+ harness,
350
+ at: now.toISOString(),
351
+ session: payload.session_id,
352
+ agent_id: payload.agent_id,
353
+ agent_type: payload.agent_type,
354
+ tool_use_id: payload.tool_use_id,
355
+ tool: toolOf(payload.tool_name),
356
+ name: name && clip(mask(String(name)), NAME_LIMIT),
357
+ duration_ms: payload.duration_ms,
358
+ ok: payload.hook_event_name !== 'PostToolUseFailure',
359
+ child_agent_id: childId,
360
+ child_agent_type: childId ? response.agentType || (payload.tool_name === 'Agent' ? input.subagent_type : undefined) : undefined,
361
+ background: background || undefined,
362
+ child_spend: spent,
363
+ tokens: typeof response.totalTokens === 'number' ? response.totalTokens : undefined,
364
+ context_tokens: contextTokensOf(payload),
365
+ branch: branchOf(payload.cwd || process.cwd()),
366
+ args: args ? clip(mask(oneLine(typeof args === 'string' ? args : JSON.stringify(args))), ARGS_LIMIT) : undefined,
367
+ result: result ? clip(mask(result), RESULT_LIMIT) : undefined,
368
+ };
369
+ return JSON.parse(JSON.stringify(record));
370
+ }
371
+
372
+ // `result`, then `args`, give way until the line fits.
373
+ function serialize(record) {
374
+ let line = JSON.stringify(record);
375
+ const fitted = { ...record };
376
+ for (const key of ['result', 'args']) {
377
+ while (Buffer.byteLength(line) > LINE_LIMIT && fitted[key]) {
378
+ const shorter = Math.floor(fitted[key].length / 2);
379
+ if (shorter < 1) delete fitted[key];
380
+ else fitted[key] = clip(fitted[key], shorter);
381
+ line = JSON.stringify(fitted);
382
+ }
383
+ }
384
+ return line;
385
+ }
386
+
387
+ // Compaction and session starts are markers, not calls: no `tool`.
388
+ function buildEventRecord(payload, harness, now = new Date()) {
389
+ const record = {
390
+ v: SCHEMA_VERSION,
391
+ harness,
392
+ at: now.toISOString(),
393
+ session: payload.session_id,
394
+ agent_id: payload.agent_id,
395
+ event: payload.hook_event_name,
396
+ trigger: payload.trigger,
397
+ source: payload.source,
398
+ context_tokens: typeof payload.context_tokens === 'number' ? payload.context_tokens : undefined,
399
+ transcript: payload.hook_event_name === 'SessionStart' ? payload.transcript_path : undefined,
400
+ };
401
+ if (payload.hook_event_name === 'SubagentStop') {
402
+ const text = readText(payload.agent_transcript_path || '');
403
+ const spent = text === undefined ? undefined : spentTokens(text);
404
+ const result = firstLine(String(payload.last_assistant_message || '').replace(TOOLS_USED, ''));
405
+ Object.assign(record, {
406
+ agent_type: payload.agent_type || undefined,
407
+ spend: spent,
408
+ result: result ? clip(mask(result), RESULT_LIMIT) : undefined,
409
+ });
410
+ }
411
+ return JSON.parse(JSON.stringify(record));
412
+ }
413
+
414
+ function sessionFile(dir, session) {
415
+ return path.join(dir, TRACE_DIR, `${String(session).replace(/[^\w.-]/g, '_')}.jsonl`);
416
+ }
417
+
418
+ function capture(harness, input, env = hookEnv(), now = new Date()) {
419
+ const payload = JSON.parse(input);
420
+ const isTool = TOOL_EVENTS.includes(payload.hook_event_name);
421
+ if (!CAPTURED_EVENTS.includes(payload.hook_event_name) || !payload.session_id || (isTool && !payload.tool_name)) return null;
422
+ const dir = projectDir(payload.cwd || process.cwd(), env);
423
+ const file = sessionFile(dir, payload.session_id);
424
+ if (!fs.existsSync(path.dirname(file))) {
425
+ fs.mkdirSync(path.dirname(file), { recursive: true });
426
+ excludeTraces(dir);
427
+ }
428
+ // One small O_APPEND write per record keeps concurrent hooks from interleaving.
429
+ const record = isTool ? buildRecord(payload, harness, now) : buildEventRecord(payload, harness, now);
430
+ fs.appendFileSync(file, serialize(record) + '\n');
431
+ return file;
432
+ }
433
+
434
+ // ---------- tree ----------
435
+
436
+ function readTrace(file) {
437
+ const records = [];
438
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
439
+ if (!line.trim()) continue;
440
+ try { records.push(JSON.parse(line)); } catch { /* a torn line is skipped */ }
441
+ }
442
+ return records;
443
+ }
444
+
445
+ function startOf(record) {
446
+ return Date.parse(record.at) - (record.duration_ms || 0);
447
+ }
448
+
449
+ function formatDuration(ms) {
450
+ if (ms < 1000) return `${ms} ms`;
451
+ const tenths = Math.round(ms / 100) / 10;
452
+ return tenths < 10 ? `${tenths.toFixed(1)} s` : `${Math.round(ms / 1000)} s`;
453
+ }
454
+
455
+ function formatCount(n) {
456
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
457
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
458
+ return `${n}`;
459
+ }
460
+
461
+ function formatSpend(spend) {
462
+ return [`${formatCount(spend.new)} new`, `${formatCount(spend.cached)} cached`, `${formatCount(spend.out)} out`];
463
+ }
464
+
465
+ function clock(ms) {
466
+ return new Date(ms).toISOString().slice(11, 19);
467
+ }
468
+
469
+ // Plugin and committed hook on one machine record everything twice.
470
+ function uniqueCalls(records) {
471
+ const seen = new Set();
472
+ const stops = subagentStops(records);
473
+ const handbacks = new Map(records.filter((r) => r.tool === HANDBACK && r.agent_id && r.result).map((r) => [r.agent_id, r.result]));
474
+ return records.filter((record) => {
475
+ if (!record.tool) return false;
476
+ if (!record.tool_use_id) return true;
477
+ if (seen.has(record.tool_use_id)) return false;
478
+ seen.add(record.tool_use_id);
479
+ return true;
480
+ }).map((record) => withStop(record, stops.get(record.child_agent_id), handbacks.get(record.child_agent_id)));
481
+ }
482
+
483
+ // A background subagent stops each time it has nothing to do and is woken when
484
+ // a child of its own reports, so the last stop is the one that ends it:
485
+ // 22:13:31 "Waiting on reviewer."
486
+ // 22:13:44 "**PASS** ..."
487
+ function subagentStops(records) {
488
+ const stops = new Map();
489
+ for (const r of records) if (r.event === 'SubagentStop' && r.agent_id) stops.set(r.agent_id, { ...stops.get(r.agent_id), ...r });
490
+ return stops;
491
+ }
492
+
493
+ // Traces captured before a background skill was told apart from a finished one
494
+ // hold Claude Code's launch notice as the call's result.
495
+ const LAUNCH_NOTICE = /^Running in the background as @/;
496
+
497
+ // A background subagent's call returns at once; it ends at its SubagentStop.
498
+ // Its result is what it handed back. A later notice can wake it once more,
499
+ // and that stop's message is a remark, not the report:
500
+ // 17:58:18 SubagentHandback "Both verdicts are PASS."
501
+ // 17:58:21 SubagentStop "The completion notice adds nothing new: ..."
502
+ // Until its first stop it is `running`: the duration recorded so far is the
503
+ // launch, about 25 ms, not the work.
504
+ function withStop(record, stop, handback) {
505
+ const { result, ...launched } = record;
506
+ const call = LAUNCH_NOTICE.test(result || '') ? { ...launched, background: true } : record;
507
+ if (!stop) return call.background ? { ...call, running: true } : call;
508
+ const merged = { ...call, child_agent_type: call.child_agent_type || stop.agent_type };
509
+ if (!call.background) return merged;
510
+ const start = startOf(call);
511
+ return { ...merged, at: stop.at, duration_ms: Math.max(0, Date.parse(stop.at) - start), result: handback || call.result || stop.result };
512
+ }
513
+
514
+ function uniqueEvents(records) {
515
+ const kept = [];
516
+ for (const record of records) {
517
+ if (record.tool || !record.event) continue;
518
+ const at = Date.parse(record.at);
519
+ const twin = kept.find((k) => k.event === record.event && k.agent_id === record.agent_id
520
+ && k.trigger === record.trigger && k.source === record.source && Math.abs(Date.parse(k.at) - at) < DUPLICATE_EVENT_MS);
521
+ if (!twin) kept.push(record);
522
+ }
523
+ return kept;
524
+ }
525
+
526
+ const TOOL_WORDS = { Skill: 'skill', Agent: 'agent' };
527
+
528
+ // The name leads and the kind follows: `review (skill)`, `counter (agent)`,
529
+ // `wc -l notes.txt (Bash)`.
530
+ function callLabel(tool, name) {
531
+ const word = TOOL_WORDS[tool] || tool;
532
+ return name ? `${name} (${word})` : word;
533
+ }
534
+
535
+ function contextOf(record) {
536
+ return record.agent_id || MAIN;
537
+ }
538
+
539
+ function shortId(id) {
540
+ return id === MAIN ? MAIN : id.slice(0, CONTEXT_WIDTH);
541
+ }
542
+
543
+ // A context is one conversation history: main, or a subagent started by a
544
+ // forked Skill or an Agent call. Inline skills and compactions are markers in
545
+ // one. A `fork` subagent starts with a copy of its parent's history; every
546
+ // other subagent starts with its prompt only.
547
+ function contextsOf(records) {
548
+ const calls = uniqueCalls(records);
549
+ const contexts = [{ id: MAIN, parent: undefined, kind: 'root', label: MAIN }];
550
+ const known = new Set([MAIN]);
551
+ for (const r of calls) {
552
+ if (!r.child_agent_id || known.has(r.child_agent_id)) continue;
553
+ known.add(r.child_agent_id);
554
+ contexts.push({
555
+ id: r.child_agent_id,
556
+ parent: contextOf(r),
557
+ kind: r.child_agent_type === COPY_AGENT_TYPE ? 'copy' : 'fresh',
558
+ label: callLabel(r.tool, r.name),
559
+ name: r.name,
560
+ tool: r.tool,
561
+ start: startOf(r),
562
+ end: Date.parse(r.at),
563
+ });
564
+ }
565
+ for (const r of calls) {
566
+ const id = contextOf(r);
567
+ if (known.has(id)) continue;
568
+ known.add(id);
569
+ contexts.push({ id, parent: undefined, kind: 'fresh', label: callLabel('Agent', r.agent_type || DEFAULT_AGENT), name: r.agent_type || DEFAULT_AGENT, tool: 'Agent' });
570
+ }
571
+
572
+ // Calls are recorded when they end, so order by start: a caller's lifeline
573
+ // stays left of the contexts it starts. Unrecorded parents go last.
574
+ const started = contexts.slice(1).sort((x, y) => (x.start ?? Infinity) - (y.start ?? Infinity));
575
+ contexts.splice(1, started.length, ...started);
576
+
577
+ // Color follows history: a copy keeps its parent's hue, a fresh context gets the next one.
578
+ const hues = new Map();
579
+ let nextHue = 0;
580
+ for (const c of contexts) {
581
+ c.hue = c.kind === 'copy' && hues.has(c.parent) ? hues.get(c.parent) : nextHue++;
582
+ hues.set(c.id, c.hue);
583
+ }
584
+
585
+ const markers = calls
586
+ .filter((r) => r.tool === 'Skill' && !r.child_agent_id)
587
+ .map((r) => ({ kind: 'inline', ctx: contextOf(r), at: startOf(r), name: r.name }));
588
+ let open;
589
+ for (const e of uniqueEvents(records)) {
590
+ if (e.event === 'PreCompact') {
591
+ open = { kind: 'compact', ctx: contextOf(e), at: Date.parse(e.at), trigger: e.trigger };
592
+ markers.push(open);
593
+ } else if (e.event === 'PostCompact') {
594
+ if (!open) markers.push({ kind: 'compact', ctx: contextOf(e), at: Date.parse(e.at), trigger: e.trigger });
595
+ open = undefined;
596
+ }
597
+ }
598
+ markers.sort((a, b) => a.at - b.at);
599
+ return { contexts, markers };
600
+ }
601
+
602
+ function buildForest(records, markers = []) {
603
+ const nodes = uniqueCalls(records).map((record, index) => ({ record, index, start: startOf(record), children: [] }));
604
+ const byChild = new Map(nodes.filter((n) => n.record.child_agent_id).map((n) => [n.record.child_agent_id, n]));
605
+ const placeholders = new Map();
606
+ const roots = [];
607
+ const containerOf = (agent, start, index, agentType) => {
608
+ if (!agent) return roots;
609
+ let parent = byChild.get(agent);
610
+ if (!parent) {
611
+ parent = placeholders.get(agent);
612
+ if (!parent) {
613
+ parent = { placeholder: true, agent, agentType, start, index, children: [] };
614
+ placeholders.set(agent, parent);
615
+ roots.push(parent);
616
+ }
617
+ parent.start = Math.min(parent.start, start);
618
+ }
619
+ return parent.children;
620
+ };
621
+ for (const node of nodes) containerOf(node.record.agent_id, node.start, node.index, node.record.agent_type).push(node);
622
+ for (const marker of markers) {
623
+ const ctx = marker.ctx === MAIN ? undefined : marker.ctx;
624
+ containerOf(ctx, marker.at, Infinity).push({ marker, start: marker.at, index: Infinity, children: [] });
625
+ }
626
+ sortTree(roots);
627
+ return roots;
628
+ }
629
+
630
+ function sortTree(nodes) {
631
+ nodes.sort((a, b) => a.start - b.start || a.index - b.index);
632
+ for (const node of nodes) sortTree(node.children);
633
+ }
634
+
635
+ function visible(node, verbose) {
636
+ return verbose || node.placeholder || node.marker || PARENT_TOOLS.includes(node.record.tool);
637
+ }
638
+
639
+ // How the call relates to contexts: `inline` for a skill that ran in its
640
+ // caller's context, `new context <id>` for one that started a subagent, plus
641
+ // `copy of <parent>` when that subagent began with the caller's history.
642
+ function contextWords(record, kinds) {
643
+ if (record.child_agent_id) {
644
+ const words = [`new context ${shortId(record.child_agent_id)}`];
645
+ if (kinds.get(record.child_agent_id) === 'copy') words.push(`copy of ${shortId(contextOf(record))}`);
646
+ if (record.background) words.push('background');
647
+ return words.join(', ');
648
+ }
649
+ return record.tool === 'Skill' ? 'inline' : '';
650
+ }
651
+
652
+ function detail(record, budget) {
653
+ let args = record.args && record.args !== record.name ? record.args : undefined;
654
+ let result = PARENT_TOOLS.includes(record.tool) || record.ok === false ? record.result : undefined;
655
+ if (budget !== undefined) {
656
+ args = args && clip(args, result ? Math.floor(budget / 2) : budget);
657
+ result = result && clip(result, budget - (args ? args.length + 3 : 0) - 3);
658
+ }
659
+ return [args && `(${args})`, result && `-> ${result}`].filter(Boolean).join(' ');
660
+ }
661
+
662
+ function paint(text, ctx, colors) {
663
+ const code = colors && colors.get(ctx);
664
+ return code ? `\x1b[${code}m${text}\x1b[0m` : text;
665
+ }
666
+
667
+ const BAR_CELLS = 8;
668
+ // In the duration column of a background call that has not stopped yet.
669
+ const RUNNING = 'running';
670
+ const BAR_EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
671
+ const BAR_STEPS = BAR_EIGHTHS.length;
672
+ const COLUMNS = [['time', 8, 'left'], ['duration', 8, 'right'], ['', BAR_CELLS, 'left'], ['new', 6, 'right'], ['cached', 7, 'right'], ['out', 6, 'right']];
673
+ const COLUMN_GAP = ' ';
674
+
675
+ function cell(text, [, width, align]) {
676
+ return align === 'right' ? text.padStart(width) : text.padEnd(width);
677
+ }
678
+
679
+ function columns(values) {
680
+ return COLUMNS.map((col, i) => cell(values[i] || '', col)).join(' ') + COLUMN_GAP;
681
+ }
682
+
683
+ // A square-root scale: the longest call fills the bar, a call a quarter as long
684
+ // fills half and one a hundredth as long a tenth, so short calls stay visible
685
+ // without hiding the long ones.
686
+ function durationBar(ms, longest) {
687
+ if (!longest || !ms) return '';
688
+ const steps = Math.round(Math.sqrt(Math.min(ms, longest) / longest) * BAR_CELLS * BAR_STEPS);
689
+ return '█'.repeat(Math.floor(steps / BAR_STEPS)) + BAR_EIGHTHS[steps % BAR_STEPS];
690
+ }
691
+
692
+ function treeHeader() {
693
+ return columns(COLUMNS.map(([name]) => name)) + 'call';
694
+ }
695
+
696
+ function formatLine(node, depth, { verbose, kinds, colors, spend, longest }) {
697
+ const indent = ' '.repeat(depth);
698
+ if (node.placeholder) {
699
+ return columns([]) + paint(`${indent}${callLabel('Agent', node.agentType || DEFAULT_AGENT)} [${shortId(node.agent)}] parent not recorded`, node.agent, colors);
700
+ }
701
+ if (node.marker) {
702
+ const m = node.marker;
703
+ return columns([clock(m.at)]) + paint(`${indent}-- ${shortId(m.ctx)} compacted (${m.trigger || 'unknown trigger'})`, m.ctx, colors);
704
+ }
705
+ const r = node.record;
706
+ const ctx = contextOf(r);
707
+ const ms = r.running ? 0 : r.duration_ms || 0;
708
+ const spent = r.child_agent_id && spend.get(r.child_agent_id);
709
+ const prefix = columns([clock(node.start), r.running ? RUNNING : formatDuration(ms), durationBar(ms, longest), ...(spent ? [spent.new, spent.cached, spent.out].map(formatCount) : [])]);
710
+ const words = [contextWords(r, kinds), r.ok === false ? 'failed' : ''].filter(Boolean).join(' ');
711
+ const head = `${indent}${callLabel(r.tool, r.name)}`;
712
+ const plainHead = words ? `${head} ${words}` : head;
713
+ const budget = verbose ? undefined : TREE_WIDTH - prefix.length - plainHead.length - 2;
714
+ const tail = detail(r, budget);
715
+ const shownWords = words && r.child_agent_id ? words.replace(/^new context \S+/, (w) => paint(w, r.child_agent_id, colors)) : words;
716
+ return prefix + [paint(head, ctx, colors), shownWords, tail].filter(Boolean).join(' ');
717
+ }
718
+
719
+ // Main keeps the terminal's own color, and so does a copy of main.
720
+ function ansiColors(contexts) {
721
+ return new Map(contexts.filter((c) => c.hue > 0).map((c) => [c.id, ANSI_COLORS[(c.hue - 1) % ANSI_COLORS.length]]));
722
+ }
723
+
724
+ function renderTree(records, { verbose = false, color = false } = {}) {
725
+ const { contexts, markers } = contextsOf(records);
726
+ const options = { verbose, kinds: new Map(contexts.map((c) => [c.id, c.kind])), colors: color ? ansiColors(contexts) : undefined, spend: contextSpend(records) };
727
+ const shown = [];
728
+ const walk = (nodes, depth) => {
729
+ for (const node of nodes) {
730
+ if (!visible(node, verbose)) continue;
731
+ shown.push([node, depth]);
732
+ walk(node.children, depth + 1);
733
+ }
734
+ };
735
+ walk(buildForest(records, markers.filter((m) => m.kind === 'compact')), 0);
736
+ options.longest = Math.max(0, ...shown.map(([node]) => (node.record && node.record.duration_ms) || 0));
737
+ return [treeHeader(), ...shown.map(([node, depth]) => formatLine(node, depth, options))].join('\n');
738
+ }
739
+
740
+ // One self-contained page: the template from libexec/ with the trace inlined.
741
+ // `<` is escaped so tool output in the JSON can't close the script tag.
742
+ function renderHtml(session) {
743
+ const calls = uniqueCalls(fillContextTokens(session.records));
744
+ const { contexts, markers } = contextsOf(session.records);
745
+ const spend = contextSpend(session.records);
746
+ const data = {
747
+ session: session.id,
748
+ branch: (calls.find((r) => r.branch) || {}).branch,
749
+ contexts: contexts.map((c) => ({ ...c, spent: spend.get(c.id) })),
750
+ markers,
751
+ calls: calls.map((r) => ({
752
+ ctx: contextOf(r), tool: r.tool, name: r.name, start: startOf(r), dur: r.duration_ms || 0,
753
+ ok: r.ok !== false, ctxTokens: r.context_tokens, args: r.args, result: r.result, child: r.child_agent_id, background: r.background, running: r.running,
754
+ })),
755
+ };
756
+ const json = JSON.stringify(data).replace(/</g, '\\u003c');
757
+ const template = fs.readFileSync(path.join(__dirname, VIEW_TEMPLATE), 'utf8');
758
+ return template.replace(DATA_SLOT, () => json);
759
+ }
760
+
761
+ function listSessions(dir) {
762
+ const traces = path.join(dir, TRACE_DIR);
763
+ if (!fs.existsSync(traces)) return [];
764
+ return fs.readdirSync(traces)
765
+ .filter((f) => f.endsWith('.jsonl'))
766
+ .map((f) => {
767
+ const records = readTrace(path.join(traces, f));
768
+ const starts = records.map(startOf).filter(Number.isFinite);
769
+ return { id: f.replace(/\.jsonl$/, ''), records, first: Math.min(...starts), last: Math.max(...records.map((r) => Date.parse(r.at)).filter(Number.isFinite)) };
770
+ })
771
+ .filter((s) => s.records.length);
772
+ }
773
+
774
+ const FORMATS = ['text', 'html'];
775
+ const VALUE_FLAGS = ['--branch', '--format'];
776
+
777
+ function parseTreeArgs(argv) {
778
+ const options = { verbose: false, format: 'text' };
779
+ for (let i = 0; i < argv.length; i += 1) {
780
+ const arg = argv[i];
781
+ if (arg === '--verbose' || arg === '-v') options.verbose = true;
782
+ else if (VALUE_FLAGS.includes(arg)) options[arg.slice(2)] = argv[(i += 1)];
783
+ else if (!arg.startsWith('-')) options.prefix = arg;
784
+ }
785
+ if (!FORMATS.includes(options.format)) throw new UsageError(`Unknown format ${options.format}; use ${FORMATS.join(' or ')}.`);
786
+ return options;
787
+ }
788
+
789
+ function stamp(session) {
790
+ return `${new Date(session.first).toISOString().slice(0, 19).replace('T', ' ')} UTC`;
791
+ }
792
+
793
+ function tree(argv, dir, { color = false } = {}) {
794
+ const { verbose, format, branch, prefix } = parseTreeArgs(argv);
795
+ const sessions = listSessions(dir);
796
+ if (!sessions.length) throw new UsageError(`No traces in ${path.join(dir, TRACE_DIR)}. Run a session with the hook installed first.`);
797
+
798
+ let chosen;
799
+ if (branch) {
800
+ chosen = sessions.filter((s) => s.records.some((r) => r.branch === branch)).sort((a, b) => a.first - b.first);
801
+ if (!chosen.length) throw new UsageError(`No session recorded on branch ${branch}.`);
802
+ } else if (prefix) {
803
+ chosen = sessions.filter((s) => s.id.startsWith(prefix));
804
+ if (chosen.length !== 1) throw new UsageError(chosen.length ? `Session prefix ${prefix} is ambiguous.` : `No session starts with ${prefix}.`);
805
+ } else {
806
+ chosen = [sessions.reduce((a, b) => (b.last > a.last ? b : a))];
807
+ }
808
+ if (format === 'html') {
809
+ if (chosen.length > 1) {
810
+ const list = chosen.map((s) => ` ${s.id.slice(0, SESSION_WIDTH)} ${stamp(s)}`).join('\n');
811
+ throw new UsageError(`The html page shows one session. Pick one by id prefix:\n${list}`);
812
+ }
813
+ return renderHtml(chosen[0]);
814
+ }
815
+ if (!branch) return renderTree(chosen[0].records, { verbose, color });
816
+ return chosen
817
+ .map((s) => `# session ${s.id} (${stamp(s)})\n${renderTree(s.records, { verbose, color })}`)
818
+ .join('\n\n');
819
+ }
820
+
821
+ // ---------- init ----------
822
+
823
+ function hookEntry() {
824
+ return { matcher: '*', hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: HOOK_TIMEOUT_S, async: true }] };
825
+ }
826
+
827
+ const isOurCommand = (command) => command === HOOK_COMMAND || command === OLD_HOOK_COMMAND;
828
+ const isOurs = (entry) => (entry.hooks || []).some((h) => isOurCommand(h.command));
829
+
830
+ // Replaces an entry an older `init` wrote, so a re-run picks up new hook options.
831
+ function mergeHooks(settings) {
832
+ const merged = { ...settings, hooks: { ...(settings.hooks || {}) } };
833
+ for (const event of CAPTURED_EVENTS) {
834
+ const entries = merged.hooks[event] || [];
835
+ const at = entries.findIndex(isOurs);
836
+ merged.hooks[event] = at < 0 ? [...entries, hookEntry()]
837
+ : [...entries.slice(0, at), hookEntry(), ...entries.slice(at + 1).filter((e) => !isOurs(e))];
838
+ }
839
+ return merged;
840
+ }
841
+
842
+ function init(argv, cwd) {
843
+ if (argv[0] !== 'claude') throw new UsageError('Usage: harness-profiler init claude');
844
+ const repo = gitRoot(cwd);
845
+ if (!repo) throw new UsageError('Run harness-profiler init inside a git repository.');
846
+ const target = path.join(repo, HOOK_DIR);
847
+ fs.mkdirSync(target, { recursive: true });
848
+ for (const file of HOOK_FILES) fs.copyFileSync(path.join(__dirname, file), path.join(target, file));
849
+ fs.chmodSync(path.join(target, LAUNCHER), 0o755);
850
+ fs.rmSync(path.join(target, OLD_LAUNCHER), { force: true });
851
+ // Cloud sessions don't install plugins, so the skill that shows the trace
852
+ // goes into the repository's own skills.
853
+ const skill = path.join(repo, '.claude', SHOW_SKILL);
854
+ fs.mkdirSync(skill, { recursive: true });
855
+ fs.copyFileSync(path.join(__dirname, '..', SHOW_SKILL, 'SKILL.md'), path.join(skill, 'SKILL.md'));
856
+
857
+ const settingsFile = path.join(repo, '.claude', 'settings.json');
858
+ const settings = fs.existsSync(settingsFile) ? JSON.parse(fs.readFileSync(settingsFile, 'utf8')) : {};
859
+ fs.writeFileSync(settingsFile, JSON.stringify(mergeHooks(settings), null, 2) + '\n');
860
+ return [
861
+ `Copied the hook to ${path.relative(repo, target)}/, registered it in .claude/settings.json, and added the show-profile skill.`,
862
+ 'Commit them; Claude Code on the web picks the hook up in the next session:',
863
+ ' git add .claude/harness-profiler .claude/skills/show-profile .claude/settings.json',
864
+ ].join('\n');
865
+ }
866
+
867
+ // ---------- doctor ----------
868
+
869
+ function readJson(file) {
870
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return undefined; }
871
+ }
872
+
873
+ function hookSources(repo, home) {
874
+ const sources = [];
875
+ const installed = readJson(path.join(home, '.claude', 'plugins', 'installed_plugins.json'));
876
+ if (installed && JSON.stringify(installed.plugins || installed).includes('harness-profiler')) sources.push('plugin');
877
+ const settingsFiles = [
878
+ ['committed hooks', path.join(repo, '.claude', 'settings.json')],
879
+ ['local settings hooks', path.join(repo, '.claude', 'settings.local.json')],
880
+ ['user settings hooks', path.join(home, '.claude', 'settings.json')],
881
+ ];
882
+ for (const [label, file] of settingsFiles) {
883
+ const settings = readJson(file);
884
+ if (settings && JSON.stringify(settings.hooks || {}).includes('harness-profiler/hp')) sources.push(label);
885
+ }
886
+ return sources;
887
+ }
888
+
889
+ // What a hook committed by an older `init` lacks: events added since, `async`,
890
+ // and the files as this copy has them.
891
+ function staleHook(repo) {
892
+ const settings = readJson(path.join(repo, '.claude', 'settings.json'));
893
+ const hooks = (settings && settings.hooks) || {};
894
+ const ours = (event) => (hooks[event] || []).filter(isOurs).flatMap((e) => e.hooks.filter((h) => isOurCommand(h.command)));
895
+ if (!CAPTURED_EVENTS.some((event) => ours(event).length)) return undefined;
896
+ const missing = CAPTURED_EVENTS.filter((event) => !ours(event).length);
897
+ const blocking = CAPTURED_EVENTS.some((event) => ours(event).some((h) => h.async !== true));
898
+ const changed = HOOK_FILES.filter((file) => readText(path.join(repo, HOOK_DIR, file)) !== readText(path.join(__dirname, file)));
899
+ const gaps = [missing.length && `misses ${missing.join(', ')}`, blocking && 'is not async', changed.length && `has another version of ${changed.join(', ')}`].filter(Boolean);
900
+ return gaps.length ? gaps.join(' and ') : undefined;
901
+ }
902
+
903
+ function doctor(cwd, env = hookEnv(), home = os.homedir()) {
904
+ const dir = projectDir(cwd, env);
905
+ const sessions = listSessions(dir);
906
+ const newest = sessions.length ? Math.max(...sessions.map((s) => s.last)) : undefined;
907
+ const repo = gitRoot(cwd) || cwd;
908
+ const sources = hookSources(repo, home);
909
+ const stale = staleHook(repo);
910
+ return [
911
+ `node: ${process.execPath} (${process.version})`,
912
+ `traces: ${path.join(dir, TRACE_DIR)}`,
913
+ `hook: ${sources.length ? sources.join(', ') : 'not installed (install the plugin, or run harness-profiler init claude)'}`,
914
+ stale && `update: the committed hook ${stale}; run harness-profiler init claude again and commit`,
915
+ `newest: ${newest ? new Date(newest).toISOString() : 'no calls recorded yet'}`,
916
+ ].filter(Boolean).join('\n');
917
+ }
918
+
919
+ // ---------- entry point ----------
920
+
921
+ class UsageError extends Error {}
922
+
923
+ const USAGE = `Usage:
924
+ harness-profiler tree [session-id-prefix] [--branch <name>] [--verbose] [--format text|html]
925
+ harness-profiler init claude
926
+ harness-profiler doctor
927
+ harness-profiler capture <harness> (run by the hook, not by hand)`;
928
+
929
+ function readStdin() {
930
+ try { return fs.readFileSync(0, 'utf8'); } catch { return ''; }
931
+ }
932
+
933
+ function main(argv) {
934
+ const [command, ...rest] = argv;
935
+ if (command === 'capture') {
936
+ // A profiler must never break or slow down the session it watches, so no error leaves capture.
937
+ try { capture(rest[0] || 'unknown', readStdin()); } catch { /* see above */ }
938
+ return 0;
939
+ }
940
+ try {
941
+ switch (command) {
942
+ case 'tree': {
943
+ const color = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
944
+ console.log(tree(rest, projectDir(process.cwd()), { color }));
945
+ return 0;
946
+ }
947
+ case 'init': console.log(init(rest, process.cwd())); return 0;
948
+ case 'doctor': console.log(doctor(process.cwd())); return 0;
949
+ default: console.log(USAGE); return command ? 1 : 0;
950
+ }
951
+ } catch (error) {
952
+ if (!(error instanceof UsageError)) throw error;
953
+ console.error(error.message);
954
+ return 1;
955
+ }
956
+ }
957
+
958
+ if (require.main === module) process.exitCode = main(process.argv.slice(2));
959
+
960
+ module.exports = { fillContextTokens, contextSpend, spentTokens, buildRecord, buildEventRecord, capture, serialize, contextsOf, renderTree, renderHtml, buildForest, tree, mergeHooks, init, doctor, mask, HOOK_COMMAND, OLD_HOOK_COMMAND };