SLOPSHOPPER

workflow-watch

Live session and Workflow tracker: main-thread turns, skills fired, spawned subagents, git commits and workflow stages with models, effort, tokens and timeline…

panecommandprocesstimer
★ 13v0.4.2MITupdated 2026-10-25alonbaron/claude-skills/mods/workflow-watch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · workflow-watch
│ ┃ Tracker ✕ › fix the failing auth test and add an audit log call │ ┃ ╭────────────────────────────────────────╮ │ ┃ │ Waiting for session activity. Turns, │ ⏺ Read(src/auth.ts) │ ┃ │ skills, subagents, commits and │ ⎿ Read 6 lines │ ┃ │ Workflow stages appear here live. │ ⏺ Update(src/auth.ts) │ ┃ ╰────────────────────────────────────────╯ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /workflow-watch │ ⎿ workflow-watch: No session or workflow activity recorded yet; se │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Tracker
╭────────────────────────────────────────────────────────╮ │ Waiting for session activity. Turns, skills, │ │ subagents, commits and Workflow stages appear here │ │ live. │ ╰────────────────────────────────────────────────────────╯
README

workflow-watch

A mod (a plugin of function hooks) that opens with every session and tracks everything happening live: main-thread turns (turn:N), skills fired (skill:<name>), spawned subagents (agent:<description>), git commits (commit:<sha>), and Workflow stages (plan, scout, spec, build, measure, refute, arbiter, fix, close). It draws only the Tracker pane beside the chat and writes nothing into the conversation: it adds no band above the prompt, status line entry, toast or log line. /tracker (or /workflow-watch) opens the pane and prints the same report as text, which is all the mobile app shows.

In VS Code and the desktop app, every part of the pane is a rounded card. A button at the top right switches the cards between a dark and a light theme, whatever the system theme is. Under it sits the header card with the run name, the output token total and one pill per count (green done, amber running or disputed, red failed). When two or more items are present, the timeline card follows, with the last ten items' spans drawn as rounded bars on the session's shared clock. Bars take their item's kind color: orange turns, violet skills, teal subagents, blue commits, pink Workflow stages. The button above the timeline folds it away (− Timeline) or opens it again (+ Timeline · 22:03 elapsed). The theme and the fold are both saved, so a new session opens the way you left it.

The pane also sizes itself. While anything runs it shows every card. After 20 seconds with nothing running it folds to one strip with the run name, its counts, and the item that finished last (or the newest one running). − Minimize and + Expand, beside the theme button, override that until the session next starts or stops working. ✕ Hide closes the pane, and it opens again by itself when the next turn or run starts. /tracker opens it at full size. The terminal folds the same way, without the buttons.

Under that, each item gets its own card, newest first, so the latest work sits just below the timeline and older work further down. The pane scrolls by itself in VS Code and ignores a plugin's request to scroll, so this order keeps the live work in view without following the end. The phase name (Turn N, Skill · <name>, or the Workflow phase) sits above its cards as a pill in the color of the item that opened the phase. A card shows:

  • a round avatar in the kind color, lettered T, S, A, C or W;
  • the item label, the model alias and the id it resolved to, and the effort level;
  • a state pill: ▶ running, ✓ done, ! failed, ! disputed (a fix round that left findings for the arbiter) or ✗ no result (a stage that returned nothing, or died before returning, say on a session limit);
  • for a turn, your prompt on an orange › line. A message you send while Claude works shows there as (mid-turn) … and opens no new turn;
  • the one-line result: Claude's latest words for a turn ((interrupted) in front when you stopped it), and for a background subagent the text extracted from SubagentHandback, which isn't counted as a tool call;
  • the details: Ran for 0:46 · 5 tools · 0.8k tokens, or Running for 0:12 · 3 calls · Bash npm test.

A running card is outlined in amber, a finished one in gray. The terminal can't draw these cards, so it shows the same items in box glyphs and follows its own theme colors.

It reads Claude Code's files under ~/.claude/projects/<project>/ every two seconds: <session>.jsonl for main-thread turns, skills, agent spawns and commits, <session>/subagents/agent-<id>.{meta.json,jsonl} for spawned subagents, and <session>/subagents/workflows/<run>/journal.jsonl (plus its agent-<id> files) for Workflow runs. [Request interrupted by user] is the engine's marker, not a prompt, so it ends the turn rather than opening one. A plugin reads at most 4 MiB at a time, and a long session with pasted screenshots goes past that. Past 4 MiB, the log is read through a filter that keeps every line valid JSON. It drops the engine's bookkeeping lines (copies of API requests, titles, bridge state), empties the base64 data of pasted images, and cuts any string past 2,000 characters, so a 10 to 12 MiB log comes to 1 or 2 MiB and parses to the same items. Windows PowerShell runs the filter on Windows, called by its full path, and perl everywhere else, including the 5.34 that macOS ships as /usr/bin/perl. The patterns and sizes reach it as environment variables, never as part of its script, and so does the log's path for PowerShell (perl gets it as its file argument). A file is filtered again only when its size changes, and a failed run is not retried until then. If a log still can't be read, the pane keeps the items it last found and says so above them. A very long session can still be over 3.5 MiB after filtering; on the logs measured, that took more than 30 MB of log. Then only its newest whole lines are kept and the pane says so. The earliest turns drop out of the cards and the header counts, and turn numbers start again from the oldest turn kept. On Windows inside the VS Code extension host (where HOME is unset), it resolves the user directory from USERPROFILE. It also parses Antigravity extension transcripts (~/.gemini/antigravity/brain/<id>/.system_generated/logs/transcript.jsonl or transcript_full.jsonl) and links spawned subagent conversations automatically.

Install with the marketplace (/plugin install workflow-watch@alonbaron) or load it for one session with claude --plugin-dir <this folder>. Works both in the terminal CLI and inside the VS Code Claude Code and Antigravity extensions. The pane needs a terminal of 144 columns, or /tracker (/workflow-watch) to seat it narrower. scripts/tracker.mjs renders the same session or workflow feed to HTML or PNG from outside a session with auto-reload for VS Code Simple Browser or Live Preview (--watch).

Check it: claude plugin validate mods/workflow-watch, claude plugin test mods/workflow-watch, tsc -p mods/workflow-watch once a session has laid the types beside it. node mods/workflow-watch/tests/slim-check.mjs [--perl <path>] [log.jsonl ...] (Node 24) runs the real filter through this machine's PowerShell or perl on generated logs (one under the 3.5 MiB tail, one far past it, one with a 90,000-escape string and an unfinished last line) and on any logs you name. The tracker-slim CI job runs it on macOS (every perl in /usr/bin), Ubuntu and Windows.

Source 4 files
hooks/register.tsx 499 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { PaneView, Stage, Theme, Watch } from '../types'
5import { KIND_FILL, PANE_BG, compactCard, headerCard, phaseChip, stageCard, timelineCard } from './cards'
6import { EMPTY, READ_LIMIT, SLIM_CUT, SLIM_TIMEOUT_MS, applyEntries, elapsed, mergeStages, parseLines, parseSession, phaseRuns, phaseTitle, readMeta, readMetaInfo, readTranscript, report, slimCommand, stageDetail, stageResult, state, tally, timelineBar, tone, who, withFacts } from './journal'
7
8const PANE = 'workflow-watch'
9const TITLE = 'Tracker'
10const watch = atom({ plugin: 'workflow-watch', key: 'watch' } as const, EMPTY)
11const theme = atom({ plugin: 'workflow-watch', key: 'theme' } as const, 'dark' as Theme)
12const isTimelineOpen = atom({ plugin: 'workflow-watch', key: 'isTimelineOpen' } as const, true)
13const pinnedView = atom({ plugin: 'workflow-watch', key: 'pinnedView' } as const, null as PaneView | null)
14
15/** How long nothing has to run before the pane folds to its compact strip. */
16export const IDLE_MS = 20000
17
18/** The item the compact strip shows: the newest one running, else the one that finished last. */
19const latestOf = (stages: Stage[]): Stage | undefined =>
20  [...stages].reverse().find(s => s.endedAt === null) ?? stages.reduce<Stage | undefined>((m, s) => (!m || (s.endedAt ?? 0) > (m.endedAt ?? 0) ? s : m), undefined)
21
22type Engine = Parameters<Parameters<Register>[0]>[2] extends (...a: infer A) => unknown ? A[0] : never
23type Listing = Awaited<ReturnType<Engine['fs']['list']>>
24
25const listOr = async ($: Engine, path: string): Promise<Listing> => {
26  try {
27    return await $.fs.list(path)
28  } catch {
29    return []
30  }
31}
32
33type Target = {
34  sid: string
35  sessionPath: string | null
36  subagentsDir: string | null
37  wf: { dir: string; path: string; run: string } | null
38}
39
40/** Finds this session's main transcript (<sid>.jsonl or Antigravity transcript.jsonl), subagents directory, and newest Workflow journal.jsonl. */
41async function findTarget($: Engine): Promise<Target | null> {
42  const rawHome = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
43  if (!rawHome) return null
44  const home = rawHome.replace(/\\/g, '/')
45  const sid = await $.session.id()
46  const projects = `${home}/.claude/projects`
47  let sessionPath: string | null = null
48  let subagentsDir: string | null = null
49  let bestWf: { dir: string; run: string; mtime: number } | null = null
50
51  for (const d of await listOr($, projects)) {
52    if (d.kind !== 'dir') continue
53    const projDir = `${projects}/${d.name}`
54    const candidateSession = `${projDir}/${sid}.jsonl`
55    if (!sessionPath && (await $.fs.exists(candidateSession))) {
56      sessionPath = candidateSession
57      const sub = `${projDir}/${sid}/subagents`
58      if (await $.fs.exists(sub)) subagentsDir = sub
59    }
60    const wf = `${projDir}/${sid}/subagents/workflows`
61    if (await $.fs.exists(wf)) {
62      if (!subagentsDir) subagentsDir = `${projDir}/${sid}/subagents`
63      for (const r of await listOr($, wf)) {
64        if (r.kind !== 'dir') continue
65        const j = (await listOr($, `${wf}/${r.name}`)).find(f => f.name === 'journal.jsonl')
66        if (j && (!bestWf || j.mtimeMs > bestWf.mtime)) bestWf = { dir: `${wf}/${r.name}`, run: r.name, mtime: j.mtimeMs }
67      }
68    }
69    if (sessionPath || bestWf) break
70  }
71
72  if (!sessionPath && !bestWf) {
73    const agyBrain = `${home}/.gemini/antigravity/brain`
74    const agyTranscript = `${agyBrain}/${sid}/.system_generated/logs/transcript.jsonl`
75    if (await $.fs.exists(agyTranscript)) {
76      sessionPath = agyTranscript
77      subagentsDir = agyBrain
78    }
79  }
80
81  const wf = bestWf ? { dir: bestWf.dir, path: `${bestWf.dir}/journal.jsonl`, run: bestWf.run } : null
82  if (!sessionPath && !wf) return null
83  return { sid, sessionPath, subagentsDir, wf }
84}
85
86const VALID_ID = /^[a-zA-Z0-9_-]+$/
87
88/** The theme color for each tally word; a zero count is drawn subtle whatever its word. */
89const TALLY_TONE: Record<string, string> = { done: 'success', disputed: 'warning', failed: 'error', running: 'warning' }
90
91const INK = '#111111'
92const fill = (s: Stage | undefined): string => KIND_FILL[s?.kind ?? 'stage']
93
94/** A timeline bar as its track and span pieces, so the track can be drawn quieter than the span. */
95const barParts = (bar: string): Array<[string, boolean]> =>
96  (bar.match(/░+|[█▓]+/g) ?? []).map(part => [part, part[0] !== '░'])
97
98/**
99 * Antigravity writes a compact transcript.jsonl (long tool args truncated) and an untruncated
100 * transcript_full.jsonl beside it: read the full one when it exists and fits, else the compact one.
101 */
102async function readTranscriptText($: Engine, path: string): Promise<string> {
103  if (path.endsWith('/transcript.jsonl')) {
104    const full = path.replace(/transcript\.jsonl$/, 'transcript_full.jsonl')
105    try {
106      if (await $.fs.exists(full)) return await $.fs.read(full)
107    } catch {
108      /* over the read limit: fall back to the compact transcript */
109    }
110  }
111  const { size } = await $.fs.stat(path)
112  return size > READ_LIMIT ? readSlimmed($, path, size) : $.fs.read(path)
113}
114
115/** Each slimmed log's last result by path until its size changes; a failure (null) too, so it isn't respawned every tick. */
116const slimmed = new Map<string, { size: number; text: string | null }>()
117
118/**
119 * A session log over the read limit, read through the SLIM filter (journal.ts): the engine's bookkeeping lines,
120 * pasted images' base64 and the tails of long strings go, every line stays valid JSON, and a 10 MiB log comes to
121 * about 1 MiB. A log still past SLIM_TAIL after that keeps only its newest whole lines, behind a SLIM_CUT line.
122 * Windows PowerShell by its full path on Windows, perl elsewhere (slimCommand); rerun only when the file's size changed.
123 */
124async function readSlimmed($: Engine, path: string, size: number): Promise<string> {
125  const known = slimmed.get(path)
126  if (known?.size === size) {
127    if (known.text === null) throw new Error('slimmed read failed at this size')
128    return known.text
129  }
130  const { argv, env } = slimCommand(path, await $.env.get('SystemRoot'))
131  const out = await $.process.run(argv, { env, timeoutMs: SLIM_TIMEOUT_MS }).catch(() => null)
132  const text = out && out.exitCode === 0 && !out.isStdoutTruncated && out.stdout.length > 0 ? out.stdout : null
133  if (slimmed.size > 16) slimmed.clear()
134  slimmed.set(path, { size, text })
135  if (text === null) throw new Error(`slimmed read failed: ${out?.stderr.slice(0, 200) ?? 'did not start'}`)
136  return text
137}
138
139/** Model, effort, tokens and tool calls from the stage's own transcript; a finished stage is read once more, then left alone. */
140async function enrich($: Engine, dir: string, s: Stage): Promise<Stage> {
141  if (!s.agentId || !VALID_ID.test(s.agentId) || s.isSettled) return s
142  let next = s
143  if (next.alias === null) {
144    try {
145      next = { ...next, alias: readMeta(await $.fs.read(`${dir}/agent-${s.agentId}.meta.json`)) }
146    } catch {
147      /* not written yet */
148    }
149  }
150  try {
151    const claudePath = `${dir}/agent-${s.agentId}.jsonl`
152    const agyPath = `${dir}/${s.agentId}/.system_generated/logs/transcript.jsonl`
153    const path = (await $.fs.exists(claudePath)) ? claudePath : agyPath
154    next = withFacts(next, readTranscript(await readTranscriptText($, path)))
155  } catch {
156    /* not written yet, or over the read limit: keep what we have */
157  }
158  return next.endedAt !== null ? { ...next, isSettled: true } : next
159}
160
161/** Links any live session Agent call whose tool_result has not returned an agentId yet by scanning agent-*.meta.json. */
162async function linkSessionAgents($: Engine, subagentsDir: string, stages: Stage[]): Promise<void> {
163  const unlinked = stages.filter(s => s.kind === 'agent' && !s.agentId && s.endedAt === null)
164  if (unlinked.length === 0) return
165  for (const f of await listOr($, subagentsDir)) {
166    if (f.kind !== 'file' || !f.name.startsWith('agent-') || !f.name.endsWith('.meta.json')) continue
167    const aid = f.name.slice('agent-'.length, -'.meta.json'.length)
168    if (!VALID_ID.test(aid)) continue
169    try {
170      const info = readMetaInfo(await $.fs.read(`${subagentsDir}/${f.name}`))
171      if (!info.toolUseId) continue
172      const match = unlinked.find(s => s.key === `agent:${info.toolUseId}`)
173      if (match) {
174        match.agentId = aid
175        if (!match.alias && info.model) match.alias = info.model
176      }
177    } catch {
178      /* ignore unreadable meta */
179    }
180  }
181}
182
183/** Opens the pane unless it is already up. The pane is the only view; nothing is written to the chat. */
184async function openPane($: Engine): Promise<void> {
185  const isUp = (await $.ui.panes()).some(p => p.id === PANE)
186  if (!isUp) await $.ui.open({ id: PANE, title: TITLE })
187}
188
189async function tick($: Engine): Promise<void> {
190  const target = await findTarget($)
191  if (!target) return
192  const now = await $.clock.now()
193  const journalKey = [target.sessionPath, target.wf?.path].filter(Boolean).join('+')
194  const prev = await read($, watch)
195  const sameRun = prev.journal === journalKey
196  const base = sameRun ? prev.stages : []
197  const prevByKey = new Map(base.map(s => [s.key, s]))
198
199  // A log that cannot be read this tick keeps what the last read found, and the pane says so instead of blanking.
200  let sessionStages: Stage[] = base.filter(s => s.kind && s.kind !== 'stage')
201  let unread: string | null = null
202  let isCut = false
203  if (target.sessionPath) {
204    try {
205      const text = await readTranscriptText($, target.sessionPath)
206      isCut = text.startsWith(SLIM_CUT)
207      const raw = parseSession(text, now)
208      for (const s of raw) if (s.kind === 'agent') s.agentId ??= prevByKey.get(s.key)?.agentId ?? null
209      if (target.subagentsDir) await linkSessionAgents($, target.subagentsDir, raw)
210      const fresh: Stage[] = []
211      for (const s of raw) {
212        if (s.kind === 'agent' && target.subagentsDir) {
213          const known = prevByKey.get(s.key)
214          if (known?.isSettled) {
215            fresh.push({ ...known, summary: known.summary ?? s.summary, endedAt: known.endedAt ?? s.endedAt })
216          } else {
217            const merged = known
218              ? { ...s, agentId: s.agentId ?? known.agentId, alias: s.alias ?? known.alias, model: s.model ?? known.model, effort: s.effort ?? known.effort, outputTokens: known.outputTokens, calls: known.calls, lastTool: known.lastTool }
219              : s
220            fresh.push(await enrich($, target.subagentsDir, merged))
221          }
222        } else {
223          fresh.push(s)
224        }
225      }
226      sessionStages = fresh
227    } catch {
228      unread = 'the session log'
229    }
230  }
231
232  let wfStages: Stage[] = base.filter(s => !s.kind || s.kind === 'stage')
233  if (target.wf) {
234    try {
235      const text = await $.fs.read(target.wf.path)
236      const fresh: Stage[] = []
237      for (const s of applyEntries(wfStages, parseLines(text), now)) fresh.push(await enrich($, target.wf.dir, s))
238      wfStages = fresh
239    } catch {
240      unread = unread ? 'the session log and the workflow journal' : 'the workflow journal'
241    }
242  }
243
244  const stages = mergeStages(sessionStages, wfStages)
245  const run = target.wf && sessionStages.length === 0 ? target.wf.run : target.wf ? `${target.sid.slice(0, 8)} · ${target.wf.run}` : `session ${target.sid.slice(0, 8)}`
246  const notice = unread
247    ? `Could not read ${unread}; showing what was last read.`
248    : isCut
249      ? 'This session’s log is too long to read in full, so only its most recent part is shown. Turn numbers start from there.'
250      : null
251  const isBusy = stages.some(s => s.endedAt === null)
252  const lastEnd = stages.reduce((m, s) => Math.max(m, s.endedAt ?? 0), 0)
253  const isIdle = stages.length > 0 && !isBusy && now - lastEnd >= IDLE_MS
254  const next: Watch = { journal: journalKey, run, stages, now, notice, isIdle }
255  // A pane the person hid comes back when work starts again: a new run, or the first item running after a quiet spell.
256  const isWaking = isBusy && !prev.stages.some(s => s.endedAt === null)
257  if (stages.length && (!sameRun || isWaking)) void openPane($)
258  // A Minimize or Expand press holds until the session next turns busy or idle; then the pane sizes itself again.
259  if (!sameRun || Boolean(prev.isIdle) !== isIdle) await update($, pinnedView, () => null)
260
261  const changed = !sameRun || prev.notice !== notice || Boolean(prev.isIdle) !== isIdle || JSON.stringify(prev.stages) !== JSON.stringify(stages) || isBusy
262  if (changed) await update($, watch, () => next)
263}
264
265/** One tick at a time: a slow read (a slimmed log, many transcripts) skips the ticks that come due meanwhile. */
266let isTicking = false
267async function tickOnce($: Engine): Promise<void> {
268  if (isTicking) return
269  isTicking = true
270  try {
271    await tick($)
272  } finally {
273    isTicking = false
274  }
275}
276
277async function runCommand($: Engine): Promise<{ text: string }> {
278  let w = await read($, watch)
279  if (!w.run || w.stages.length === 0) {
280    await tickOnce($)
281    w = await read($, watch)
282  }
283  const opened = await $.ui.open({ id: PANE, title: TITLE })
284  await update($, pinnedView, () => 'full')
285  if (!w.run || w.stages.length === 0) return { text: 'No session or workflow activity recorded yet; send a prompt or start a Workflow, then type /tracker again.' }
286  const where = opened.isPlaced ? 'pane open' : 'no pane on this surface; this text is the view, type /tracker again for a fresh one'
287  return { text: `${report(w)}\n(${where})` }
288}
289
290export const register: Register = on => {
291  on('session.start', async ($, e, next) => {
292    const description = 'Live session & workflow tracker: turns, skills, subagents, commits and stages with models, effort, tokens and timeline'
293    await $.command.register({ name: 'workflow-watch', description })
294    await $.command.register({ name: 'tracker', description })
295    const saved = await $.store.get('theme').catch(() => undefined)
296    if (saved === 'dark' || saved === 'light') await update($, theme, () => saved)
297    const savedOpen = await $.store.get('isTimelineOpen').catch(() => undefined)
298    if (typeof savedOpen === 'boolean') await update($, isTimelineOpen, () => savedOpen)
299    $.clock.every(2000, () => void tickOnce($))
300    void openPane($)
301    void tickOnce($)
302    return next(e)
303  })
304
305  // Not every surface seats the pane; the text report below is what every surface can show, so it carries the whole picture.
306  on('command.run', { command: 'workflow-watch' }, async $ => runCommand($))
307  on('command.run', { command: 'tracker' }, async $ => runCommand($))
308
309  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
310    const elements = $.ui.resolve(e)
311    const { Box, Text, Button } = elements
312    const Svg = e.surface !== 'terminal' && 'Svg' in elements ? elements.Svg : null
313    const w = await read($, watch)
314    const notice = w.notice ? (
315      <Text color="warning" wrap="wrap">
316        {w.notice}
317      </Text>
318    ) : null
319    if (!w.run || w.stages.length === 0) {
320      return (
321        <Box flexDirection="column" paddingX={1}>
322          <Box borderStyle="round" borderColor="claude" paddingX={1}>
323            <Text color="subtle">Waiting for session activity. Turns, skills, subagents, commits and Workflow stages appear here live.</Text>
324          </Box>
325          {notice}
326        </Box>
327      )
328    }
329    const tokens = w.stages.reduce((n, s) => n + s.outputTokens, 0)
330    const t0 = w.stages.reduce((m, s) => Math.min(m, s.startedAt), Infinity)
331    const t1 = w.stages.reduce((m, s) => Math.max(m, s.endedAt ?? w.now), -Infinity)
332    const total = Math.max(1, t1 - t0)
333    // Newest first: the latest work sits under the header with no scrolling, history further down.
334    // (The editor's pane scrolls by itself and leaves $.ui.scroll unapplied, so following the end is not an option there.)
335    // Phases are cut in run order, so each chip keeps its opener's kind and round; then groups and members are reversed.
336    const groups = phaseRuns(w.stages).reverse()
337    const newestOf = (g: { stages: Stage[] }): Stage[] => [...g.stages].reverse()
338    // Idle, the pane folds to one strip (the run, its counts, the latest item); busy, it opens to every card. A press overrides either.
339    const pinned = await read($, pinnedView)
340    const isCompact = pinned ? pinned === 'compact' : Boolean(w.isIdle)
341    const latest = latestOf(w.stages) as Stage
342    // A header card, a timeline card (when 2+ items exist), then one card per stage, newest first, under a colored phase chip.
343    // A surface with Svg (desktop, vscode, mobile) draws each card as a rounded vector card; the terminal draws them in box glyphs.
344    if (Svg) {
345      const mode = await read($, theme)
346      const isOpen = await read($, isTimelineOpen)
347      const head = headerCard(w, tokens, mode)
348      const tl = timelineCard(w.stages, t0, total, w.now, mode)
349      const bar = (
350        <Box justifyContent="flex-end" gap={1} marginBottom={1}>
351          <Button key="size" label={isCompact ? '+ Expand' : '− Minimize'} onPress={() => void update($, pinnedView, () => (isCompact ? 'full' : 'compact')).catch(() => undefined)} />
352          <Button
353            key="theme"
354            label={mode === 'dark' ? '☀ Light mode' : '☾ Dark mode'}
355            onPress={() => {
356              void update($, theme, m => (m === 'dark' ? 'light' : 'dark'))
357                .then(m => $.store.set('theme', m))
358                .catch(() => undefined)
359            }}
360          />
361          <Button key="hide" label="✕ Hide" onPress={() => void $.ui.close({ id: PANE }).catch(() => undefined)} />
362        </Box>
363      )
364      if (isCompact) {
365        const c = compactCard(w, latest, w.now, mode)
366        return (
367          <Box flexDirection="column" paddingX={1} paddingY={1} backgroundColor={PANE_BG[mode]}>
368            {bar}
369            {notice}
370            <Svg source={c.source} alt={c.alt} width={c.width} height={c.height} />
371          </Box>
372        )
373      }
374      return (
375        <Box flexDirection="column" paddingX={1} paddingY={1} backgroundColor={PANE_BG[mode]}>
376          {bar}
377          {notice}
378          <Svg source={head.source} alt={head.alt} width={head.width} height={head.height} />
379          {w.stages.length > 1 && (
380            <Box flexDirection="column" marginTop={1}>
381              <Box>
382                <Button
383                  key="timeline"
384                  label={isOpen ? '− Timeline' : `+ Timeline · ${elapsed(total)} elapsed`}
385                  onPress={() => {
386                    void update($, isTimelineOpen, open => !open)
387                      .then(open => $.store.set('isTimelineOpen', open))
388                      .catch(() => undefined)
389                  }}
390                />
391              </Box>
392              {isOpen && (
393                <Box marginTop={1}>
394                  <Svg source={tl.source} alt={tl.alt} width={tl.width} height={tl.height} />
395                </Box>
396              )}
397            </Box>
398          )}
399          {groups.map((g, i) => {
400            const chip = phaseChip(g, mode)
401            return (
402              <Box key={`phase-${i}`} flexDirection="column" marginTop={1}>
403                <Svg source={chip.source} alt={chip.alt} width={chip.width} height={chip.height} />
404                {newestOf(g).map(s => {
405                  const c = stageCard(s, w.now, mode)
406                  return (
407                    <Box key={s.key} marginTop={1}>
408                      <Svg source={c.source} alt={c.alt} width={c.width} height={c.height} />
409                    </Box>
410                  )
411                })}
412              </Box>
413            )
414          })}
415        </Box>
416      )
417    }
418    return (
419      <Box flexDirection="column" paddingX={1}>
420        {notice}
421        <Box flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
422          <Text bold color="claude" wrap="truncate-end">
423            {w.run}
424          </Text>
425          <Text wrap="truncate-end">
426            {tally(w)
427              .split(' · ')
428              .map((part, i) => (
429                <Text key={part}>
430                  {i > 0 ? ' ' : ''}
431                  {/^0 /.test(part) ? (
432                    <Text color="subtle">{` ${part} `}</Text>
433                  ) : (
434                    <Text bold backgroundColor={TALLY_TONE[part.split(' ')[1] ?? ''] ?? 'text'} color="inverseText">{` ${part} `}</Text>
435                  )}
436                </Text>
437              ))}
438            <Text color="subtle">{`  ${(tokens / 1000).toFixed(1)}k output tokens`}</Text>
439          </Text>
440          {isCompact && (
441            <Text wrap="truncate-end">
442              <Text bold backgroundColor={tone(latest)} color="inverseText">{` ${state(latest)} `}</Text>
443              {`  ${latest.label} `}
444              <Text color="subtle">{`(${elapsed((latest.endedAt ?? w.now) - latest.startedAt)})`}</Text>
445            </Text>
446          )}
447        </Box>
448        {!isCompact && w.stages.length > 1 && (
449          <Box flexDirection="column" borderStyle="round" borderColor="subtle" paddingX={1} marginTop={1}>
450            <Text bold color="claude" wrap="truncate-end">
451              {`Timeline · ${elapsed(total)} elapsed`}
452            </Text>
453            {w.stages.slice(-10).map(s => (
454              <Text key={`tl-${s.key}`} wrap="truncate-end">
455                {barParts(timelineBar(s, t0, total, 14)).map(([part, isSpan], j) => (
456                  <Text key={j} color={isSpan ? fill(s) : 'subtle'}>
457                    {part}
458                  </Text>
459                ))}
460                {`  ${s.label} `}
461                <Text color="subtle">{`(${elapsed((s.endedAt ?? w.now) - s.startedAt)})`}</Text>
462              </Text>
463            ))}
464          </Box>
465        )}
466        {!isCompact && groups.map((g, i) => (
467          <Box key={`phase-${i}`} flexDirection="column" marginTop={1}>
468            <Text wrap="truncate-end">
469              <Text bold backgroundColor={fill(g.stages[0])} color={INK}>{` ${phaseTitle(g)} `}</Text>
470            </Text>
471            {newestOf(g).map(s => (
472              <Box key={s.key} flexDirection="column" borderStyle="round" borderColor={s.endedAt === null ? tone(s) : 'subtle'} paddingX={1}>
473                <Text wrap="truncate-end">
474                  <Text bold backgroundColor={tone(s)} color="inverseText">{` ${state(s)} `}</Text>
475                  <Text bold>{`  ${s.label}`}</Text>
476                  <Text color="permission">{`  ${who(s)}`}</Text>
477                </Text>
478                {s.prompt && (
479                  <Text color="claude" wrap="truncate-end">
480                    {`› ${s.prompt}`}
481                  </Text>
482                )}
483                {s.endedAt === null ? (
484                  <Text color="subtle" italic wrap="truncate-end">{stageResult(s)}</Text>
485                ) : (
486                  <Text wrap="truncate-end">{stageResult(s)}</Text>
487                )}
488                <Text color="subtle" wrap="truncate-end">
489                  {stageDetail(s, w.now)}
490                </Text>
491              </Box>
492            ))}
493          </Box>
494        ))}
495      </Box>
496    )
497  })
498}
499
hooks/cards.ts 134 lines
1import type { Stage, StageKind, Theme, Watch } from '../types'
2import { elapsed, phaseTitle, stageDetail, stageResult, state, tally, timelineBar, tone, who } from './journal'
3
4/** Card markup for the graphical surfaces (desktop, vscode, mobile): rounded cards, round kind avatars, pill badges. */
5export type Card = { source: string; alt: string; width: number; height: number }
6
7export const W = 440
8const FONT = `font-family="Segoe UI, -apple-system, system-ui, sans-serif"`
9
10/** One fill per kind of item, the same as the terminal chips, read in dark ink. */
11export const KIND_FILL: Record<StageKind, string> = { turn: '#FB923C', skill: '#A78BFA', agent: '#2DD4BF', commit: '#60A5FA', stage: '#F472B6' }
12const KIND_LETTER: Record<StageKind, string> = { turn: 'T', skill: 'S', agent: 'A', commit: 'C', stage: 'W' }
13const kindOf = (s: Stage | undefined): StageKind => s?.kind ?? 'stage'
14
15// The pane's toggle picks the theme, whatever the system's: both name the same classes.
16const PILLS = `.ink{fill:#111}.pill-success{fill:rgba(52,199,89,.18)}.pill-warning{fill:rgba(245,176,65,.18)}.pill-error{fill:rgba(239,68,68,.18)}.pill-subtle{fill:rgba(154,156,161,.14)}`
17const STYLE: Record<Theme, string> = {
18  dark: `<style>${PILLS}.card{fill:#202124;stroke:#2f3033}.live{stroke:#f5b041}.t{fill:#ececec}.m{fill:#9a9ca1}.p{fill:#f0a35e}.who{fill:#8ab4f8}.track{fill:#2c2d31}.tx-success{fill:#5ee38a}.tx-warning{fill:#f7c35c}.tx-error{fill:#f87171}.tx-subtle{fill:#9a9ca1}</style>`,
19  light: `<style>${PILLS}.card{fill:#fff;stroke:#e7e7ea}.live{stroke:#d97706}.t{fill:#1a1a1a}.m{fill:#6b6d72}.p{fill:#c2560c}.who{fill:#1d4ed8}.track{fill:#efeff2}.tx-success{fill:#15803d}.tx-warning{fill:#b45309}.tx-error{fill:#b91c1c}.tx-subtle{fill:#6b6d72}</style>`,
20}
21
22/** The pane's own background under the cards in each theme. */
23export const PANE_BG: Record<Theme, string> = { dark: '#181818', light: '#f3f3f5' }
24
25const esc = (v: string): string => v.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)
26/** Cuts a line to what fits in `px` at `size`, estimating an average glyph at 0.5em. */
27const fit = (v: string, px: number, size: number): string => {
28  const n = Math.max(1, Math.floor(px / (size * 0.5)))
29  return v.length <= n ? v : `${v.slice(0, n - 1)}…`
30}
31const textW = (v: string, size: number): number => Math.ceil(v.length * size * 0.5)
32const svg = (h: number, body: string, theme: Theme): string =>
33  `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${h}" width="${W}" height="${h}" ${FONT}>${STYLE[theme]}${body}</svg>`
34const frame = (h: number, cls = 'card'): string => `<rect class="${cls}" x="0.5" y="0.5" width="${W - 1}" height="${h - 1}" rx="16" stroke-width="1"/>`
35
36/** The run's name, the token total, and one pill per count, each with its number in a badge. */
37export function headerCard(w: Watch, tokens: number, theme: Theme): Card {
38  const h = 92
39  const toks = `${(tokens / 1000).toFixed(1)}k output tokens`
40  let x = 18
41  const pills = tally(w)
42    .split(' · ')
43    .map(part => {
44      const [count = '0', word = ''] = part.split(' ')
45      const t = count === '0' ? 'subtle' : word === 'done' ? 'success' : word === 'failed' ? 'error' : 'warning'
46      const pw = 30 + textW(word, 12) + 14
47      const out = `<rect class="pill-${t}" x="${x}" y="50" width="${pw}" height="28" rx="14"/><rect class="pill-${t}" x="${x + 4}" y="54" width="22" height="20" rx="10"/><text class="tx-${t}" x="${x + 15}" y="68" font-size="12" font-weight="700" text-anchor="middle">${esc(count)}</text><text class="tx-${t}" x="${x + 32}" y="68" font-size="12" font-weight="600">${esc(word)}</text>`
48      x += pw + 8
49      return out
50    })
51    .join('')
52  const body = `${frame(h)}<text class="p" x="18" y="32" font-size="17" font-weight="700">${esc(fit(w.run ?? '', W - 36 - textW(toks, 12) - 12, 17))}</text><text class="m" x="${W - 18}" y="31" font-size="12" text-anchor="end">${esc(toks)}</text>${pills}`
53  return { source: svg(h, body, theme), alt: `${w.run}: ${tally(w)} · ${toks}`, width: W, height: h }
54}
55
56/** The minimized pane: the run's name and counts, then the live item (or the last one) on one row with its state pill. */
57export function compactCard(w: Watch, latest: Stage, now: number, theme: Theme): Card {
58  const h = 96
59  const counts = tally(w)
60    .split(' · ')
61    .filter(part => !/^0 /.test(part) || part.endsWith('running'))
62    .join(' · ')
63  const t = tone(latest)
64  const st = state(latest)
65  const pw = textW(st, 12) + 22
66  const detail = elapsed((latest.endedAt ?? now) - latest.startedAt)
67  const label = fit(latest.label, W - 92 - pw - textW(detail, 12) - 24, 13)
68  const body =
69    frame(h, latest.endedAt === null ? 'card live' : 'card') +
70    `<text class="p" x="18" y="30" font-size="15" font-weight="700">${esc(fit(w.run ?? '', W - 36 - textW(counts, 12) - 12, 15))}</text>` +
71    `<text class="m" x="${W - 18}" y="30" font-size="12" text-anchor="end">${esc(counts)}</text>` +
72    `<rect class="track" x="10" y="46" width="${W - 20}" height="40" rx="12"/>` +
73    `<circle cx="34" cy="66" r="12" fill="${KIND_FILL[kindOf(latest)]}"/><text class="ink" x="34" y="70.5" font-size="11" font-weight="700" text-anchor="middle">${KIND_LETTER[kindOf(latest)]}</text>` +
74    `<text class="t" x="56" y="71" font-size="13" font-weight="600">${esc(label)}</text>` +
75    `<text class="m" x="${W - 28 - pw}" y="71" font-size="12" text-anchor="end">${esc(detail)}</text>` +
76    `<rect class="pill-${t}" x="${W - 20 - pw}" y="54" width="${pw}" height="24" rx="12"/><text class="tx-${t}" x="${W - 20 - pw / 2}" y="70" font-size="12" font-weight="700" text-anchor="middle">${esc(st)}</text>`
77  return { source: svg(h, body, theme), alt: `${w.run}: ${counts} | ${st} ${latest.label} ${detail}`, width: W, height: h }
78}
79
80/** Each item's span on the shared clock as a rounded bar in its kind color, on a soft track. */
81export function timelineCard(stages: Stage[], t0: number, total: number, now: number, theme: Theme): Card {
82  const rows = stages.slice(-10)
83  const h = 50 + rows.length * 24 + 8
84  const tx = 132
85  const tw = W - tx - 62
86  const body = rows
87    .map((s, i) => {
88      const y = 50 + i * 24
89      const bar = timelineBar(s, t0, total, 40)
90      const start = bar.indexOf(bar.match(/[█▓]/)?.[0] ?? '█')
91      const len = (bar.match(/[█▓]+/)?.[0] ?? '█').length
92      const bx = tx + (start / 40) * tw
93      const bw = Math.max(8, (len / 40) * tw)
94      const dur = elapsed((s.endedAt ?? now) - s.startedAt)
95      return `<text class="t" x="18" y="${y + 13}" font-size="12">${esc(fit(s.label, tx - 26, 12))}</text><rect class="track" x="${tx}" y="${y + 3}" width="${tw}" height="12" rx="6"/><rect x="${bx}" y="${y + 3}" width="${bw}" height="12" rx="6" fill="${KIND_FILL[kindOf(s)]}" opacity="${s.endedAt === null ? 0.65 : 0.95}"/><text class="m" x="${W - 18}" y="${y + 13}" font-size="12" text-anchor="end">${esc(dur)}</text>`
96    })
97    .join('')
98  const title = `<text class="t" x="18" y="30" font-size="14" font-weight="700">Timeline</text><text class="m" x="${18 + textW('Timeline', 14) + 10}" y="30" font-size="12">${esc(`${elapsed(total)} elapsed`)}</text>`
99  return { source: svg(h, `${frame(h)}${title}${body}`, theme), alt: `Timeline, ${elapsed(total)} elapsed: ${rows.map(s => s.label).join(', ')}`, width: W, height: h }
100}
101
102/** The phase a run of cards belongs to, as a pill in its kind color at the left of a card-wide strip, so it scales as the cards do. */
103export function phaseChip(g: { phase: string; stages: Stage[] }, theme: Theme): Card {
104  const label = fit(phaseTitle(g), W - 40, 12)
105  const pw = textW(label, 12) + 28
106  const body = `<rect x="2" y="2" width="${pw}" height="24" rx="12" fill="${KIND_FILL[kindOf(g.stages[0])]}"/><text class="ink" x="${2 + pw / 2}" y="18" font-size="12" font-weight="700" text-anchor="middle">${esc(label)}</text>`
107  return { source: svg(28, body, theme), alt: label, width: W, height: 28 }
108}
109
110/** One item: a round avatar in its kind color, the label and the model, a state pill, then prompt, result and details. */
111export function stageCard(s: Stage, now: number, theme: Theme): Card {
112  const t = tone(s)
113  const st = state(s)
114  const pw = textW(st, 12) + 22
115  const isLive = s.endedAt === null
116  const lines: Array<{ cls: string; v: string; size: number; italic?: boolean }> = []
117  if (s.prompt) lines.push({ cls: 'p', v: `› ${s.prompt}`, size: 13 })
118  lines.push({ cls: isLive ? 'm' : 't', v: stageResult(s), size: 13, italic: isLive })
119  lines.push({ cls: 'm', v: stageDetail(s, now), size: 12 })
120  const h = 64 + lines.length * 20 + 10
121  const x = 62
122  const rows = lines
123    .map((l, i) => `<text class="${l.cls}" x="${x}" y="${78 + i * 20}" font-size="${l.size}"${l.italic ? ' font-style="italic"' : ''}>${esc(fit(l.v, W - x - 18, l.size))}</text>`)
124    .join('')
125  const body =
126    frame(h, s.endedAt === null ? 'card live' : 'card') +
127    `<circle cx="34" cy="36" r="18" fill="${KIND_FILL[kindOf(s)]}"/><text class="ink" x="34" y="41" font-size="14" font-weight="700" text-anchor="middle">${KIND_LETTER[kindOf(s)]}</text>` +
128    `<text class="t" x="${x}" y="32" font-size="14" font-weight="700">${esc(fit(s.label, W - x - pw - 30, 14))}</text>` +
129    `<text class="who" x="${x}" y="52" font-size="12">${esc(fit(who(s), W - x - 18, 12))}</text>` +
130    `<rect class="pill-${t}" x="${W - 16 - pw}" y="17" width="${pw}" height="24" rx="12"/><text class="tx-${t}" x="${W - 16 - pw / 2}" y="33" font-size="12" font-weight="700" text-anchor="middle">${esc(st)}</text>` +
131    rows
132  return { source: svg(h, body, theme), alt: [`${st} ${s.label} ${who(s)}`, ...lines.map(l => l.v)].join(' | '), width: W, height: h }
133}
134
hooks/journal.ts 980 lines
1// Pure functions over a workflow run's files (journal.jsonl, agent-<id>.jsonl, agent-<id>.meta.json):
2// no `$`, so they test alone.
3import type { Stage, Watch } from '../types'
4
5export type Entry = {
6  type: string
7  key?: string
8  agentId?: string
9  label?: string
10  phase?: string
11  result?: unknown
12}
13
14export const EMPTY: Watch = { journal: null, run: null, stages: [], now: 0 }
15
16/** Parses JSON lines; a half-flushed last line is left for the next read. */
17export function parseLines(text: string): Entry[] {
18  const lines = text.split('\n').filter(line => line.length > 0)
19  const out: Entry[] = []
20  for (let i = 0; i < lines.length; i++) {
21    try {
22      const value: unknown = JSON.parse(lines[i] as string)
23      if (value && typeof value === 'object' && typeof (value as Entry).type === 'string') out.push(value as Entry)
24    } catch {
25      if (i === lines.length - 1) break
26    }
27  }
28  return out
29}
30
31/** Folds the journal's entries over the stages seen so far. */
32export function applyEntries(prev: Stage[], entries: Entry[], now: number): Stage[] {
33  const byKey = new Map(prev.map(s => [s.key, s]))
34  const order = prev.map(s => s.key)
35  for (const e of entries) {
36    if (!e.key) continue
37    if (e.type === 'started') {
38      const known = byKey.get(e.key)
39      if (known) {
40        byKey.set(e.key, { ...known, agentId: e.agentId ?? known.agentId, label: e.label !== undefined ? oneLine(e.label) : known.label, phase: e.phase !== undefined ? oneLine(e.phase) : known.phase })
41      } else {
42        byKey.set(e.key, {
43          key: e.key,
44          agentId: e.agentId ?? null,
45          label: oneLine(e.label ?? e.key.slice(0, 12)),
46          phase: oneLine(e.phase ?? ''),
47          startedAt: now,
48          endedAt: null,
49          summary: null,
50          isEmpty: false,
51          isFailed: false,
52          isDisputed: false,
53          alias: null,
54          model: null,
55          effort: null,
56          outputTokens: 0,
57          calls: 0,
58          lastTool: null,
59          isSettled: false,
60        })
61        order.push(e.key)
62      }
63    } else if (e.type === 'result' || e.type === 'failed') {
64      const known = byKey.get(e.key)
65      if (!known) continue
66      if (known.endedAt !== null) continue
67      // `failed`: the stage died before it returned (a session limit, an API error), so there is no result.
68      const died = e.type === 'failed'
69      const isEmpty = died || e.result === null || e.result === undefined
70      const summary = died ? '(stopped without a result)' : isEmpty ? '(no result)' : oneLine(summarize(known.label, e.result))
71      byKey.set(e.key, { ...known, endedAt: now, isEmpty, isFailed: !isEmpty && isFailure(e.result), isDisputed: !isEmpty && isDispute(e.result), summary })
72    }
73  }
74  return order.map(k => byKey.get(k) as Stage)
75}
76
77type Rec = Record<string, unknown>
78const rec = (r: unknown): Rec => (r && typeof r === 'object' ? (r as Rec) : {})
79
80/** A result that reports a failure: a failing verdict or `ok: false`. */
81export function isFailure(result: unknown): boolean {
82  const r = rec(result)
83  return r.verdict === 'fail' || r.ok === false
84}
85
86/** A fix round that left findings disputed: the arbiter rules on them next, so it is neither a pass nor a failure. */
87export function isDispute(result: unknown): boolean {
88  const r = rec(result)
89  return Array.isArray(r.notFixed) && r.notFixed.length > 0
90}
91
92/** What a transcript (agent-<id>.jsonl) says about its stage so far; `first` and `last` are its timestamps in epoch ms. */
93export type TranscriptFacts = {
94  model: string | null
95  effort: string | null
96  outputTokens: number
97  calls: number
98  lastTool: string | null
99  first: number | null
100  last: number | null
101  handback?: string | null
102  lastText?: string | null
103}
104
105/** Reads model, effort, output tokens, tool calls and the first and last timestamps off a transcript's lines (Claude Code or Antigravity). */
106export function readTranscript(text: string): TranscriptFacts {
107  const facts: TranscriptFacts = { model: null, effort: null, outputTokens: 0, calls: 0, lastTool: null, first: null, last: null, handback: null, lastText: null }
108  const seenMsgTokens = new Map<string, number>()
109  for (const line of text.split('\n')) {
110    if (!line) continue
111    let e: Rec
112    try {
113      e = rec(JSON.parse(line))
114    } catch {
115      continue
116    }
117    const rawTs = typeof e.timestamp === 'string' ? e.timestamp : typeof e.created_at === 'string' ? e.created_at : null
118    const at = rawTs ? Date.parse(rawTs) : NaN
119    if (Number.isFinite(at)) {
120      facts.first = facts.first ?? at
121      facts.last = at
122    }
123    if (e.type === 'PLANNER_RESPONSE') {
124      if (typeof e.output_tokens === 'number') facts.outputTokens += e.output_tokens
125      if (typeof e.content === 'string' && oneLine(e.content)) facts.lastText = str(e.content, 100)
126      if (Array.isArray(e.tool_calls)) {
127        for (const tc of e.tool_calls) {
128          const t = rec(tc)
129          const name = oneLine(t.name ?? '?')
130          const args = rec(t.args)
131          if (name === 'send_message') {
132            const msgText = unquoteArg(args.Message)
133            if (oneLine(msgText)) facts.handback = str(msgText, 100)
134            continue
135          }
136          facts.calls += 1
137          const arg = [args.CommandLine, args.AbsolutePath, args.TargetFile, args.query, args.Url, args.toolSummary].map(unquoteArg).find(v => v.length > 0)
138          facts.lastTool = `${name}${arg ? ' ' + str(arg, 50) : ''}`
139        }
140      }
141      continue
142    }
143    const msg = rec(e.message)
144    if (e.type === 'assistant') {
145      // `<synthetic>` is the client's own message when a call fails (a session limit, an API error), not a model.
146      if (typeof msg.model === 'string' && msg.model !== '<synthetic>') facts.model = oneLine(msg.model)
147      if (typeof e.effort === 'string') facts.effort = oneLine(e.effort)
148      const usage = rec(msg.usage)
149      if (typeof usage.output_tokens === 'number') {
150        if (typeof msg.id === 'string') {
151          const prevTok = seenMsgTokens.get(msg.id) ?? 0
152          if (usage.output_tokens > prevTok) {
153            facts.outputTokens += usage.output_tokens - prevTok
154            seenMsgTokens.set(msg.id, usage.output_tokens)
155          }
156        } else {
157          facts.outputTokens += usage.output_tokens
158        }
159      }
160    }
161    const content = msg.content
162    if (!Array.isArray(content)) continue
163    for (const block of content) {
164      const b = rec(block)
165      if (b.type === 'text' && typeof b.text === 'string' && oneLine(b.text)) {
166        facts.lastText = str(b.text, 100)
167      }
168      if (b.type !== 'tool_use') continue
169      const input = rec(b.input)
170      if (b.name === 'SubagentHandback') {
171        if (typeof input.message === 'string' && oneLine(input.message)) facts.handback = str(input.message, 100)
172        continue
173      }
174      facts.calls += 1
175      const arg = [input.command, input.file_path, input.pattern, input.description].find(v => typeof v === 'string') as string | undefined
176      facts.lastTool = `${oneLine(b.name ?? '?')}${arg ? ' ' + str(arg, 50) : ''}`
177    }
178  }
179  return facts
180}
181
182/**
183 * The stage with what its transcript says. Its times come from the transcript's own timestamps once
184 * there are any, so a stage first seen after it finished still shows how long it ran.
185 */
186export function withFacts(s: Stage, facts: TranscriptFacts): Stage {
187  const { first, last, handback, lastText, ...rest } = facts
188  const endedAt = s.endedAt !== null ? (last ?? s.endedAt) : s.kind === 'agent' && handback ? (last ?? s.startedAt) : null
189  const summary = s.kind === 'agent' ? (handback ?? s.summary ?? (endedAt !== null ? lastText : null) ?? null) : s.summary
190  const model = rest.model ?? s.model
191  const effort = rest.effort ?? s.effort
192  const alias = s.alias ?? (s.kind === 'agent' ? inferAlias(model) : null)
193  return { ...s, ...rest, model, effort, alias, summary, startedAt: first ?? s.startedAt, endedAt, isSettled: endedAt !== null }
194}
195
196/** Full metadata from agent-<id>.meta.json for linking session subagents by toolUseId. */
197export function readMetaInfo(text: string): { model: string | null; description: string | null; toolUseId: string | null } {
198  try {
199    const m = rec(JSON.parse(text))
200    return {
201      model: typeof m.model === 'string' && oneLine(m.model) ? oneLine(m.model) : null,
202      description: typeof m.description === 'string' && oneLine(m.description) ? oneLine(m.description) : null,
203      toolUseId: typeof m.toolUseId === 'string' && oneLine(m.toolUseId) ? oneLine(m.toolUseId) : null,
204    }
205  } catch {
206    return { model: null, description: null, toolUseId: null }
207  }
208}
209
210/** The alias the script asked for, from agent-<id>.meta.json. */
211export const readMeta = (text: string): string | null => readMetaInfo(text).model
212
213/** Infers the short tier alias (`fable`, `opus`, `sonnet`, `haiku`, `gemini`) from a resolved model id. */
214export function inferAlias(model: string | null): string | null {
215  if (!model) return null
216  const m = model.toLowerCase()
217  if (m.includes('fable')) return 'fable'
218  if (m.includes('opus')) return 'opus'
219  if (m.includes('sonnet')) return 'sonnet'
220  if (m.includes('haiku')) return 'haiku'
221  if (m.includes('gemini') || m.includes('argon')) return 'gemini'
222  return null
223}
224
225const count = (a: unknown): number => (Array.isArray(a) ? a.length : 0)
226/** One line: each run of whitespace and control characters (which the host refuses to draw) becomes one space. */
227const oneLine = (v: unknown): string => String(v ?? '').replace(/[\s\u0000-\u001f\u007f-\u009f]+/g, ' ').trim()
228/** At most n characters; a cut ends in `…`. */
229export const clip = (text: string, n: number): string => (text.length <= n ? text : n <= 0 ? '' : `${text.slice(0, n - 1)}…`)
230const str = (v: unknown, n = 80): string => clip(oneLine(v), n)
231
232function unquoteArg(v: unknown): string {
233  if (typeof v !== 'string') return ''
234  const s = v.trim()
235  if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith('[') && s.endsWith(']')) || (s.startsWith('{') && s.endsWith('}'))) {
236    try {
237      const parsed: unknown = JSON.parse(s)
238      if (typeof parsed === 'string') return parsed
239    } catch {
240      /* keep raw string */
241    }
242  }
243  // A JSON-quoted value cut short by transcript truncation: drop the opening quote and undo the escapes.
244  if (s.startsWith('"')) return s.slice(1).replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\')
245  return s
246}
247
248const toolResultText = (content: unknown): string =>
249  typeof content === 'string'
250    ? content
251    : Array.isArray(content)
252      ? content.map(b => (typeof rec(b).text === 'string' ? String(rec(b).text) : '')).join('\n')
253      : ''
254
255/** Drops injected blocks from one text block; a block a slimmed read cut before its closing tag runs to the end. */
256const stripInjected = (text: string): string =>
257  text.replace(/<browser_instruction>[\s\S]*?(?:<\/browser_instruction>|$)/gi, '').replace(/<system-reminder>[\s\S]*?(?:<\/system-reminder>|$)/gi, '')
258
259function cleanPrompt(content: unknown): string | null {
260  if (Array.isArray(content) && content.every(b => rec(b).type === 'tool_result')) return null
261  const blocks =
262    typeof content === 'string'
263      ? [content]
264      : Array.isArray(content)
265        ? content.filter(b => rec(b).type === 'text').map(b => String(rec(b).text ?? ''))
266        : []
267  const stripped = blocks.map(stripInjected).join(' ').trim()
268  if (!stripped || /^<(task-notification|command-name|local-command-|agent-message)/i.test(stripped)) return null
269  return oneLine(stripped) || null
270}
271
272/**
273 * Parses a main session transcript (`<sessionId>.jsonl`) into stages:
274 * main-thread turns (`turn:N`), skill activations (`skill:<name>`), spawned subagents (`agent:<desc>`),
275 * and git commits (`commit:<sha>`).
276 */
277export function parseSession(text: string, now: number): Stage[] {
278  const stages: Stage[] = []
279  const pendingAgents = new Map<string, Stage>()
280  const agentsById = new Map<string, Stage>()
281  const pendingCommits = new Map<string, { cmd: string; phase: string; alias: string | null; model: string | null; effort: string | null; at: number }>()
282  const seenCommits = new Set<string>()
283  const seenMsgTokens = new Map<string, number>()
284  let turnCount = 0
285  let currentTurn: Stage | null = null
286  let currentPhase = 'Session'
287  let lastTurnAt = now
288
289  const openTurn = (at: number, prompt: string | null): Stage => {
290    turnCount += 1
291    currentPhase = `Turn ${turnCount}`
292    lastTurnAt = at
293    const turn: Stage = {
294      kind: 'turn',
295      key: `turn:${turnCount}`,
296      agentId: null,
297      label: `turn:${turnCount}`,
298      phase: currentPhase,
299      startedAt: at,
300      endedAt: null,
301      summary: null,
302      prompt,
303      isEmpty: false,
304      isFailed: false,
305      isDisputed: false,
306      alias: null,
307      model: null,
308      effort: null,
309      outputTokens: 0,
310      calls: 0,
311      lastTool: null,
312      isSettled: false,
313    }
314    stages.push(turn)
315    return turn
316  }
317
318  const recordCommit = (id: string, pc: { cmd: string; phase: string; alias: string | null; model: string | null; effort: string | null; at: number }, out: string, t: number): void => {
319    if (/nothing to commit/i.test(out)) return
320    const std = /\[([^\s\]]+)\s+([0-9a-f]{7,12})\]\s*([^\r\n]+)/.exec(out)
321    const mFlag = /\bgit\s+(?:-C\s+\S+\s+)?commit\b[^;&|]*?-m\s+(?:"([^"]+)"|'([^']+)')/.exec(pc.cmd)
322    const subject = oneLine(std?.[3] ?? mFlag?.[1] ?? mFlag?.[2] ?? 'git commit')
323    const shaLine = subject
324      ? out
325          .split(/\r?\n/)
326          .map(l => /^([0-9a-f]{7,12})\s+(.+)/.exec(l.replace(/\u001b\[[0-9;]*m/g, '')))
327          .find(m => m && m[2]?.includes(subject.slice(0, 20)))
328      : undefined
329    const sha = std?.[2] ?? shaLine?.[1] ?? null
330    const dedupKey = sha ?? subject
331    if (seenCommits.has(dedupKey)) return
332    seenCommits.add(dedupKey)
333    stages.push({
334      kind: 'commit',
335      key: `commit:${id}`,
336      agentId: null,
337      label: sha ? `commit:${sha}` : 'commit',
338      phase: pc.phase,
339      startedAt: pc.at,
340      endedAt: t,
341      summary: str(subject, 100),
342      isEmpty: false,
343      isFailed: false,
344      isDisputed: false,
345      alias: pc.alias,
346      model: pc.model,
347      effort: pc.effort,
348      outputTokens: 0,
349      calls: 1,
350      lastTool: 'Bash git commit',
351      isSettled: true,
352    })
353  }
354
355  let agyModel: string | null = null
356  let agyEffort: string | null = null
357  let agyAlias: string | null = null
358  const pendingAgyAgents: Stage[] = []
359  // Set by invoke_subagent; only the next "Created the following subagents" result is a real spawn (not a tool output quoting it).
360  let awaitingSubagents = false
361  const pendingAgyCommits: Array<{ id: string; cmd: string; phase: string; alias: string | null; model: string | null; effort: string | null; at: number }> = []
362  const seenTurnSkills = new Set<string>()
363
364  const lines = text.split('\n').filter(l => l.length > 0)
365  for (let i = 0; i < lines.length; i++) {
366    let e: Rec
367    try {
368      e = rec(JSON.parse(lines[i] as string))
369    } catch {
370      if (i === lines.length - 1) break
371      continue
372    }
373    const rawTs = typeof e.timestamp === 'string' ? e.timestamp : typeof e.created_at === 'string' ? e.created_at : null
374    const at = rawTs ? Date.parse(rawTs) : NaN
375    const t = Number.isFinite(at) ? at : now
376    const msg = rec(e.message)
377
378    if (e.type === 'USER_INPUT') {
379      const rawContent = typeof e.content === 'string' ? e.content : ''
380      const modelMatch = /Model Selection[^\r\n]*? to ([^\r\n.]+)/i.exec(rawContent)?.[1]
381      if (modelMatch) {
382        const me = /^(.+?)\s*\((Low|Medium|High|Max)\)$/i.exec(modelMatch.trim())
383        agyModel = oneLine(me ? me[1] : modelMatch)
384        if (me?.[2]) agyEffort = oneLine(me[2].toLowerCase())
385        agyAlias = inferAlias(agyModel)
386      }
387      const reqMatch = /<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/i.exec(rawContent)?.[1]
388      const cleaned = oneLine(reqMatch ?? rawContent.replace(/<(ADDITIONAL_METADATA|USER_SETTINGS_CHANGE)>[\s\S]*?<\/\1>/gi, ''))
389      if (cleaned) {
390        if (currentTurn && currentTurn.endedAt === null) {
391          currentTurn.endedAt = lastTurnAt
392          currentTurn.isSettled = true
393        }
394        seenTurnSkills.clear()
395        currentTurn = openTurn(t, str(cleaned, 100))
396        currentTurn.model = agyModel ?? 'gemini'
397        currentTurn.alias = agyAlias ?? 'gemini'
398        currentTurn.effort = agyEffort
399      }
400      continue
401    }
402
403    if (e.type === 'PLANNER_RESPONSE') {
404      if (!currentTurn) {
405        currentTurn = openTurn(t, null)
406        currentTurn.model = agyModel ?? 'gemini'
407        currentTurn.alias = agyAlias ?? 'gemini'
408        currentTurn.effort = agyEffort
409      }
410      lastTurnAt = t
411      if (typeof e.output_tokens === 'number') currentTurn.outputTokens += e.output_tokens
412      if (typeof e.content === 'string' && oneLine(e.content)) currentTurn.summary = str(e.content, 100)
413      const tcs = Array.isArray(e.tool_calls) ? e.tool_calls : []
414      if (tcs.length === 0) {
415        currentTurn.endedAt = t
416        currentTurn.isSettled = true
417        continue
418      }
419      currentTurn.endedAt = null
420      currentTurn.isSettled = false
421      for (const tc of tcs) {
422        const b = rec(tc)
423        const name = oneLine(b.name ?? '?')
424        const args = rec(b.args)
425        if (name === 'send_message') continue
426        currentTurn.calls += 1
427        const arg = [args.CommandLine, args.AbsolutePath, args.TargetFile, args.query, args.Url, args.toolSummary].map(unquoteArg).find(v => v.length > 0)
428        currentTurn.lastTool = `${name}${arg ? ' ' + str(arg, 50) : ''}`
429        const id = `step_${String(e.step_index ?? stages.length)}_${currentTurn.calls}`
430
431        const pathArg = unquoteArg(args.AbsolutePath)
432        const skillMatch = name === 'view_file' ? /[\\/]skills[\\/]([^\\/]+)[\\/]SKILL\.md$/i.exec(pathArg)?.[1] : undefined
433        if (skillMatch) {
434          const shortSkill = oneLine(skillMatch).replace(/_/g, '-')
435          if (!seenTurnSkills.has(shortSkill)) {
436            seenTurnSkills.add(shortSkill)
437            currentPhase = `Skill · ${shortSkill}`
438            stages.push({
439              kind: 'skill',
440              key: `skill:${id}`,
441              agentId: null,
442              label: `skill:${shortSkill}`,
443              phase: currentPhase,
444              startedAt: t,
445              endedAt: t,
446              summary: `Activated /${shortSkill}`,
447              isEmpty: false,
448              isFailed: false,
449              isDisputed: false,
450              alias: currentTurn.alias,
451              model: currentTurn.model,
452              effort: currentTurn.effort,
453              outputTokens: 0,
454              calls: 1,
455              lastTool: `Skill ${shortSkill}`,
456              isSettled: true,
457            })
458          }
459        } else if (name === 'invoke_subagent') {
460          awaitingSubagents = true
461          let list: unknown[] = Array.isArray(args.Subagents) ? args.Subagents : []
462          const rawSubs = unquoteArg(args.Subagents)
463          if (!list.length && rawSubs) try {
464            const parsed: unknown = JSON.parse(rawSubs)
465            if (Array.isArray(parsed)) list = parsed
466          } catch {
467            for (const m of rawSubs.matchAll(/"Role"\s*:\s*"((?:\\.|[^"\\])*)"/g)) {
468              list.push({ Role: m[1]?.replace(/\\"/g, '"') })
469            }
470          }
471          for (let sIdx = 0; sIdx < list.length; sIdx++) {
472            const sub = rec(list[sIdx])
473            const desc = oneLine(sub.Role) || oneLine(sub.TypeName) || 'subagent'
474            const reqModel = oneLine(sub.Model)
475            const reqAlias = reqModel && reqModel !== 'inherit' ? reqModel : currentTurn.alias
476            const ag: Stage = {
477              kind: 'agent',
478              key: `agent:${id}_${sIdx}`,
479              agentId: null,
480              label: `agent:${clip(desc, 42)}`,
481              phase: currentPhase,
482              startedAt: t,
483              endedAt: null,
484              summary: null,
485              isEmpty: false,
486              isFailed: false,
487              isDisputed: false,
488              alias: reqAlias,
489              model: currentTurn.model,
490              effort: currentTurn.effort,
491              outputTokens: 0,
492              calls: 0,
493              lastTool: null,
494              isSettled: false,
495            }
496            pendingAgyAgents.push(ag)
497            stages.push(ag)
498          }
499        } else if (name === 'run_command') {
500          const cmd = unquoteArg(args.CommandLine)
501          if (/(?:^|[;&|\r\n])\s*git\s+(?:-C\s+\S+\s+)?commit\b/.test(cmd)) {
502            pendingAgyCommits.push({ id, cmd, phase: currentPhase, alias: currentTurn.alias, model: currentTurn.model, effort: currentTurn.effort, at: t })
503          }
504        }
505      }
506      continue
507    }
508
509    if (e.type === 'GENERIC') {
510      const raw = typeof e.content === 'string' ? e.content : ''
511      if (awaitingSubagents && raw.includes('Created the following subagents:')) {
512        awaitingSubagents = false
513        let sIdx = 0
514        for (const m of raw.matchAll(/"conversationId":\s*"([a-zA-Z0-9_-]+)"/g)) {
515          const cid = m[1]
516          if (cid && agentsById.has(cid)) continue
517          let ag = pendingAgyAgents.shift()
518          if (!ag && cid) {
519            ag = {
520              kind: 'agent',
521              key: `agent:agy_${t}_${sIdx}`,
522              agentId: cid,
523              label: `agent:${clip(cid, 12)}`,
524              phase: currentPhase,
525              startedAt: t,
526              endedAt: null,
527              summary: null,
528              isEmpty: false,
529              isFailed: false,
530              isDisputed: false,
531              alias: currentTurn?.alias ?? null,
532              model: currentTurn?.model ?? null,
533              effort: currentTurn?.effort ?? null,
534              outputTokens: 0,
535              calls: 0,
536              lastTool: null,
537              isSettled: false,
538            }
539            stages.push(ag)
540          }
541          if (cid && ag) {
542            ag.agentId = cid
543            agentsById.set(cid, ag)
544          }
545          sIdx++
546        }
547        pendingAgyAgents.length = 0
548      } else if (pendingAgyCommits.length > 0 && raw.includes('The command exited with code')) {
549        const pc = pendingAgyCommits.shift()
550        if (pc && raw.includes('The command exited with code 0')) recordCommit(pc.id, pc, raw, t)
551      }
552      continue
553    }
554
555    if (e.type === 'SYSTEM_MESSAGE') {
556      const raw = typeof e.content === 'string' ? e.content : ''
557      for (const m of raw.matchAll(/\[Message\]\s+timestamp=[^\s]+\s+sender=([^\s]+)\s+priority=[^\s]+\s+content=([\s\S]*?)(?=\n\[Message\]|<\/SYSTEM_MESSAGE>|$)/g)) {
558        const sender = oneLine(m[1])
559        const body = m[2] ?? ''
560        if (sender === 'system' && /subagents and background tasks have been stopped/i.test(body)) {
561          for (const s of stages) {
562            if (s.kind === 'agent' && s.endedAt === null) {
563              s.endedAt = t
564              s.isFailed = true
565              s.summary = s.summary ?? '(stopped by server restart)'
566            }
567          }
568        } else if (sender && agentsById.has(sender)) {
569          const ag = agentsById.get(sender) as Stage
570          if (ag.endedAt === null) ag.endedAt = t
571          if (!ag.summary && oneLine(body)) ag.summary = str(body, 100)
572        }
573      }
574      continue
575    }
576
577    if (e.type === 'user') {
578      const rawContent = toolResultText(msg.content)
579      if (rawContent && (rawContent.includes('<agent-message') || rawContent.includes('<task-'))) {
580        // A slimmed read can cut a long report before its closing tag.
581        const am = /<agent-message\s+from="([^"]+)"[^>]*>([\s\S]*?)(?:<\/agent-message>|$)/i.exec(rawContent)
582        const tnId = /<task-id>([^<]+)<\/task-id>/i.exec(rawContent)?.[1]
583        const tnTool = /<tool-use-id>([^<]+)<\/tool-use-id>/i.exec(rawContent)?.[1]
584        const aid = oneLine(am?.[1] ?? tnId)
585        const ag = (aid ? agentsById.get(aid) : undefined) ?? (tnTool ? pendingAgents.get(oneLine(tnTool)) : undefined)
586        if (ag) {
587          if (aid && !ag.agentId) {
588            ag.agentId = aid
589            agentsById.set(aid, ag)
590          }
591          if (ag.endedAt === null) ag.endedAt = t
592          if (ag.phase) currentPhase = ag.phase
593          if (/<status>failed<\/status>/i.test(rawContent)) ag.isFailed = true
594          if (am?.[2] && !ag.summary) ag.summary = str(am[2].replace(/^\[Subagent\s+[^\]]+\]\s*/i, ''), 100)
595        }
596      }
597
598      if (Array.isArray(msg.content)) {
599        for (const block of msg.content) {
600          const b = rec(block)
601          if (b.type !== 'tool_result') continue
602          const id = String(b.tool_use_id ?? '')
603          const ag = pendingAgents.get(id)
604          if (ag) {
605            const tr = rec(e.toolUseResult)
606            if (typeof tr.agentId === 'string' && oneLine(tr.agentId)) {
607              ag.agentId = oneLine(tr.agentId)
608              agentsById.set(ag.agentId, ag)
609            }
610            if (typeof tr.resolvedModel === 'string' && oneLine(tr.resolvedModel) && !ag.model) {
611              ag.model = oneLine(tr.resolvedModel)
612              ag.alias = ag.alias ?? inferAlias(ag.model)
613            }
614            const isAsync = tr.isAsync === true || tr.status === 'async_launched'
615            if (b.is_error === true) {
616              ag.endedAt = t
617              ag.isFailed = true
618              ag.summary = str(toolResultText(b.content), 100) || '(agent failed)'
619            } else if (!isAsync) {
620              ag.endedAt = t
621              const outTxt = toolResultText(b.content)
622              if (outTxt && !ag.summary) ag.summary = str(outTxt, 100)
623            }
624          }
625          const pc = pendingCommits.get(id)
626          if (pc) {
627            pendingCommits.delete(id)
628            if (b.is_error !== true) {
629              const out = `${toolResultText(b.content)}\n${typeof rec(e.toolUseResult).stdout === 'string' ? String(rec(e.toolUseResult).stdout) : ''}`
630              recordCommit(id, pc, out, t)
631            }
632          }
633        }
634      }
635
636      if (!e.isMeta) {
637        const prompt = cleanPrompt(msg.content)
638        if (prompt && /^\[Request interrupted by user/.test(prompt)) {
639          // The engine's marker for an interrupt, not something typed: it ends the turn, the next prompt opens one.
640          if (currentTurn && currentTurn.endedAt === null) {
641            currentTurn.endedAt = lastTurnAt
642            currentTurn.isSettled = true
643            currentTurn.summary = currentTurn.summary ? `(interrupted) ${currentTurn.summary}` : '(interrupted)'
644          }
645        } else if (prompt) {
646          if (currentTurn && currentTurn.endedAt === null) {
647            currentTurn.endedAt = lastTurnAt
648            currentTurn.isSettled = true
649          }
650          currentTurn = openTurn(t, str(prompt, 100))
651        }
652      }
653    } else if (e.type === 'attachment') {
654      // A message typed while Claude works is folded into the running turn, so it opens none; the turn shows it as its prompt.
655      const att = rec(e.attachment)
656      if (att.type === 'queued_command' && att.commandMode === 'prompt' && currentTurn) {
657        const text = cleanPrompt(att.prompt)
658        if (text) currentTurn.prompt = str(`(mid-turn) ${text}`, 100)
659      }
660    } else if (e.type === 'assistant') {
661      if (!currentTurn) currentTurn = openTurn(t, null)
662      lastTurnAt = t
663      if (typeof msg.model === 'string' && msg.model !== '<synthetic>') {
664        currentTurn.model = oneLine(msg.model)
665        currentTurn.alias = inferAlias(currentTurn.model)
666      }
667      if (typeof e.effort === 'string') currentTurn.effort = oneLine(e.effort)
668      const usage = rec(msg.usage)
669      if (typeof usage.output_tokens === 'number') {
670        if (typeof msg.id === 'string') {
671          const prevTok = seenMsgTokens.get(msg.id) ?? 0
672          if (usage.output_tokens > prevTok) {
673            currentTurn.outputTokens += usage.output_tokens - prevTok
674            seenMsgTokens.set(msg.id, usage.output_tokens)
675          }
676        } else {
677          currentTurn.outputTokens += usage.output_tokens
678        }
679      }
680      if (msg.stop_reason === 'end_turn') {
681        currentTurn.endedAt = t
682        currentTurn.isSettled = true
683      } else if (msg.stop_reason === 'tool_use') {
684        currentTurn.endedAt = null
685        currentTurn.isSettled = false
686      }
687
688      const content = msg.content
689      if (!Array.isArray(content)) continue
690      for (const block of content) {
691        const b = rec(block)
692        // The client's own filler after an interrupt (<synthetic> "No response requested.") is not Claude's answer.
693        if (b.type === 'text' && typeof b.text === 'string' && oneLine(b.text) && msg.model !== '<synthetic>') {
694          currentTurn.summary = str(b.text, 100)
695        }
696        if (b.type !== 'tool_use') continue
697        currentTurn.calls += 1
698        const input = rec(b.input)
699        const arg = [input.command, input.file_path, input.pattern, input.description, input.skill].find(v => typeof v === 'string') as string | undefined
700        currentTurn.lastTool = `${oneLine(b.name ?? '?')}${arg ? ' ' + str(arg, 50) : ''}`
701        const id = String(b.id ?? stages.length)
702
703        if (b.name === 'Skill') {
704          const rawSkill = oneLine(input.skill) || 'skill'
705          const shortSkill = rawSkill.replace(/^alon-skills:/, '')
706          currentPhase = `Skill · ${shortSkill}`
707          stages.push({
708            kind: 'skill',
709            key: `skill:${id}`,
710            agentId: null,
711            label: `skill:${shortSkill}`,
712            phase: currentPhase,
713            startedAt: t,
714            endedAt: t,
715            summary: oneLine(input.args) ? str(input.args, 100) : `Activated /${shortSkill}`,
716            isEmpty: false,
717            isFailed: false,
718            isDisputed: false,
719            alias: currentTurn.alias,
720            model: currentTurn.model,
721            effort: currentTurn.effort,
722            outputTokens: 0,
723            calls: 1,
724            lastTool: `Skill ${shortSkill}`,
725            isSettled: true,
726          })
727        } else if (b.name === 'Agent') {
728          const desc = oneLine(input.description) || oneLine(input.subagent_type) || 'subagent'
729          const reqAlias = typeof input.model === 'string' && oneLine(input.model) ? oneLine(input.model) : null
730          const ag: Stage = {
731            kind: 'agent',
732            key: `agent:${id}`,
733            agentId: null,
734            label: `agent:${clip(desc, 42)}`,
735            phase: currentPhase,
736            startedAt: t,
737            endedAt: null,
738            summary: null,
739            isEmpty: false,
740            isFailed: false,
741            isDisputed: false,
742            alias: reqAlias,
743            model: null,
744            effort: null,
745            outputTokens: 0,
746            calls: 0,
747            lastTool: null,
748            isSettled: false,
749          }
750          pendingAgents.set(id, ag)
751          stages.push(ag)
752        } else if ((b.name === 'Bash' || b.name === 'PowerShell') && typeof input.command === 'string' && /(?:^|[;&|\r\n])\s*git\s+(?:-C\s+\S+\s+)?commit\b/.test(input.command)) {
753          pendingCommits.set(id, { cmd: input.command, phase: currentPhase, alias: currentTurn.alias, model: currentTurn.model, effort: currentTurn.effort, at: t })
754        }
755      }
756    }
757  }
758  return stages
759}
760
761/** Merges session items and workflow stages in chronological start order. */
762/**
763 * What a session log past the plugin read limit is filtered through: the same three patterns run in PowerShell (.NET)
764 * and perl, and in slimLog for the tests. Every line stays valid JSON. `meta` drops the engine's bookkeeping lines
765 * (api-request copies, titles, bridge state; never user, assistant or attachment), `image` empties pasted images'
766 * base64, and `long` cuts any string past 2000 characters at an escape boundary. Perl before 5.38 (macOS's
767 * /usr/bin/perl is 5.34) stops a repeated group after 65534 rounds, so past its first 2001 units `long` takes runs of
768 * plain characters whole and escapes in chunks of up to 30000, each held by a lookahead and a backreference (atomic in
769 * JS, .NET and perl alike, so a miss can't backtrack into it). It never starts on an escaped quote, so a miss costs one pass.
770 * slimLog applies the patterns only; the tail cut lives in the child scripts and tests/slim-check.mjs runs those.
771 */
772export const SLIM = {
773  meta: '^[{]"type":"(?!user"|assistant"|attachment")[a-z][a-z-]*".*\\r?\\n',
774  image: '"data":"[A-Za-z0-9+/=]{200,}"',
775  long: '(?<!\\\\)"((?:[^"\\\\\\r\\n]|\\\\.){2000})(?:[^"\\\\\\r\\n]|\\\\.)[^"\\\\\\r\\n]*(?:(?=((?:\\\\.[^"\\\\\\r\\n]*){1,30000}))\\2)*"',
776} as const
777
778export const slimLog = (text: string): string =>
779  text.replace(new RegExp(SLIM.meta, 'gm'), '').replace(new RegExp(SLIM.image, 'g'), '"data":""').replace(new RegExp(SLIM.long, 'g'), '"$1..."')
780
781/** What one $.fs.read copies at most: the engine rejects a larger file, and caps a process's stdout the same. */
782export const READ_LIMIT = 4 * 1024 * 1024
783/** Bytes a slimmed log keeps at most: past it only its newest whole lines are kept, behind SLIM_CUT. */
784export const SLIM_TAIL = READ_LIMIT - 512 * 1024
785/** The first line of a slimmed log that had to drop its oldest lines; parseSession skips it. */
786export const SLIM_CUT = '{"type":"slim-cut"}'
787/** How long a slimming child may run before its read counts as failed. */
788export const SLIM_TIMEOUT_MS = 20000
789
790// The SLIM patterns, the tail size and the cut marker reach the child as environment variables, never spliced into its
791// script, and so does the log path for PowerShell; perl gets it as its file argument. perl runs with -C0 and an empty
792// PERL5OPT so a user's PERL_UNICODE or PERL5OPT=-C can't turn its byte counts into character counts.
793const POWERSHELL_SCRIPT = [
794  "$ErrorActionPreference='Stop'",
795  '[Console]::OutputEncoding=[Text.Encoding]::UTF8',
796  '$t=[IO.File]::ReadAllText($env:WW_LOG)',
797  "$t=[regex]::Replace($t,$env:WW_META,'',[Text.RegularExpressions.RegexOptions]::Multiline)",
798  `$t=[regex]::Replace($t,$env:WW_IMAGE,'"data":""')`,
799  `$t=[regex]::Replace($t,$env:WW_LONG,'"$1..."')`,
800  '$b=[Text.Encoding]::UTF8.GetBytes($t)',
801  '$n=[int]$env:WW_TAIL',
802  'if($b.Length -gt $n){$i=[Array]::IndexOf($b,[byte]10,$b.Length-$n-1); $t=$env:WW_CUT+[char]10+[Text.Encoding]::UTF8.GetString($b,$i+1,$b.Length-$i-1)}',
803  '[Console]::Out.Write($t)',
804].join('; ')
805const PERL_SCRIPT =
806  's/$ENV{WW_META}//gm; s/$ENV{WW_IMAGE}/"data":""/g; s/$ENV{WW_LONG}/"$1..."/g; ' +
807  'if (length($_) > $ENV{WW_TAIL}) { $_ = "$ENV{WW_CUT}\\n" . substr($_, index($_, "\\n", length($_) - $ENV{WW_TAIL} - 1) + 1) }'
808
809/** The child that slims a log: Windows PowerShell by its full path when SystemRoot is set, perl elsewhere. */
810export function slimCommand(path: string, systemRoot: string | null | undefined, perl = 'perl'): { argv: string[]; env: Record<string, string> } {
811  const argv = systemRoot
812    ? [`${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, '-NoProfile', '-NonInteractive', '-Command', POWERSHELL_SCRIPT]
813    : [perl, '-C0', '-0777', '-pe', PERL_SCRIPT, path]
814  const env = { WW_LOG: path, WW_META: SLIM.meta, WW_IMAGE: SLIM.image, WW_LONG: SLIM.long, WW_TAIL: String(SLIM_TAIL), WW_CUT: SLIM_CUT }
815  return { argv, env: systemRoot ? env : { ...env, PERL5OPT: '' } }
816}
817
818export function mergeStages(sessionStages: Stage[], workflowStages: Stage[]): Stage[] {
819  if (sessionStages.length === 0) return workflowStages
820  if (workflowStages.length === 0) return sessionStages
821  return [...sessionStages, ...workflowStages].sort((a, b) => a.startedAt - b.startedAt)
822}
823
824/** Compact Unicode swimlane bar (`░░████░░`) for a stage's span across `[t0, t0 + total]`. */
825export function timelineBar(s: Stage, t0: number, total: number, width = 16): string {
826  const w = Math.max(4, width)
827  const span = Math.max(1, total)
828  const from = Math.max(0, s.startedAt - t0)
829  const to = Math.max(from, (s.endedAt ?? t0 + span) - t0)
830  const start = Math.min(w - 1, Math.floor((from / span) * w))
831  const len = Math.max(1, Math.min(w - start, Math.ceil(((to - from) / span) * w)))
832  const fill = s.endedAt === null ? '▓' : '█'
833  return `${'░'.repeat(start)}${fill.repeat(len)}${'░'.repeat(Math.max(0, w - start - len))}`
834}
835
836/**
837 * One line per stage result. The alon-skills build-loop labels are known
838 * (plan, scout, spec, research, build, measure, refute, arbiter, fix, close);
839 * any other label gets a short generic line.
840 */
841export function summarize(label: string, result: unknown): string {
842  const role = label.split(':')[0] ?? ''
843  if (typeof result === 'string') return str(result, 100)
844  const r = rec(result)
845  switch (role) {
846    case 'plan': {
847      const stale = rec(r.staleBlocked)
848      if (r.staleBlocked) return `stale row ${str(stale.taskId)}: ${str(stale.reason)}`
849      return r.taskId ? `picked ${str(r.taskId)} on ${str(r.branch)}${r.resuming ? ' (resuming)' : ''}` : `stop: ${str(r.stopReason)}`
850    }
851    case 'scout':
852      return `${count(r.files)} files, ${count(r.tests)} tests, ${count(r.docSections)} doc sections`
853    case 'spec':
854      return r.stopReason ? `stop: ${str(r.stopReason)}` : `spec at ${str(r.specPath)}; docs changed ${count(r.docsChanged)}; unverified APIs ${count(r.unverifiedApis)}`
855    case 'research':
856      return `research at ${str(r.researchPath)}; still unverified ${count(r.unverifiedRemaining)}`
857    case 'build':
858      return `ok=${String(r.ok)} commits=${count(r.commits)} tests=${r.testsPassed ? 'pass' : 'FAIL'} lint=${r.lintPassed ? 'pass' : 'FAIL'} deviations=${count(r.deviations)}${r.blockedReason ? ` BLOCKED: ${str(r.blockedReason)}` : ''}`
859    case 'measure':
860      return `${String(r.filesChanged)} files, ${String(r.linesChanged)} lines${r.docsOnly ? ', docs only' : ''}${r.touchesTrustBoundary ? ', trust boundary' : ''}`
861    case 'refute': {
862      const first = rec((r.blocking as unknown[] | undefined)?.[0])
863      const head = `${String(r.verdict).toUpperCase()} blocking=${count(r.blocking)} advisory=${count(r.advisory)} testsRan=${String(r.testsRan)}`
864      return first.issue ? `${head} | ${str(first.file)}: ${str(first.issue, 60)}` : head
865    }
866    case 'arbiter':
867      return ((r.rulings as unknown[] | undefined) ?? []).map(x => `${str(rec(x).key)} ${str(rec(x).ruling)}: ${str(rec(x).reason, 100)}`).join('; ') || 'no rulings'
868    case 'fix':
869      return `fixed=${count(r.fixed)} disputed=${count(r.notFixed)} commits=${count(r.commits)}` + ((r.notFixed as unknown[] | undefined) ?? []).map(x => ` | disputed ${str(rec(x).key)}: ${str(rec(x).reason, 100)}`).join('')
870    case 'close':
871      return r.ok ? `row updated, commit ${str(r.commit) || '?'}` : 'close reported not ok'
872    default:
873      return str(JSON.stringify(result), 100)
874  }
875}
876
877/**
878 * Stages in run order, cut where the phase changes: each stretch of one phase
879 * gets its own divider, so a second refute round is not folded into the first.
880 */
881export function phaseRuns(stages: Stage[]): Array<{ phase: string; stages: Stage[] }> {
882  const runs: Array<{ phase: string; stages: Stage[] }> = []
883  for (const s of stages) {
884    const last = runs[runs.length - 1]
885    if (last && last.phase === s.phase) last.stages.push(s)
886    else runs.push({ phase: s.phase, stages: [s] })
887  }
888  return runs
889}
890
891/** A divider's text: the phase, and the round when its stages' labels carry one (`refute:…:r2`): `Refute · round 2`. */
892export function phaseTitle(g: { phase: string; stages: Stage[] }): string {
893  const round = /:r(\d+)$/.exec(g.stages[0]?.label ?? '')?.[1]
894  return `${g.phase || '(no phase)'}${round ? ` · round ${round}` : ''}`
895}
896
897export const running = (w: Watch): Stage[] => w.stages.filter(s => s.endedAt === null)
898
899/** `0:46`, `15:03`: minutes unpadded, seconds rounded down. */
900export function elapsed(ms: number): string {
901  const s = Math.max(0, Math.floor(ms / 1000))
902  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
903}
904
905const many = (n: number, one: string, more: string): string => `${n} ${n === 1 ? one : more}`
906
907type Outcome = 'running' | 'empty' | 'failed' | 'disputed' | 'done'
908function outcome(s: Stage): Outcome {
909  if (s.endedAt === null) return 'running'
910  if (s.isEmpty) return 'empty'
911  if (s.isFailed === true) return 'failed'
912  if (s.isDisputed === true) return 'disputed'
913  return 'done'
914}
915const STATE: Record<Outcome, string> = { running: '▶ running', empty: '✗ no result', failed: '! failed', disputed: '! disputed', done: '✓ done' }
916
917/** The stage's state as a glyph and a word, so it never rests on color alone. */
918export const state = (s: Stage): string => STATE[outcome(s)]
919
920/** The theme color that goes with the state. */
921export function tone(s: Stage): 'warning' | 'error' | 'success' {
922  const o = outcome(s)
923  return o === 'running' || o === 'disputed' ? 'warning' : o === 'done' ? 'success' : 'error'
924}
925
926/**
927 * Every stage counted once, as its card shows it: `14 done · 5 failed · 0 running`, with
928 * `· 1 disputed` after done when a fix round left findings for the arbiter. Failed includes no result.
929 */
930export function tally(w: Watch): string {
931  const n = { done: 0, disputed: 0, failed: 0, running: 0 }
932  for (const s of w.stages) {
933    const o = outcome(s)
934    n[o === 'empty' ? 'failed' : o] += 1
935  }
936  return `${n.done} done${n.disputed ? ` · ${n.disputed} disputed` : ''} · ${n.failed} failed · ${n.running} running`
937}
938
939/** `fable→claude-fable-5-1 high`: what ran the stage, at which effort (`n/a` for a model that records none). */
940export function who(s: Stage): string {
941  const model = s.alias && s.model ? `${s.alias}→${s.model}` : (s.model ?? s.alias ?? '?')
942  return `${model} ${s.effort ?? 'n/a'}`
943}
944
945/** The head of a stage's block after its state: `build:1.2  sonnet→claude-sonnet-5-5 medium`. */
946export function stageTitle(s: Stage): string {
947  return `${s.label}  ${who(s)}`
948}
949
950/** The result in one line, or `no result yet` while the stage runs. */
951export function stageResult(s: Stage): string {
952  return s.endedAt === null ? 'no result yet' : (s.summary ?? '')
953}
954
955/**
956 * The details as one compact line, the element tables having no fold:
957 * `Ran for 0:46 · 5 tools · 0.8k tokens`, or `Running for 0:12 · 3 calls · Bash npm test`.
958 */
959export function stageDetail(s: Stage, now: number): string {
960  const isLive = s.endedAt === null
961  const time = elapsed((isLive ? now : (s.endedAt as number)) - s.startedAt)
962  if (isLive) return `Running for ${time} · ${many(s.calls, 'call', 'calls')} · ${s.lastTool ?? 'starting…'}`
963  return `Ran for ${time} · ${many(s.calls, 'tool', 'tools')} · ${(s.outputTokens / 1000).toFixed(1)}k tokens`
964}
965
966/** One stage as a block: the head line, then its result and its details indented under it. */
967export function stageLines(s: Stage, now: number): string[] {
968  return [`${state(s)}  ${stageTitle(s)}`, ...(s.prompt ? [`    › ${s.prompt}`] : []), `    ${stageResult(s)}`, `    ${stageDetail(s, now)}`]
969}
970
971/** The whole picture as plain text: what the command prints, the same blocks the pane draws, oldest first as a log reads. */
972export function report(w: Watch): string {
973  const lines = [`${w.run}: ${tally(w)}`]
974  for (const g of phaseRuns(w.stages)) {
975    lines.push(`── ${phaseTitle(g)}`)
976    for (const s of g.stages) lines.push(...stageLines(s, w.now))
977  }
978  return lines.join('\n')
979}
980
types/index.d.ts 67 lines
1/** The pane's card theme, picked with its toggle and kept between sessions. */
2export type Theme = 'dark' | 'light'
3
4/** The pane's size the person picked with its Minimize/Expand button, until the session next turns busy or idle. */
5export type PaneView = 'full' | 'compact'
6
7export type StageKind = 'stage' | 'turn' | 'skill' | 'agent' | 'commit'
8
9export type Stage = {
10  /** The kind of item in the feed; defaults to 'stage' for Workflow stages. */
11  kind?: StageKind
12  /** The journal's or session's key for this item. */
13  key: string
14  /** The subagent's loop id; its transcript is agent-<id>.jsonl beside the journal or under subagents/. */
15  agentId: string | null
16  label: string
17  phase: string
18  /** The transcript's first timestamp (epoch ms); until there is one, $.clock.now() at the tick that first saw the stage. */
19  startedAt: number
20  /** The transcript's last timestamp once the stage finished, else $.clock.now() at the tick that saw it finish; null while running. */
21  endedAt: number | null
22  /** One line about the result, or null while running. */
23  summary: string | null
24  /** For a turn: the person's words that opened it, or the latest typed while it ran. */
25  prompt?: string | null
26  /** True when the journal recorded a null result, or a `failed` entry (the stage died before it returned). */
27  isEmpty: boolean
28  /** True when the result reports a failure: a failing verdict or `ok: false`. */
29  isFailed: boolean
30  /** True when a fix round left findings disputed, for the arbiter to rule on. */
31  isDisputed: boolean
32  /** The model alias the script asked for (from the agent's meta.json), or null. */
33  alias: string | null
34  /** The model id the engine resolved the alias to, from the transcript, or null. */
35  model: string | null
36  /** The effort level the transcript recorded; null for a model without one. */
37  effort: string | null
38  /** Output tokens the stage generated so far, thinking included. */
39  outputTokens: number
40  /** Tool calls seen in the transcript so far. */
41  calls: number
42  /** The last tool the stage called, with a short argument. */
43  lastTool: string | null
44  /** True once a finished stage's transcript was read for the last time. */
45  isSettled: boolean
46}
47
48export type Watch = {
49  /** The journal.jsonl being tailed, or null when no run was found yet. */
50  journal: string | null
51  /** The run's directory name (the run id). */
52  run: string | null
53  stages: Stage[]
54  /** $.clock.now() at the last tick, so elapsed times redraw. */
55  now: number
56  /** Set while a log could not be read: what the pane says above the items it kept. */
57  notice?: string | null
58  /** True once nothing has run for IDLE_MS: the pane folds to its compact strip unless the person expanded it. */
59  isIdle?: boolean
60}
61
62declare module 'claude-code' {
63  interface PluginState {
64    'workflow-watch': { watch: Watch; theme: Theme; isTimelineOpen: boolean; pinnedView: PaneView | null }
65  }
66}
67