Side pane following a run-lot run, or a run-plan run with a plan view and navigation between its batches: phases as columns, agents (model, duration, tokens…

From a business need to tested, audited code — Claude Code does the work, you make the decisions.
cctoolkit is a Claude Code plugin for DDD / clean-architecture repos. You describe a feature; Claude writes the spec with you, plans it, then builds it batch by batch under strict TDD and audits the result before you commit. What the product does is kept in a business knowledge base beside the code, so every new spec starts from it.
.NET first; Python, Java/Kotlin and TypeScript repos work through their layout and test tags.
claude plugin marketplace add pierrebelin/claude-code-toolkit --scope project
claude plugin install cctoolkit@cctoolkit --scope project
Restart Claude Code, then run /cctoolkit:kit-init: it reads your repo, asks a few questions and sets everything up.
Requirements, options and what kit-init writes: INSTALL.md.
Three commands, one per step. Each one writes a file the next one reads.
flowchart LR
S["<b>1. Spec</b><br/>/business-spec"] -->|SPEC.md| P["<b>2. Plan</b><br/>/plan-implementation"]
P -->|"PLAN.md + one sheet per batch"| R["<b>3. Build</b><br/>/run-plan or /run-lot"]
R -->|"code, tests, report"| C(["you review and commit"])
/cctoolkit:business-spec — Claude asks you one question at a time, then writes a short business spec: rules, use cases, no technical detail. A second agent tries to poke holes in it./cctoolkit:plan-implementation — turns the spec into a technical plan, split into small batches.| Whole plan | Batch by batch | |
|---|---|---|
| Command | /cctoolkit:run-plan <plan> | /cctoolkit:run-lot <sheet> |
| Runs | every batch, in dependency order | one batch |
| You step in | once, at the end | after each batch: review, /clear, next |
| Stops | a batch that cannot pass is set aside, only its dependents wait; batches set aside for one shared cause stop the plan | the batch comes back DONE, or with what needs your eyes |
| Fits | a plan you trust, a run over lunch or overnight | a new plan, a tricky batch, a team that reviews every commit |
Whole plan runs the batches in the order the plan allows. Nothing waits for you: an ambiguity is decided by the agent that meets it, and what was decided without you opens the run report, to read after the plan. A batch that still cannot pass is set aside with its partial work saved, the next run picking it up where it stopped, and the batches that do not depend on it carry on. Each batch that passes gets its own commit; you review them together at the end.
Batch by batch keeps you in the loop: each batch ends on a report and its own commit, you read it and start the next one with a clean context.
On a new plan, or a batch you are unsure of, go batch by batch until the first ones come back clean.
Inside run-lot, each behaviour of the batch is one loop:
flowchart LR
I["run-lot"] --> R
I -->|"compact contract:<br/>RM/CU, scenario, signatures,<br/>invariants, expected cost"| A["tdd-cycle subagent"]
A --> R["RED<br/>writes the red test"]
R --> K["checkpoint<br/>the hook checks the disk:<br/>red, on an assertion"]
K --> G["GREEN + REFACTOR<br/>writes the production code"]
G -->|"green + cost stated<br/>or BLOCKED"| I
I -.->|"next behaviour"| A
I ==>|"whole batch green"| V["audit<br/>ddd-tdd-auditor"]
The orchestrator writes neither tests nor code: it splits the work, checks the reports and settles the design. One agent per behaviour writes the failing test, passes a checkpoint read off the disk, then makes it pass; a test it changes after that checkpoint is recorded with its assertions and judged by the audit. Another agent audits.
A batch that stops short: fix the cause and run /cctoolkit:run-lot on the same sheet again, it resumes from the cycles already done. /cctoolkit:implement-tdd launches the chain from a plan path, /cctoolkit:verify-ddd-tdd audits a batch on demand.
Want to see the files? examples/ walks one small feature from spec to report.
What the product does and why lives in the repo, under docs/business/ by default: one folder per bounded context, one file per use case with its rules, the business decisions, the ADRs, and a history of every change. Each use case, rule and decision has a global id (CAT-RM-003) that the specs and plans cite.
flowchart LR
K[("knowledge base")] -->|read by levels| S["/business-spec<br/>writes a delta"]
S --> P["plan, build"]
P -->|"plan delivered:<br/>merge staged"| M["/knowledge-merge<br/>you confirm"]
M --> K
H["code changed<br/>outside the kit"] -->|"/knowledge-sync"| K
/cctoolkit:knowledge-sync builds the base from your code the first time, then catches up with what changed outside the kit. Nothing is written until you confirm./cctoolkit:business-spec reads the base first and writes the spec as a delta: what the feature adds, changes or retires.run-plan stages the merge; /cctoolkit:knowledge-merge shows the diff and writes it on your word./cctoolkit:ask answers how the product behaves, or why, from the base, each fact cited by its id.The base is plain Markdown, so you can review and commit it like code. The worked example is under examples/docs/business/.
A batch takes tens of minutes and a dozen agents, a whole plan several times that. The run-lot-pane mod shows it live inside Claude Code. On a plan, it opens on the plan: each batch with its state, time and tokens, and the supervisor checking between batches.

Open a batch and it shows each phase, which agent is working, the tests going red then green, the tokens spent, and the final verdict. The pane also steers the run: review what it decided without you, leave a note for a batch's agents (keys).

claude plugin install run-lot-pane@cctoolkit --scope project
Two more mods — a browser of the knowledge base that spends no model context and shows the spec live as it's written, and a context meter telling you when to /clear: mods/README.md.
This kit encodes one way of working. It will:
DONE batch, nothing else — the workflow commits the batch files only, your earlier changes stay out; never a push.If your team works differently, half of it will feel like noise. Full list: skills/README.md.
| Install, update, dependencies | INSTALL.md |
| A feature from spec to report | examples/ |
| The knowledge base's format | knowledge-format.md |
| Every skill and agent | skills/README.md |
| Layouts and configuration | presets/README.md |
MIT. Take what you want, closed-source projects included.
hooks/register.tsx 4762 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, FsEntry, ModelUsage, Register, TurnStepChunk } from 'claude-code'
3
4import type {
5 AuditVerdict, ChildWorkflow, Journal, KnowledgeMerge, Navigation, Outcome, PhaseDeclaration, PhaseSample, PhaseSamples, RunStatus, Screen, SessionFigures, Sheet,
6 LotFigures, PlanLot, Prompted, RunFeed, SheetCycle, Step, StreamKind, TddMarks, ToolTrace, WorkflowAgent, WorkflowRun,
7} from '../types'
8
9const PANE = 'run-lot-pane'
10const TICK_MS = 2_000
11const KEPT_RUNS = 1
12const NO_PHASE = '—'
13const AUDIT_PHASE = 'Audit'
14const SLOW_FACTOR = 2
15const STALL_TOOLS = 40
16const STALL_CONTEXT = 150_000
17const STALL_IDLE_MS = 60_000
18const STALL_WAIT_MS = 120_000
19const STALL_TOOL_MS = 300_000
20const STALL_SLOW_MS = 60_000
21const SLOW_RATE = 20
22const CHARS_PER_TOKEN = 4
23const STREAM_WRITE_MS = 1_000
24const ALERT_MS = 10_000
25const ALERT_REASON = 110
26const PARALLEL_PHASES = [['Global green', 'Closing'], ['Audit', 'Review']]
27const INTERLEAVED_PHASES = [['RED', 'GREEN']]
28const CONDITIONAL_PHASES = ['Arbiter', 'Question']
29const KEPT_JOURNALS = 8
30const SCANNED_SESSIONS = 200
31const DONE = '✅'
32const COUNT_WIDTH = 6
33const TIME_WIDTH = 7
34const TOKENS_WIDTH = 7
35// Wider than any terminal: the dock opens at its ceiling, 45 % of the terminal's columns.
36const PANE_COLUMNS = 1000
37const MODEL_WIDTH = 14
38const rule = (cells: number): string => '─'.repeat(Math.max(0, cells))
39const WIDE_COLUMNS = 56
40const SHEET_PATTERN = /-PLAN-(F\d+)\.md$/
41const LOT_PATTERN = /(?:^|[\\/])([^\\/]+?)-PLAN-(F\d+)\.md$/
42const CHILD_PLUGIN = /\bworkflow\(\s*['"]([\w-]+):[\w.-]+['"]/
43const CHILD_CALL = /\bworkflow\(\s*(?:['"](?:[\w-]+:)?([\w.-]+)['"]|\{\s*scriptPath:[^)]*?[\\/]([\w.-]+)\.js)/
44const PROMPT_LOT = /Workflow run-lot, batch (F\d+)\.[\s\S]*?Batch sheet: (\S+?\.md)\./
45const REVIEW_LOT = /^mode: next-batch \S+ (\S*?-PLAN-(F\d+)\.md)/
46const PLAN_SECTIONS = ['### Execution des lots', '### Batch execution']
47const PLAN_DONE = /^### (?:Lot|Batch) (F\d+)\b.*✅ DONE/gm
48const PLAN_HEADING = /^### (?:Lot|Batch) (F\d+) — (.+?)(?:\s+(?:—\s+)?(?:✅ DONE.*|⬜))?\s*$/gm
49const REPORT_STATUS = /^## (?:STATUT|STATUS) — (\S+)/
50const LOT_DONE = ['TERMINÉ', 'DONE']
51const WAITING_TONE = 'cyan'
52const WAVE_LABEL = /^RED \S+ w(\d+)\b/
53const REPORT_PHASE = 'Report'
54const CYCLES_SECTION = '## Cycles'
55const PANE_FILE = '.pane.jsonl'
56const FEED_KINDS = ['question', 'answer', 'audit-round', 'attempt', 'breaker', 'ack', 'journal']
57const STEP_PHASES = ['Global green', 'Closing']
58const ASIDE_LINE = /^(F\d+) ✗ — set aside — (.*?)(?: — patch (\S+))?$/
59// A section heading and its French aliases (docs/FROZEN-LITERALS.md § French aliases).
60const TO_VALIDATE = ['## To validate', '## À valider']
61const KEPT_SECTIONS = [TO_VALIDATE, ['## Plan stopped']]
62
63type Launched = { status?: string; runId?: string; scriptPath?: string; workflowName?: string; transcriptDir?: string }
64
65const runs = atom({ plugin: 'run-lot-pane', key: 'runs' } as const, [] as WorkflowRun[])
66const now = atom({ plugin: 'run-lot-pane', key: 'now' } as const, 0)
67const HOME: Navigation = { screen: 'run', phase: null, agentId: null, back: 'run', toggled: [], lot: null }
68const nav = atom({ plugin: 'run-lot-pane', key: 'nav' } as const, HOME)
69const isShown = atom({ plugin: 'run-lot-pane', key: 'isShown' } as const, false)
70const usage = atom({ plugin: 'run-lot-pane', key: 'usage' } as const, { context: null, percent: null } as SessionFigures)
71const history = atom({ plugin: 'run-lot-pane', key: 'history' } as const, {} as PhaseSamples)
72const feed = atom({ plugin: 'run-lot-pane', key: 'feed' } as const, null as RunFeed | null)
73
74export const duration = (ms: number): string => {
75 const seconds = Math.max(0, Math.round(ms / 1000))
76 const minutes = Math.floor(seconds / 60)
77 if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, '0')}`
78 return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}`
79}
80
81const SPINNER = ['✢', '✳', '✶', '✻', '✽', '✻', '✶', '✳']
82
83export const spinnerFrame = (at: number): string => SPINNER[Math.floor(at / TICK_MS) % SPINNER.length] ?? '✻'
84
85export const statusTone = (status: RunStatus): 'claude' | 'success' | 'error' | 'warning' =>
86 status === 'running' ? 'claude' : status === 'completed' ? 'success' : status === 'killed' ? 'warning' : 'error'
87
88export const statusGlyph = (status: RunStatus): string =>
89 status === 'running' ? '⏺' : status === 'completed' ? '✓' : status === 'killed' ? '⏹' : '✗'
90
91const USER_WAITING = ['BLOQUÉ', 'BLOCKED']
92
93export const headlineOf = (status: RunStatus, outcome: Outcome | null, asking = 0): { glyph: string; text: string; tone: string } =>
94 (status === 'running' && asking > 0) || (status !== 'running' && outcome !== null && USER_WAITING.includes(outcome.label))
95 ? { glyph: '?', text: 'waiting for user', tone: WAITING_TONE }
96 : { glyph: statusGlyph(status), text: status, tone: statusTone(status) }
97
98export const progressBar =(reached: number, total: number, width: number) => {
99 const filled = total === 0 ? 0 : Math.round((Math.min(reached, total) / total) * width)
100 return [
101 { key: 'filled', text: '━'.repeat(filled), isFilled: true },
102 { key: 'rest', text: '─'.repeat(width - filled), isFilled: false },
103 ]
104}
105
106// The pane's rows are laid out for a terminal, where leading spaces indent a row under its parent and `⎿` hangs
107// a detail. In the desktop's proportional face those spaces shrink to slivers and the hierarchy blurs: there each
108// indent becomes a padding of as many cells, a spacer Text a Box as wide, and the `⎿` goes. The terminal's first
109// level, two spaces under a title, is dropped: on a desktop a block's surface groups its rows, so they align with
110// its title and a nested row keeps only what sets it under its parent.
111type Tree = { type: string; props: Record<string, unknown>; children?: unknown[] }
112const isTree = (node: unknown): node is Tree => typeof node === 'object' && node !== null && 'type' in node && 'props' in node
113const INDENT_MIN = 2
114const INDENT_BASE = 2
115const isNothing = (node: unknown) => node === null || node === undefined || node === false || node === ''
116
117const leadOf = (node: unknown): { node: unknown; spaces: number } => {
118 if (typeof node === 'string') {
119 const found = /^( *)(?:⎿ ?)?/.exec(node)
120 return { node: node.slice(found?.[0].length ?? 0), spaces: found?.[1]?.length ?? 0 }
121 }
122 if (!isTree(node) || node.type !== 'Text') return { node, spaces: 0 }
123 const children = [...(node.children ?? [])].flat()
124 let spaces = 0
125 while (children.length > 0) {
126 if (isNothing(children[0])) {
127 children.shift()
128 continue
129 }
130 const inner = leadOf(children[0])
131 spaces += inner.spaces
132 const isEmptied = inner.node === '' || (isTree(inner.node) && inner.node.type === 'Text' && (inner.node.children ?? []).flat().every(isNothing))
133 if (isEmptied && inner.spaces > 0) {
134 children.shift()
135 continue
136 }
137 children[0] = inner.node
138 break
139 }
140 return { node: { ...node, children }, spaces }
141}
142
143const polish = (node: unknown, inBox: boolean): unknown => {
144 if (Array.isArray(node)) return node.map(one => polish(one, inBox)).filter(one => one !== null)
145 if (!isTree(node)) return node
146 if (node.type === 'Text') {
147 const { node: stripped, spaces } = leadOf(node)
148 if (spaces < INDENT_MIN) return node
149 const pad = spaces - INDENT_BASE
150 const isBlank = isTree(stripped) && (stripped.children ?? []).flat().every(isNothing)
151 if (isBlank && inBox) return pad === 0 ? null : { type: 'Box', props: { width: pad, flexShrink: 0 }, children: [] }
152 if (!inBox || pad === 0) return stripped
153 return { type: 'Box', props: { paddingLeft: pad, flexShrink: 1, minWidth: 0 }, children: [stripped] }
154 }
155 // A one-cell height clips a desktop line, taller than a cell: the rows overlap. There it is a floor instead.
156 const props = node.type === 'Box' && node.props.height === 1 ? { ...withoutHeight(node.props), minHeight: 1 } : node.props
157 return node.children === undefined ? { ...node, props } : { ...node, props, children: node.children.map(one => polish(one, node.type === 'Box')).filter(one => one !== null) }
158}
159
160const withoutHeight = ({ height: _, ...rest }: Record<string, unknown>) => rest
161
162export const desktopTree = (surface: string, tree: JSX.Element): JSX.Element => (surface === 'desktop' ? (polish(tree, false) as JSX.Element) : tree)
163
164// The desktop's progress bar: drawn, in the hex of the tone a terminal names, since an SVG reads no theme key.
165const METER = { width: 180, height: 6 } as const
166const INKS: Record<string, string> = {
167 claude: '#d97757',
168 success: '#3fa66b',
169 warning: '#d99a1e',
170 error: '#d64545',
171 cyan: '#2fa3b8',
172}
173export const inkOf = (tone: string): string => INKS[tone] ?? '#8a8f98'
174// The desktop sets its blocks apart by shade, not by line: a translucent grey surface reads on a light or a dark
175// theme alike, and a row that asks for attention (running, failed, waiting) takes a faint wash of its tone.
176const SURFACE = '#80808014'
177const WASH: Record<string, string> = {
178 claude: '#d977571f',
179 error: '#d6454524',
180 warning: '#d99a1e24',
181 cyan: '#2fa3b824',
182}
183export const washOf = (tone: string | undefined): string | undefined => (tone === undefined ? undefined : WASH[tone])
184export const meterSource = (share: number, ink: string): string => {
185 const { width, height } = METER
186 const filled = Math.round(Math.min(1, Math.max(0, share)) * width)
187 const radius = height / 2
188 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
189 + `<rect width="${width}" height="${height}" rx="${radius}" fill="${ink}" fill-opacity="0.18"/>`
190 + (filled > 0 ? `<rect width="${Math.max(filled, height)}" height="${height}" rx="${radius}" fill="${ink}"/>` : '')
191 + '</svg>'
192}
193
194export const kilo = (tokens: number): string => {
195 if (tokens >= 1_000_000) return `${Number((tokens / 1_000_000).toFixed(1))}M`
196 if (tokens >= 1000) return `${Math.round(tokens / 1000)}k`
197 return `${tokens}`
198}
199
200export const coarse = (ms: number): string => {
201 const minutes = Math.max(1, Math.round(ms / 60_000))
202 return minutes < 60 ? `${minutes}m` : `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}`
203}
204
205export const promptTokens = (used: ModelUsage): number =>
206 used.input_tokens + used.cache_read_input_tokens + used.cache_creation_input_tokens
207
208export type Totals = { context: number; tokens: number }
209
210export const totalsOf = (agents: WorkflowAgent[]): Totals => {
211 const running = agents.filter(agent => agent.state === 'running')
212 return {
213 context: Math.max(0, ...(running.length > 0 ? running : agents).map(agent => agent.context)),
214 tokens: agents.reduce((sum, agent) => sum + agent.tokens, 0),
215 }
216}
217
218export const lotFiguresOf = (agents: WorkflowAgent[]): LotFigures | null => {
219 if (agents.length === 0) return null
220 const startedAt = Math.min(...agents.map(agent => agent.startedAt))
221 const endedAt = Math.max(...agents.map(agent => agent.endedAt ?? agent.lastActiveAt))
222 const totals = totalsOf(agents)
223 return { agents: agents.length, durationMs: endedAt - startedAt, tokens: totals.tokens, endedAt }
224}
225
226// A resumed plan: the time its batches finished by an earlier run took, this run's time excluded.
227export const earlierMsOf = (run: WorkflowRun): number =>
228 run.lots.reduce((sum, entry) => (entry.past && !run.agents.some(agent => agent.lot === entry.lot) ? sum + entry.past.durationMs : sum), 0)
229
230export const lotFiguresFrom = (value: unknown): LotFigures | null => {
231 if (typeof value !== 'object' || value === null) return null
232 const fields = value as Record<string, unknown>
233 return ['agents', 'durationMs', 'tokens', 'endedAt'].every(key => typeof fields[key] === 'number') ? (fields as LotFigures) : null
234}
235
236export const figuresKeyOf = (transcriptDir: string | null, sheet: string | null): string | null => {
237 const found = lotOf(sheet)
238 if (found === null) return null
239 const project = /[\\/]projects[\\/]([^\\/]+)[\\/]/.exec(transcriptDir ?? '')?.[1] ?? ''
240 return `lot:${project}:${found.code}-${found.lot}`
241}
242
243export const figuresLine = (totals: Totals): string =>
244 `ctx ${kilo(totals.context)} · ${kilo(totals.tokens)} tok`
245
246export const firstLine = (text: string, length = 160): string => {
247 const line = (text.split('\n').find(one => one.trim() !== '') ?? '').trim()
248 return line.length > length ? `${line.slice(0, length - 1)}…` : line
249}
250
251export const toolSummary = (counts: Record<string, number>): string =>
252 Object.entries(counts)
253 .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
254 .map(([tool, count]) => `${tool} ${count}`)
255 .join(' · ')
256
257// On Windows the engine's paths come as `C:\x\repo\…`, git's and the kit's as `C:/x/repo/…`: paths are
258// compared with `/`, the drive's case aside, and a drive path is shown with `/`.
259const slashed = (path: string): string => path.replace(/\\/g, '/')
260const isDrive = (path: string): boolean => /^[A-Za-z]:/.test(path)
261export const isAbsolutePath = (path: string): boolean => /^(?:[A-Za-z]:)?[\\/]/.test(path)
262export const samePath = (a: string, b: string): boolean => {
263 const [one, two] = [slashed(a).replace(/\/$/, ''), slashed(b).replace(/\/$/, '')]
264 return isDrive(one) ? one.toLowerCase() === two.toLowerCase() : one === two
265}
266const lastSeparator = (path: string): number => Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
267
268export const relativePath = (path: string, root: string | null): string => {
269 if (root === null) return path
270 const [file, base] = [slashed(path), slashed(root).replace(/\/$/, '')]
271 const cased = (one: string): string => (isDrive(base) ? one.toLowerCase() : one)
272 return cased(file).startsWith(`${cased(base)}/`) ? file.slice(base.length + 1) : path
273}
274
275const EDITING_TOOLS = ['Edit', 'Write', 'NotebookEdit']
276const KEPT_FILES = 12
277
278export const editedPath = (tool: string, input: Record<string, unknown>): string | null => {
279 if (!EDITING_TOOLS.includes(tool)) return null
280 const path = input.file_path ?? input.notebook_path
281 return typeof path === 'string' && path !== '' ? path : null
282}
283
284export const withFile = (files: string[], path: string): string[] =>
285 [...files.filter(one => one !== path), path].slice(-KEPT_FILES)
286
287const KEPT_CALLS = 300
288const RESERVED_KEYS = ['tool', 'tool_use_id', 'consent', 'agentId', 'requestMeta']
289
290const ownFields = (input: Record<string, unknown>): [string, unknown][] =>
291 Object.entries(input).filter(([key]) => !RESERVED_KEYS.includes(key))
292
293export const callBrief = (tool: string, input: Record<string, unknown>, root: string | null): string => {
294 const text = (key: string) => textOf(input[key])
295 const path = (key: string) => {
296 const found = text(key)
297 return found === null ? null : relativePath(found, root)
298 }
299 if (tool === 'Bash') return firstLine(text('description') ?? text('command') ?? '', 120)
300 if (tool === 'Read' || tool === 'Edit' || tool === 'Write') return path('file_path') ?? ''
301 if (tool === 'NotebookEdit') return path('notebook_path') ?? ''
302 if (tool === 'Grep') return [text('pattern'), path('path') ?? text('glob')].filter(part => part !== null).join(' in ')
303 if (tool === 'StructuredOutput') return ''
304 const first = ownFields(input).map(([, value]) => textOf(value)).find(value => value !== null)
305 return first === undefined || first === null ? '' : firstLine(first, 120)
306}
307
308const EXIT_LINE = /^Exit code (\d+)$/
309
310export const errorDetail = (result: { deny?: string; isError?: boolean; text?: string }): string | null => {
311 if (typeof result.deny === 'string') return `denied · ${firstLine(result.deny, 200)}`
312 if (result.isError !== true) return null
313 const lines = (result.text ?? '').split('\n').map(one => one.trim()).filter(one => one !== '')
314 const exit = lines.map(one => EXIT_LINE.exec(one)?.[1]).find(code => code !== undefined)
315 const detail = lines.filter(one => !EXIT_LINE.test(one)).pop()
316 const parts = [exit === undefined ? null : `exit ${exit}`, detail === undefined ? null : firstLine(detail, 200)].filter(part => part !== null)
317 return parts.length === 0 ? 'error' : parts.join(' · ')
318}
319
320export const errorOf = (tool: string, result: { deny?: string; isError?: boolean; text?: string }, brief = ''): string | null => {
321 const detail = errorDetail(result)
322 return detail === null ? null : `${brief === '' ? tool : `${tool} · ${brief}`}: ${detail}`
323}
324
325export const withCall = (calls: ToolTrace[], trace: ToolTrace): ToolTrace[] => [...calls, trace].slice(-KEPT_CALLS)
326
327export const closedCall = (calls: ToolTrace[], id: string, error: string | null): ToolTrace[] =>
328 calls.map(call => (call.id === id ? { ...call, state: error === null ? 'ok' : 'error', error } : call))
329
330export type ErrorSummary = { count: number; last: ToolTrace | null; isRecovered: boolean }
331
332export const errorsOf = (agent: WorkflowAgent): ErrorSummary => {
333 const failed = agent.calls.filter(call => call.state === 'error')
334 const last = failed[failed.length - 1] ?? null
335 if (last === null) return { count: 0, last: null, isRecovered: true }
336 const after = agent.calls.slice(agent.calls.indexOf(last) + 1)
337 return { count: failed.length, last, isRecovered: agent.state !== 'error' && after.some(call => call.state === 'ok') }
338}
339
340const KEPT_ANSWER_LINES = 20
341const ITEM_KEYS = ['gap', 'question', 'behaviour', 'title', 'summary', 'name', 'path']
342
343const itemLine = (item: unknown): string => {
344 if (item === null || typeof item !== 'object') return firstLine(String(item), 200)
345 const fields = item as Record<string, unknown>
346 const head = [textOf(fields.severity), textOf(fields.axis)].filter(part => part !== null)
347 const body = ITEM_KEYS.map(key => textOf(fields[key])).find(value => value !== null) ?? Object.values(fields).map(textOf).find(value => value !== null) ?? '…'
348 return [...head, firstLine(body, 200)].join(' · ')
349}
350
351export const structuredLines = (value: unknown): string[] | null => {
352 if (value === null || typeof value !== 'object' || Array.isArray(value)) return null
353 const audit = auditOf(value)
354 const lines = audit === null ? [] : [auditLabel(audit)]
355 for (const [key, field] of ownFields(value as Record<string, unknown>)) {
356 if (audit !== null && key === 'verdict') continue
357 if (Array.isArray(field)) {
358 lines.push(field.length === 0 ? `${key}: none` : `${key} · ${field.length}`)
359 lines.push(...field.map(item => ` ${itemLine(item)}`))
360 } else if (field !== null && typeof field === 'object') {
361 lines.push(`${key}: {…}`)
362 } else if (field !== null && field !== undefined && String(field).trim() !== '') {
363 lines.push(`${key}: ${firstLine(String(field), 200)}`)
364 }
365 }
366 if (lines.length === 0) return null
367 return lines.length > KEPT_ANSWER_LINES
368 ? [...lines.slice(0, KEPT_ANSWER_LINES - 1), `… ${lines.length - KEPT_ANSWER_LINES + 1} more lines`]
369 : lines
370}
371
372const KEPT_PROMPT_LINES = 6
373
374export const promptBrief = (prompt: string): string => {
375 const trimmed = prompt.trim()
376 const split = trimmed.indexOf('\n\n')
377 const body = /^Workflow run-/.test(trimmed) && split >= 0 ? trimmed.slice(split).trim() : trimmed
378 return body
379 .split('\n')
380 .map(one => one.trim())
381 .filter(one => one !== '')
382 .slice(0, KEPT_PROMPT_LINES)
383 .map(one => firstLine(one, 300))
384 .join('\n')
385}
386
387export const clockOf = (ms: number): string => {
388 const seconds = Math.max(0, Math.round(ms / 1000))
389 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
390}
391
392export type PhaseInsight = { totals: Totals; share: number | null; heaviest: string | null; slowest: string | null }
393
394export const phaseInsight = (phase: PhaseRow, run: WorkflowRun, at: number): PhaseInsight => {
395 const totals = totalsOf(phase.agents)
396 const runTokens = totalsOf(run.agents).tokens
397 const top = (score: (agent: WorkflowAgent) => number): string | null =>
398 phase.agents.length < 2 ? null : ([...phase.agents].sort((a, b) => score(b) - score(a))[0]?.id ?? null)
399 return {
400 totals,
401 share: runTokens > 0 ? Math.round((totals.tokens / runTokens) * 100) : null,
402 heaviest: totals.tokens > 0 ? top(agent => agent.tokens) : null,
403 slowest: top(agent => (agent.endedAt ?? at) - agent.startedAt),
404 }
405}
406
407export const shortModel = (model: string): string => {
408 const family = /(opus|sonnet|haiku|fable)/i.exec(model)?.[1]
409 if (family === undefined) return model.replace(/^claude-/, '').replace(/-\d{8}$/, '')
410 return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()}`
411}
412
413export const modelLabel = (agent: WorkflowAgent): string =>
414 agent.effort === null ? agent.model : `${agent.model} · ${agent.effort}`
415
416const phasesBlock = (script: string): string => {
417 const start = script.search(/\bphases\s*:\s*\[/)
418 if (start < 0) return ''
419 const open = script.indexOf('[', start)
420 let depth = 0
421 let quote = ''
422 for (let index = open; index < script.length; index++) {
423 const char = script.charAt(index)
424 if (quote !== '') {
425 if (char === '\\') index++
426 else if (char === quote) quote = ''
427 } else if (char === "'" || char === '"' || char === '`') quote = char
428 else if (char === '[') depth++
429 else if (char === ']' && --depth === 0) return script.slice(open, index)
430 }
431 return script.slice(open)
432}
433
434export const parsePhases = (script: string): PhaseDeclaration[] => {
435 const block = phasesBlock(script)
436 const titles = [...block.matchAll(/\btitle\s*:\s*(['"`])((?:(?!\1).)+)\1/g)]
437 return titles.flatMap((found, index) => {
438 const title = found[2]
439 if (title === undefined) return []
440 const segment = block.slice(found.index, titles[index + 1]?.index)
441 const detail = /\bdetail\s*:\s*(['"`])((?:(?!\1).)+)\1/.exec(segment)?.[2] ?? null
442 return [{ title, detail }]
443 })
444}
445
446export const detailsOf = (phases: PhaseDeclaration[]): Record<string, string> =>
447 Object.fromEntries(phases.flatMap(phase => (phase.detail === null ? [] : [[phase.title, phase.detail]])))
448
449const OPENERS: Record<string, string> = { "'": "'", '"': '"', '`': '`', '{': '}', '(': ')', '[': ']' }
450
451const closingOf = (text: string, from: number): number => {
452 const open = text[from] ?? ''
453 const close = OPENERS[open]
454 let at = from + 1
455 while (at < text.length && text[at] !== close) {
456 const char = text[at] ?? ''
457 if (char === '\\') at += 1
458 else if (open === '`' && text.startsWith('${', at)) at = closingOf(text, at + 1)
459 else if (open !== "'" && open !== '"' && open !== '`' && char in OPENERS) at = closingOf(text, at)
460 at += 1
461 }
462 return at
463}
464
465const branchesOf = (expression: string): string[] | null => {
466 let question = -1
467 let nested = 0
468 for (let at = 0; at < expression.length; at++) {
469 const char = expression[at] ?? ''
470 if (char in OPENERS) {
471 at = closingOf(expression, at)
472 continue
473 }
474 const isTernary = char === '?' && expression[at + 1] !== '.' && expression[at + 1] !== '?' && expression[at - 1] !== '?'
475 if (isTernary && question < 0) question = at
476 else if (isTernary) nested += 1
477 else if (char === ':' && question >= 0 && nested > 0) nested -= 1
478 else if (char === ':' && question >= 0) return [expression.slice(question + 1, at), expression.slice(at + 1)]
479 }
480 return null
481}
482
483const literalPrefixesOf = (expression: string): string[] => {
484 const text = expression.trim()
485 const branches = branchesOf(text)
486 if (branches !== null) return branches.flatMap(literalPrefixesOf)
487 const quote = text[0] ?? ''
488 if (quote !== "'" && quote !== '"' && quote !== '`') return []
489 const body = text.slice(1, closingOf(text, 0))
490 const head = quote === '`' ? (body.split('${')[0] ?? '') : body
491 if (head !== '') return [head]
492 return quote === '`' && body.startsWith('${') ? literalPrefixesOf(text.slice(3, closingOf(text, 2))) : []
493}
494
495const forwardedValuesOf = (script: string, lines: string[], at: number, parameter: string): string[] => {
496 const owner = lines
497 .slice(0, at + 1)
498 .reverse()
499 .map(text => /\bfunction\s+(\w+)\s*\(([^)]*)\)|\bconst\s+(\w+)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/.exec(text))
500 .find(found => found !== null)
501 const name = owner?.[1] ?? owner?.[3]
502 const parameters = (owner?.[2] ?? owner?.[4] ?? '').split(',').map(one => one.trim().split(/\s*=/)[0])
503 const position = parameters.indexOf(parameter)
504 if (name === undefined || position < 0) return []
505 return [...script.matchAll(new RegExp(`(?<![\\w.])${name}\\(([^)]*)\\)`, 'g'))].flatMap(call =>
506 literalPrefixesOf((call[1] ?? '').split(',')[position] ?? ''),
507 )
508}
509
510const calledPrefixesOf = (script: string, expression: string): string[] => {
511 const name = /^\s*(\w+)\s*\(/.exec(expression)?.[1]
512 if (name === undefined) return []
513 const definition = new RegExp(
514 `\\b(?:const|let)\\s+${name}\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>\\s*|\\bfunction\\s+${name}\\s*\\([^)]*\\)\\s*\\{\\s*return\\s+`,
515 ).exec(script)
516 if (definition === null) return []
517 const body = script.slice(definition.index + definition[0].length)
518 return (body[0] ?? '') in OPENERS ? literalPrefixesOf(body.slice(0, closingOf(body, 0) + 1)) : []
519}
520
521const labelPrefixesOf = (script: string, expression: string): string[] => {
522 const literal = literalPrefixesOf(expression)
523 return literal.length > 0 ? literal : calledPrefixesOf(script, expression)
524}
525
526const optionOf = (text: string, key: string): string | null => {
527 const start = text.search(new RegExp(`\\b${key}\\s*:`))
528 return start < 0 ? null : (text.slice(start).replace(new RegExp(`^${key}\\s*:`), '').split(/,\s*\w+\s*:/)[0] ?? '')
529}
530
531const identifierOf = (expression: string): string | null => /^\s*(\w+)\s*}?\s*$/.exec(expression)?.[1] ?? null
532
533const literalOf = (expression: string): string | null => /^\s*(['"`])((?:(?!\1).)+)\1/.exec(expression)?.[2] ?? null
534
535const phasesOf = (script: string, lines: string[], at: number, expression: string): string[] => {
536 const branches = branchesOf(expression.trim())
537 if (branches !== null) {
538 const phases = branches.map(literalOf)
539 return phases.every((one): one is string => one !== null) ? phases : []
540 }
541 const literal = literalOf(expression)
542 if (literal !== null) return [literal]
543 const parameter = identifierOf(expression)
544 const forwarded = parameter === null ? [] : [...new Set(forwardedValuesOf(script, lines, at, parameter))]
545 return forwarded.length === 1 ? forwarded : []
546}
547
548export const labelPhasesOf = (script: string): Record<string, string> => {
549 const lines = script.split('\n')
550 return Object.fromEntries(
551 lines.flatMap((text, at) => {
552 const phaseExpression = optionOf(text, 'phase')
553 const phases = phaseExpression === null ? [] : phasesOf(script, lines, at, phaseExpression)
554 if (phases.length === 0) return []
555 const expression = optionOf(text, 'label')
556 const forwarded = expression === null ? (/\blabel\s*[,}]/.test(text) ? 'label' : null) : identifierOf(expression)
557 if (phases.length > 1) {
558 const branches = expression === null || forwarded !== null ? null : branchesOf(expression.trim())
559 if (branches === null || branches.length !== phases.length) return []
560 return branches.flatMap((branch, index) => labelPrefixesOf(script, branch).map(label => [label, phases[index] ?? '']))
561 }
562 const labels = forwarded !== null ? forwardedValuesOf(script, lines, at, forwarded) : labelPrefixesOf(script, expression ?? '')
563 return labels.map(label => [label, phases[0] ?? ''])
564 }),
565 )
566}
567
568const labelledPhaseOf = (labels: Record<string, string>, label: string, phase: string | null): string | null => {
569 if (phase !== null && !phase.startsWith('▸ ')) return phase
570 const prefix = Object.keys(labels)
571 .filter(one => label.startsWith(one))
572 .sort((a, b) => b.length - a.length)[0]
573 return prefix === undefined ? phase : (labels[prefix] ?? phase)
574}
575
576export const nestedPhaseOf = (child: ChildWorkflow | null, label: string, phase: string | null): string | null =>
577 child === null ? phase : labelledPhaseOf(child.labels ?? {}, label, phase)
578
579export const journalPathOf =(transcriptDir: string, runId: string): string =>
580 transcriptDir.replace(new RegExp(`([\\\\/])subagents[\\\\/]workflows[\\\\/]${runId}[\\\\/]?$`), `$1workflows$1${runId}.json`)
581
582const STATUSES: RunStatus[] = ['completed', 'failed', 'killed']
583
584const jsonOf = (text: string): unknown => {
585 try {
586 return JSON.parse(text)
587 } catch {
588 return null
589 }
590}
591
592const textOf = (value: unknown): string | null => (typeof value === 'string' && value.trim() !== '' ? value.trim() : null)
593
594export const argumentOf = (input: Record<string, unknown>): string | null => {
595 const given = input.args
596 if (typeof given === 'object' && given !== null) {
597 const fields = given as Record<string, unknown>
598 return textOf(fields.sheet) ?? textOf(fields.plan)
599 }
600 return textOf(given)
601}
602
603export const lotOf = (argument: string | null): { lot: string; code: string } | null => {
604 const found = argument === null ? null : LOT_PATTERN.exec(argument)
605 return found?.[1] === undefined || found[2] === undefined ? null : { lot: found[2], code: found[1] }
606}
607
608export const sheetPathOf = (argument: string | null): string | null =>
609 argument !== null && SHEET_PATTERN.test(argument) ? argument : null
610
611export const childWorkflowOf = (script: string): string | null => {
612 const found = CHILD_CALL.exec(script)
613 return found?.[1] ?? found?.[2] ?? null
614}
615
616export const childPluginOf = (script: string): string | null => CHILD_PLUGIN.exec(script)?.[1] ?? null
617
618export const claudeHomeOf = (path: string | null | undefined): string | null => {
619 const at = path?.search(/[\\/]projects[\\/]/) ?? -1
620 return at > 0 ? path!.slice(0, at) : null
621}
622
623type Installed = { scope?: string; projectPath?: string; installPath?: string }
624
625export const installPathOf = (installed: string, plugin: string, root: string): string | null => {
626 try {
627 const plugins = (JSON.parse(installed) as { plugins?: Record<string, Installed[]> }).plugins ?? {}
628 const entries = Object.entries(plugins)
629 .filter(([key]) => key.startsWith(`${plugin}@`))
630 .flatMap(([, list]) => list)
631 const chosen = entries.find(one => typeof one.projectPath === 'string' && samePath(one.projectPath, root)) ?? entries.find(one => one.scope === 'user')
632 return chosen?.installPath ?? null
633 } catch {
634 return null
635 }
636}
637
638export const childScriptPathsOf = (name: string, root: string, installPath: string | null): string[] => [
639 ...(installPath === null ? [] : [`${installPath}/workflows/${name}.js`]),
640 `${root}/.claude/workflows/${name}.js`,
641]
642
643export const planPathOf = (argument: string | null): string | null => {
644 const path = argument?.trim().split(/\s+/)[0] ?? ''
645 return /-PLAN\.md$/.test(path) ? path.replace(/^@/, '') : null
646}
647
648export const promptLotOf = (prompt: string): { lot: string; sheet: string } | null => {
649 const framed = PROMPT_LOT.exec(prompt)
650 if (framed?.[1] !== undefined && framed[2] !== undefined) return { lot: framed[1], sheet: framed[2] }
651 const review = REVIEW_LOT.exec(prompt)
652 return review?.[1] !== undefined && review[2] !== undefined ? { lot: review[2], sheet: review[1] } : null
653}
654
655const blankLot = (lot: string): PlanLot => ({ lot, sheet: null, deps: [], isDone: false, outcome: null, audit: null, view: null })
656
657const cellsOf = (line: string): string[] =>
658 line
659 .trim()
660 .replace(/^\||\|$/g, '')
661 .split('|')
662 .map(cell => cell.trim())
663
664export const parsePlanLots = (text: string): PlanLot[] => {
665 const lines = text.split('\n')
666 const start = lines.findIndex(line => PLAN_SECTIONS.includes(line.trim()))
667 if (start < 0) return []
668 const table: string[] = []
669 for (const line of lines.slice(start + 1)) {
670 if (line.startsWith('|')) table.push(line)
671 else if (table.length > 0 || line.startsWith('#')) break
672 }
673 const header = cellsOf(table[0] ?? '').map(cell => cell.toLowerCase())
674 const lotAt = Math.max(header.indexOf('lot'), header.indexOf('batch'))
675 const depsAt = Math.max(header.indexOf('depend de'), header.indexOf('depends on'))
676 if (lotAt < 0) return []
677 const done = new Set([...text.matchAll(PLAN_DONE)].map(found => found[1]))
678 const titles = Object.fromEntries([...text.matchAll(PLAN_HEADING)].map(found => [found[1] ?? '', found[2] ?? '']))
679 return table.slice(2).flatMap(line => {
680 const cells = cellsOf(line)
681 const lot = /F\d+/.exec(cells[lotAt] ?? '')?.[0]
682 if (lot === undefined) return []
683 const deps = depsAt < 0 ? [] : ((cells[depsAt] ?? '').match(/F\d+/g) ?? [])
684 const title = titles[lot]
685 return [{ ...blankLot(lot), deps, isDone: done.has(lot), ...(title === undefined || title === '' ? {} : { title }) }]
686 })
687}
688
689export const mergeLots = (known: PlanLot[], planned: PlanLot[]): PlanLot[] => [
690 ...planned.map(one => {
691 const seen = known.find(other => other.lot === one.lot)
692 return seen === undefined ? one : { ...seen, deps: one.deps, isDone: one.isDone, ...(one.title === undefined ? {} : { title: one.title }) }
693 }),
694 ...known.filter(other => !planned.some(one => one.lot === other.lot)),
695]
696
697export const withLot = (lots: PlanLot[], lot: string, change: (one: PlanLot) => PlanLot): PlanLot[] =>
698 lots.some(one => one.lot === lot) ? lots.map(one => (one.lot === lot ? change(one) : one)) : [...lots, change(blankLot(lot))]
699
700const runRootOf = (sheet: string): string => `${sheet.slice(0, lastSeparator(sheet) + 1)}run`
701
702export const reportPathsOf = (sheet: string, lot: string): string[] => [`${runRootOf(sheet)}/batches/${lot}.md`]
703
704export const workFileOf = (sheet: string): string => `${runRootOf(sheet)}/.work.jsonl`
705
706type WorkLine = { kind?: unknown; batch?: unknown; id?: unknown; slug?: unknown; state?: unknown }
707
708export const workLinesOf = (text: string): WorkLine[] =>
709 text.split('\n').flatMap(line => {
710 const record = jsonOf(line)
711 return typeof record === 'object' && record !== null && !Array.isArray(record) ? [record as WorkLine] : []
712 })
713
714export const cycleStatesOf = (lines: WorkLine[], lot: string): Record<string, string> =>
715 Object.fromEntries(
716 lines.flatMap(line => (line.kind === 'cycle' && line.batch === lot && typeof line.slug === 'string' ? [[line.slug, JSON.stringify(line.state ?? null)]] : [])),
717 )
718
719
720export type PendingQuestion = { batch: string; id: string; count: number; endsAt: number }
721
722const numberOf = (value: unknown): number | null => (typeof value === 'number' && Number.isFinite(value) ? value : null)
723
724// A question waits `waitSeconds` before the run applies its
725// recommendation; an answer line of the same id, written at or after it, answers it.
726export const openQuestionsOf = (lines: WorkLine[]): PendingQuestion[] => {
727 const records = lines as Record<string, unknown>[]
728 return records.flatMap(line => {
729 if (line.kind !== 'question') return []
730 const at = numberOf(line.at) ?? 0
731 if (records.some(other => other.kind === 'answer' && String(other.id) === String(line.id) && (numberOf(other.at) ?? Infinity) >= at)) return []
732 const payload = fieldsOf(line.payload)
733 const asked = Array.isArray(payload?.questions) ? payload.questions.length : 1
734 return [{ batch: String(line.batch ?? payload?.batch ?? ''), id: String(line.id), count: Math.max(1, asked), endsAt: (at + (numberOf(payload?.waitSeconds) ?? 0)) * 1000 }]
735 })
736}
737
738export const pendingQuestionsOf = (lines: WorkLine[], lot: string): string[] => openQuestionsOf(lines).filter(one => one.batch === lot).map(one => one.id)
739
740export const reportOutcomeOf = (text: string, path: string): Outcome | null => {
741 const status = REPORT_STATUS.exec(text.split('\n')[0] ?? '')?.[1]
742 if (status === undefined) return null
743 const reason = /^(?:Raison|Reason)\s*:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? null
744 return { label: status, reason: reason === null || reason === '—' ? null : reason, report: path }
745}
746
747export type LotState = RunStatus | 'pending' | 'done' | 'waiting'
748
749export type Wave = { wave: number; total: number }
750
751export const waveOf = (run: WorkflowRun): Wave | null => {
752 const seen = run.agents.flatMap(agent => {
753 const found = WAVE_LABEL.exec(agent.label)?.[1]
754 return found === undefined ? [] : [Number(found)]
755 })
756 if (seen.length === 0) return null
757 const wave = Math.max(...seen)
758 const indexed = Math.max(0, ...(run.sheet?.cycles ?? []).map(cycle => cycle.wave))
759 return { wave, total: Math.max(wave, indexed) }
760}
761
762export const lotStateOf = (run: WorkflowRun, entry: PlanLot): LotState => {
763 const agents = run.agents.filter(agent => agent.lot === entry.lot)
764 if ((entry.asking ?? 0) > 0 && entry.outcome === null) return 'waiting'
765 if (entry.outcome !== null && USER_WAITING.includes(entry.outcome.label)) {
766 return agents.some(agent => agent.state === 'running') ? 'running' : 'waiting'
767 }
768 if (entry.outcome !== null) return LOT_DONE.includes(entry.outcome.label) ? 'completed' : 'failed'
769 if (agents.length === 0) return entry.isDone ? 'done' : 'pending'
770 if (agents.some(agent => agent.state === 'running')) return 'running'
771 const latest = [...run.agents].filter(agent => agent.lot !== null).sort((a, b) => b.index - a.index)[0]?.lot
772 if (latest !== entry.lot) return 'completed'
773 return run.status
774}
775
776export const lotDetailOf = (run: WorkflowRun, entry: PlanLot, state: LotState, at: number): string => {
777 if (entry.outcome !== null) return [entry.outcome.label, oneLine(entry.outcome.reason ?? '')].filter(one => one !== '').join(' · ')
778 if (state === 'running') {
779 const active = [...run.agents]
780 .filter(agent => agent.lot === entry.lot && agent.state === 'running')
781 .sort((a, b) => b.index - a.index)[0]
782 if (active !== undefined) return `${active.phase ?? NO_PHASE} · ${active.label}`
783 const rows = phaseRows(lotRun(run, entry.lot), at)
784 const reached = rows.map(row => row.mark !== 'pending').lastIndexOf(true)
785 const step = rows.slice(reached + 1).find(row => !CONDITIONAL_PHASES.includes(row.title))
786 return step === undefined ? 'running' : step.title
787 }
788 if (state === 'waiting') return 'question awaiting an answer'
789 if (state === 'done') return 'done before this run'
790 if (state === 'pending') return entry.deps.length > 0 ? `after ${entry.deps.join(', ')}` : 'pending'
791 return state
792}
793
794export const placedInPhases = (agents: WorkflowAgent[], phases: string[]): WorkflowAgent[] => {
795 if (phases.length === 0) return agents
796 let previous = phases[0] ?? null
797 const placed = new Map(
798 [...agents]
799 .sort((a, b) => a.index - b.index)
800 .map(agent => {
801 if (agent.phase !== null && phases.includes(agent.phase)) previous = agent.phase
802 return [agent.id, previous] as const
803 }),
804 )
805 return agents.map(agent => ({ ...agent, phase: placed.get(agent.id) ?? agent.phase }))
806}
807
808export const lotRun = (run: WorkflowRun, lot: string): WorkflowRun => {
809 const entry = run.lots.find(one => one.lot === lot) ?? blankLot(lot)
810 const phases = run.child?.phases ?? []
811 const resolved = run.agents
812 .filter(agent => agent.lot === lot)
813 .map(agent => ({ ...agent, phase: nestedPhaseOf(run.child, agent.label, agent.phase) }))
814 const agents = placedInPhases(resolved, phases)
815 const state = lotStateOf(run, entry)
816 const asking = entry.outcome === null ? (entry.asking ?? 0) : 0
817 const status: RunStatus = state === 'waiting' && asking > 0 ? 'running' : state === 'pending' || state === 'done' || state === 'waiting' ? 'completed' : state
818 const startedAt = agents.length > 0 ? Math.min(...agents.map(agent => agent.startedAt)) : run.startedAt
819 const endedAt = agents.length > 0 ? Math.max(...agents.map(agent => agent.endedAt ?? agent.lastActiveAt)) : startedAt
820 return {
821 ...run,
822 runId: `${run.runId}#${lot}`,
823 name: run.child?.name ?? run.name,
824 argument: entry.sheet,
825 phases: run.child?.phases ?? [],
826 details: run.child?.details ?? {},
827 startedAt,
828 launchedAt: startedAt,
829 durationMs: status === 'running' ? null : endedAt - startedAt,
830 status,
831 outcome: entry.outcome,
832 audit: entry.audit,
833 sheet: entry.view,
834 agents,
835 child: null,
836 plan: null,
837 lots: [],
838 asking,
839 }
840}
841
842const VERDICTS: AuditVerdict['verdict'][] = ['VALIDE', 'ECARTS', 'ÉCARTS', 'VALID', 'GAPS']
843
844export const auditOf = (source: unknown): AuditVerdict | null => {
845 if (source === null || typeof source !== 'object') return null
846 const fields = source as Record<string, unknown>
847 const verdict = VERDICTS.find(one => one === fields.verdict)
848 if (verdict === undefined) return null
849 const gaps = Array.isArray(fields.gaps) ? fields.gaps : []
850 const count = (severities: string[]) => gaps.filter(gap => severities.includes(gap?.severity)).length
851 return { verdict, blocking: count(['Bloquant', 'Blocking']), major: count(['Majeur', 'Major']) }
852}
853
854export const auditLabel = (audit: AuditVerdict): string =>
855 [audit.verdict, audit.blocking > 0 ? `${audit.blocking} blocking` : '', audit.major > 0 ? `${audit.major} major` : '']
856 .filter(part => part !== '')
857 .join(' · ')
858
859export const auditTone = (audit: AuditVerdict): 'success' | 'warning' | 'error' =>
860 audit.verdict === 'VALIDE' || audit.verdict === 'VALID' ? 'success' : audit.blocking > 0 ? 'error' : 'warning'
861
862const OUTCOME_KEYS = ['statut', 'status', 'verdict', 'summary']
863
864const outcomeOf = (result: unknown): Outcome | null => {
865 if (typeof result === 'string') {
866 const label = firstLine(result, 120)
867 return label === '' ? null : { label, reason: null, report: null }
868 }
869 if (result === null || typeof result !== 'object') return null
870 const fields = result as Record<string, unknown>
871 const label = OUTCOME_KEYS.map(key => textOf(fields[key])).find(found => found !== null) ?? null
872 if (label === null) return null
873 const reason = textOf(fields.raison) ?? textOf(fields.reason)
874 const merge = mergeOf(fields.merge)
875 return { label, reason: reason === '—' ? null : reason, report: textOf(fields.rapport) ?? textOf(fields.report), ...(merge === null ? {} : { merge }) }
876}
877
878const MERGE_STATES = ['staged', 'refused', 'blocked', 'failed'] as const
879
880// `merge` of a run-plan result (workflows/run-plan.js): absent when the plan had nothing to merge.
881export const mergeOf = (value: unknown): KnowledgeMerge | null => {
882 if (value === null || typeof value !== 'object') return null
883 const fields = value as Record<string, unknown>
884 const state = MERGE_STATES.find(one => one === fields.state)
885 if (state === undefined) return null
886 const texts = (list: unknown): string[] => (Array.isArray(list) ? list.flatMap(one => (textOf(one) === null ? [] : [textOf(one) as string])) : [])
887 const next = textOf(fields.next)
888 return { state, lines: texts(fields.lines), warnings: texts(fields.warnings), next: next === null ? null : (next.split(' — ')[0] ?? next) }
889}
890
891// A staged merge waits for the user: the plan is green, the base is not written yet.
892export const mergeRows = (merge: KnowledgeMerge): { text: string; tone: 'warning' | 'error' | 'inactive' | undefined; bold: boolean }[] => [
893 merge.state === 'staged'
894 ? { text: '◆ Knowledge base — merge staged, not written', tone: 'warning', bold: true }
895 : { text: `✗ Knowledge base — merge ${merge.state}`, tone: 'error', bold: true },
896 ...merge.lines.map(text => ({ text, tone: 'inactive' as const, bold: false })),
897 ...merge.warnings.map(text => ({ text, tone: 'warning' as const, bold: false })),
898 ...(merge.next === null ? [] : [{ text: `→ ${merge.next}`, tone: undefined, bold: false }]),
899]
900
901export const outcomeTone = (outcome: Outcome, status: RunStatus): 'success' | 'warning' | 'error' | typeof WAITING_TONE => {
902 if (['TERMINÉ', 'DONE'].includes(outcome.label)) return 'success'
903 if (['ECARTS', 'ÉCARTS', 'GAPS'].includes(outcome.label)) return 'warning'
904 if (['BLOQUÉ', 'BLOCKED'].includes(outcome.label)) return 'error'
905 return status === 'completed' ? 'success' : status === 'killed' ? 'warning' : 'error'
906}
907
908const recordOf = (text: string): Record<string, unknown> | null => {
909 const parsed = jsonOf(text)
910 return parsed !== null && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null
911}
912
913export const parseJournal = (text: string): Journal | null => {
914 const raw = recordOf(text)
915 if (raw === null) return null
916 const status = STATUSES.find(one => one === raw.status) ?? (raw.status === 'running' ? 'running' : 'failed')
917 const declared = Array.isArray(raw.phases)
918 ? raw.phases.flatMap(one => (typeof one?.title === 'string' ? [{ title: one.title as string, detail: textOf(one.detail) }] : []))
919 : []
920 const agentPhases: Record<string, string> = {}
921 for (const entry of Array.isArray(raw.workflowProgress) ? raw.workflowProgress : []) {
922 if (entry?.type === 'workflow_agent' && typeof entry.agentId === 'string' && typeof entry.phaseTitle === 'string') {
923 agentPhases[entry.agentId] = entry.phaseTitle
924 }
925 }
926 const failure = typeof raw.error === 'string' ? { label: status, reason: raw.error, report: null } : null
927 return {
928 status,
929 durationMs: typeof raw.durationMs === 'number' ? raw.durationMs : null,
930 outcome: outcomeOf(raw.result) ?? failure,
931 argument: argumentOf({ args: raw.args }),
932 audit: auditOf(raw.result),
933 phases: declared.map(phase => phase.title),
934 details: detailsOf(declared),
935 agentPhases,
936 }
937}
938
939export type Sample = { phase: string; ms: number; tools: number | null; startedAt: number | null; scope?: string; label?: string }
940
941export const samplesOf = (text: string, labels: Record<string, string> = {}): Sample[] => {
942 const raw = recordOf(text)
943 if (raw === null) return []
944 const isComplete = raw.status === 'completed'
945 return (Array.isArray(raw.workflowProgress) ? raw.workflowProgress : []).flatMap(entry =>
946 entry?.type === 'workflow_agent' && entry.state === 'done' && typeof entry.phaseTitle === 'string' && typeof entry.durationMs === 'number'
947 ? [
948 {
949 phase: labelledPhaseOf(labels, typeof entry.label === 'string' ? entry.label : '', entry.phaseTitle as string) ?? (entry.phaseTitle as string),
950 scope: entry.phaseTitle as string,
951 label: typeof entry.label === 'string' ? entry.label : '',
952 ms: entry.durationMs as number,
953 tools: typeof entry.toolCalls === 'number' ? entry.toolCalls : null,
954 startedAt: isComplete && typeof entry.startedAt === 'number' ? entry.startedAt : null,
955 },
956 ]
957 : [],
958 )
959}
960
961const spansOf = (samples: Sample[]): { phase: string; ms: number }[] => {
962 const bounds: Record<string, { from: number; to: number }> = {}
963 for (const sample of samples) {
964 if (sample.startedAt === null) continue
965 const key = JSON.stringify([sample.scope ?? sample.phase, sample.phase])
966 const found = bounds[key]
967 const end = sample.startedAt + sample.ms
968 bounds[key] = { from: Math.min(found?.from ?? sample.startedAt, sample.startedAt), to: Math.max(found?.to ?? end, end) }
969 }
970 return Object.entries(bounds).map(([key, one]) => ({ phase: (JSON.parse(key) as string[])[1] ?? '', ms: one.to - one.from }))
971}
972
973const NO_SAMPLE: PhaseSample = { total: 0, count: 0, tools: 0, toolCount: 0, span: 0, spanCount: 0 }
974
975export const statsOf = (known: PhaseSamples, phase: string): PhaseSample => ({ ...NO_SAMPLE, ...known[phase] })
976
977export const withSamples = (known: PhaseSamples, samples: Sample[]): PhaseSamples => {
978 const merged: PhaseSamples = { ...known }
979 for (const sample of samples) {
980 const before = statsOf(merged, sample.phase)
981 merged[sample.phase] = {
982 ...before,
983 total: before.total + sample.ms,
984 count: before.count + 1,
985 tools: before.tools + (sample.tools ?? 0),
986 toolCount: before.toolCount + (sample.tools === null ? 0 : 1),
987 }
988 }
989 for (const one of spansOf(samples)) {
990 const before = statsOf(merged, one.phase)
991 merged[one.phase] = { ...before, span: before.span + one.ms, spanCount: before.spanCount + 1 }
992 }
993 return merged
994}
995
996const peersOf = (agents: WorkflowAgent[], agent: WorkflowAgent): WorkflowAgent[] =>
997 agents.filter(
998 other =>
999 other.id !== agent.id && (other.phase ?? NO_PHASE) === (agent.phase ?? NO_PHASE) && other.state === 'done' && other.endedAt !== null,
1000 )
1001
1002export const typicalMs = (known: PhaseSamples, agents: WorkflowAgent[], agent: WorkflowAgent): number | null => {
1003 const stats = statsOf(known, agent.phase ?? NO_PHASE)
1004 const peers = peersOf(agents, agent)
1005 const count = stats.count + peers.length
1006 const own = peers.reduce((sum, other) => sum + ((other.endedAt ?? other.startedAt) - other.startedAt), 0)
1007 return count === 0 ? null : (stats.total + own) / count
1008}
1009
1010export const typicalTools = (known: PhaseSamples, agents: WorkflowAgent[], agent: WorkflowAgent): number | null => {
1011 const stats = statsOf(known, agent.phase ?? NO_PHASE)
1012 const peers = peersOf(agents, agent)
1013 const count = stats.toolCount + peers.length
1014 const own = peers.reduce((sum, other) => sum + other.tools, 0)
1015 return count === 0 ? null : (stats.tools + own) / count
1016}
1017
1018export const isSlow = (agent: WorkflowAgent, typical: number | null, at: number): boolean =>
1019 typical !== null && (agent.endedAt ?? at) - agent.startedAt > SLOW_FACTOR * typical
1020
1021export const throughputOf = (agent: WorkflowAgent): number | null => {
1022 if (agent.streamKind === null || agent.firstChunkAt === null || agent.lastChunkAt === null || agent.streamChars === 0) return null
1023 const span = agent.lastChunkAt - agent.firstChunkAt
1024 return span < 1000 ? null : agent.streamChars / CHARS_PER_TOKEN / (span / 1000)
1025}
1026
1027export const liveSignalOf = (agent: WorkflowAgent, at: number): string | null => {
1028 if (agent.state !== 'running') return null
1029 if (agent.openCalls > 0) return agent.toolSince !== null && at - agent.toolSince > STALL_TOOL_MS ? 'long tool' : null
1030 if (agent.waitingSince !== null) return at - agent.waitingSince > STALL_WAIT_MS ? 'waiting' : null
1031 const idle = at - Math.max(agent.lastActiveAt, agent.lastChunkAt ?? 0)
1032 if (idle > STALL_IDLE_MS) return `idle ${Math.floor(idle / 60_000)}m`
1033 const rate = throughputOf(agent)
1034 const span = (agent.lastChunkAt ?? 0) - (agent.firstChunkAt ?? at)
1035 return rate !== null && span > STALL_SLOW_MS && rate < SLOW_RATE ? 'slow' : null
1036}
1037
1038export const stallReasons = (agent: WorkflowAgent, typical: number | null, at: number): string[] => {
1039 if (agent.state !== 'running') return []
1040 return [
1041 liveSignalOf(agent, at) ?? '',
1042 agent.tools > (typical === null ? STALL_TOOLS : SLOW_FACTOR * typical) ? `${agent.tools} tools` : '',
1043 agent.context > STALL_CONTEXT ? `ctx ${kilo(agent.context)}` : '',
1044 ]
1045 .filter(reason => reason !== '')
1046 .map(reason => `⚠ ${reason}`)
1047}
1048
1049const STREAM_LABELS: Record<StreamKind, string> = { thinking: 'thinking', output: 'output', tool: 'tool' }
1050
1051export const characters = (count: number): string => {
1052 if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M chars`
1053 const tenths = Math.round(count / 100)
1054 if (tenths >= 100) return `${Math.round(count / 1000)}k chars`
1055 if (count >= 1000) return `${(tenths / 10).toFixed(1)}k chars`
1056 return `${count} chars`
1057}
1058
1059export const elapsed = (ms: number): string => {
1060 const seconds = Math.max(0, Math.floor(ms / 1000))
1061 return seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min`
1062}
1063
1064export const activityOf = (agent: WorkflowAgent, at: number): string | null => {
1065 if (agent.state !== 'running') return null
1066 if (agent.openCalls > 0 && agent.toolSince !== null) return `tool ${agent.lastTool ?? '?'} ${elapsed(at - agent.toolSince)}`
1067 if (agent.waitingSince !== null) return `○ waiting model ${elapsed(at - agent.waitingSince)}`
1068 if (agent.streamKind === null) return null
1069 if (agent.streamChars === 0) return `● ${STREAM_LABELS[agent.streamKind]}${agent.firstChunkAt === null ? '' : ` · ${elapsed(at - agent.firstChunkAt)}`}`
1070 const rate = throughputOf(agent)
1071 return `● ${STREAM_LABELS[agent.streamKind]} · ${characters(agent.streamChars)}${rate === null ? '' : ` · ${Math.round(rate)} tok/s`}`
1072}
1073
1074export const attemptsOf = (agents: WorkflowAgent[]): Record<string, number> => {
1075 const seen: Record<string, number> = {}
1076 const attempts: Record<string, number> = {}
1077 for (const agent of [...agents].sort((a, b) => a.startedAt - b.startedAt || a.index - b.index)) {
1078 if (agent.state !== 'interrupted') seen[agent.label] = (seen[agent.label] ?? 0) + 1
1079 attempts[agent.id] = seen[agent.label] ?? 1
1080 }
1081 return attempts
1082}
1083
1084export const isPhaseDone = (tdd: TddMarks | null): boolean =>
1085 tdd !== null && tdd.red === DONE && tdd.green === DONE && tdd.cost === DONE
1086
1087export const isStepDone = (step: Step): boolean =>
1088 (step.isDone || isPhaseDone(step.tdd)) && step.corrections.every(one => isPhaseDone(one.tdd))
1089
1090export const isStepStarted = (step: Step): boolean =>
1091 [step.tdd, ...step.corrections.map(one => one.tdd)].some(
1092 tdd => tdd !== null && (tdd.red === DONE || tdd.green === DONE || tdd.cost === DONE),
1093 )
1094
1095export const markOf = (value: string): string => (value === DONE ? '✓' : value === '' || value === '⬜' ? '·' : value)
1096
1097export const parseSheet = (text: string, path: string): Sheet => {
1098 const lines = text.split(/\r?\n/)
1099 const title = lines.find(line => line.startsWith('# '))?.slice(2).trim() ?? ''
1100 const lot = SHEET_PATTERN.exec(path)?.[1] ?? /PLAN-(F\d+)/.exec(title)?.[1] ?? '?'
1101 const name = title
1102 .replace(/\s+—\s+✅ DONE.*$/, '')
1103 .split(' — ')
1104 .slice(1)
1105 .join(' — ')
1106 const steps: Step[] = []
1107 let section = ''
1108 let hypotheses = 0
1109
1110 for (const line of lines) {
1111 if (line.startsWith('## ')) {
1112 section = line.slice(3).trim()
1113 continue
1114 }
1115 if ((/^(H[yi]poth[eè]ses|Assumptions)/i.test(section) || section.includes('<!-- kit:assumptions -->')) && /^\s*(?:[-*]\s+)?\**H\d+\b/.test(line)) hypotheses += 1
1116 if (!/^(D[eé]roulement TDD|TDD sequence)/i.test(section)) continue
1117
1118 const step = /^### (?:[EÉ]tape|Step) (\S+) — (.+)$/.exec(line)
1119 if (step) {
1120 const heading = step[2] ?? ''
1121 steps.push({
1122 number: step[1] ?? '',
1123 title: heading.replace(/\s+—\s+✅ DONE.*$/, ''),
1124 isDone: heading.includes('✅ DONE'),
1125 tdd: null,
1126 corrections: [],
1127 })
1128 continue
1129 }
1130 const current = steps[steps.length - 1]
1131 if (current === undefined) continue
1132
1133 if (line.startsWith('✅ DONE')) {
1134 current.isDone = true
1135 continue
1136 }
1137
1138 const correction = /^(?:#{3,4} )?Correction (C\d+) — (.+)$/.exec(line)
1139 if (correction) {
1140 current.corrections.push({ id: correction[1] ?? '', finding: correction[2] ?? '', tdd: null })
1141 continue
1142 }
1143 const tdd = /^TDD ?: RED (\S+) · GREEN (\S+) · CO[US]T (\S+)/.exec(line)
1144 if (tdd) {
1145 const marks: TddMarks = { red: tdd[1] ?? '', green: tdd[2] ?? '', cost: tdd[3] ?? '' }
1146 const owner = current.corrections[current.corrections.length - 1] ?? current
1147 if (owner.tdd === null) owner.tdd = marks
1148 }
1149 }
1150
1151 const isDone = title.includes('✅ DONE') || (steps.length > 0 && steps.every(isStepDone))
1152 const cycles = parseCycles(text)
1153 return { lot, name, isDone, steps, hypotheses, ...(cycles === null ? {} : { cycles }) }
1154}
1155
1156export const parseCycles = (text: string): SheetCycle[] | null => {
1157 const lines = text.split(/\r?\n/)
1158 const start = lines.findIndex(line => line.trim() === CYCLES_SECTION)
1159 if (start < 0) return null
1160 const end = lines.findIndex((line, at) => at > start && line.startsWith('## '))
1161 const fenced = /```json[ \t]*\n([\s\S]*?)\n```/.exec(lines.slice(start + 1, end < 0 ? undefined : end).join('\n'))?.[1]
1162 const block = fenced === undefined ? null : recordOf(fenced)
1163 const listed = Array.isArray(block?.cycles) ? (block.cycles as unknown[]) : []
1164 const cycles = listed.flatMap((one, at): SheetCycle[] => {
1165 const fields = one !== null && typeof one === 'object' ? (one as Record<string, unknown>) : null
1166 const behaviour = textOf(fields?.behaviour)
1167 if (fields === null || behaviour === null) return []
1168 return [
1169 {
1170 id: textOf(fields.id) ?? `${at + 1}`,
1171 behaviour,
1172 wave: typeof fields.wave === 'number' ? fields.wave : 1,
1173 guard: fields.guard === true,
1174 state: 'pending',
1175 unreachable: [],
1176 },
1177 ]
1178 })
1179 return cycles.length === 0 ? null : cycles
1180}
1181
1182export const cycleSlugOf = (behaviour: string): string =>
1183 behaviour
1184 .normalize('NFD')
1185 .replace(/[\u0300-\u036f]/g, '')
1186 .toLowerCase()
1187 .replace(/[^a-z0-9]+/g, '-')
1188 .replace(/^-|-$/g, '')
1189 .slice(0, 60)
1190
1191const fieldsOf = (value: unknown): Record<string, unknown> | null =>
1192 value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
1193
1194export const cycleProgressOf = (cycle: SheetCycle, saved: string | null): SheetCycle => {
1195 const state = saved === null ? null : recordOf(saved)
1196 const red = fieldsOf(state?.red)
1197 if (red === null) return { ...cycle, state: 'pending', unreachable: [] }
1198 const green = fieldsOf(state?.green)
1199 const unreachable = (Array.isArray(red.unreachable) ? (red.unreachable as unknown[]) : []).flatMap(one => {
1200 const method = textOf(fieldsOf(one)?.method)types/index.d.ts 177 lines1export type AgentState = 'running' | 'done' | 'error' | 'interrupted'
2
3export type StreamKind = 'thinking' | 'output' | 'tool'
4
5export type CallState = 'running' | 'ok' | 'error'
6
7export type ToolTrace = {
8 id: string
9 tool: string
10 brief: string
11 at: number
12 state: CallState
13 error: string | null
14}
15
16export type WorkflowAgent = {
17 id: string
18 index: number
19 label: string
20 phase: string | null
21 model: string
22 effort: string | null
23 type: string
24 startedAt: number
25 endedAt: number | null
26 lastActiveAt: number
27 openCalls: number
28 toolSince: number | null
29 waitingSince: number | null
30 firstChunkAt: number | null
31 lastChunkAt: number | null
32 streamKind: StreamKind | null
33 streamChars: number
34 state: AgentState
35 lastTool: string | null
36 tools: number
37 context: number
38 contextStart: number
39 contextPeak: number
40 tokens: number
41 prompt: string
42 answer: string | null
43 structured: string[] | null
44 calls: ToolTrace[]
45 toolCounts: Record<string, number>
46 files: string[]
47 lastError: string | null
48 lot: string | null
49}
50
51export type RunStatus = 'running' | 'completed' | 'failed' | 'killed'
52
53// The knowledge-base merge a run-plan result carries: staged after a plan delivered whole, never
54// written by the run — `next` is the skill that shows the diff and writes it on confirmation.
55export type KnowledgeMerge = {
56 state: 'staged' | 'refused' | 'blocked' | 'failed'
57 lines: string[]
58 warnings: string[]
59 next: string | null
60}
61
62export type Outcome = {
63 label: string
64 reason: string | null
65 report: string | null
66 merge?: KnowledgeMerge
67}
68
69export type AuditVerdict = {
70 verdict: 'VALIDE' | 'ECARTS' | 'ÉCARTS' | 'VALID' | 'GAPS'
71 blocking: number
72 major: number
73}
74
75export type PhaseDeclaration = {
76 title: string
77 detail: string | null
78}
79
80export type TddMarks = { red: string; green: string; cost: string }
81
82export type Correction = { id: string; finding: string; tdd: TddMarks | null }
83
84export type Step = {
85 number: string
86 title: string
87 isDone: boolean
88 tdd: TddMarks | null
89 corrections: Correction[]
90}
91
92export type CycleState = 'pending' | 'red' | 'done'
93
94export type SheetCycle = { id: string; behaviour: string; wave: number; guard: boolean; state: CycleState; unreachable: string[]; live?: 'RED' | 'GREEN' }
95
96export type Sheet = { lot: string; name: string; isDone: boolean; steps: Step[]; hypotheses: number; cycles?: SheetCycle[] }
97
98export type ChildWorkflow = { name: string; phases: string[]; details: Record<string, string>; labels: Record<string, string>; script?: string | null }
99
100export type LotFigures = { agents: number; durationMs: number; tokens: number; endedAt: number }
101
102export type PlanLot = {
103 lot: string
104 sheet: string | null
105 deps: string[]
106 isDone: boolean
107 outcome: Outcome | null
108 audit: AuditVerdict | null
109 view: Sheet | null
110 asking?: number
111 past?: LotFigures | null
112 title?: string
113}
114
115export type WorkflowRun = {
116 runId: string
117 name: string
118 argument: string | null
119 phases: string[]
120 details: Record<string, string>
121 transcriptDir: string | null
122 startedAt: number
123 launchedAt: number
124 durationMs: number | null
125 status: RunStatus
126 outcome: Outcome | null
127 audit: AuditVerdict | null
128 sheet: Sheet | null
129 agents: WorkflowAgent[]
130 child: ChildWorkflow | null
131 plan: string | null
132 lots: PlanLot[]
133 asking?: number
134}
135
136export type Journal = {
137 status: RunStatus
138 durationMs: number | null
139 outcome: Outcome | null
140 argument: string | null
141 audit: AuditVerdict | null
142 phases: string[]
143 details: Record<string, string>
144 agentPhases: Record<string, string>
145}
146
147export type PhaseSample = { total: number; count: number; tools: number; toolCount: number; span: number; spanCount: number }
148
149export type PhaseSamples = Record<string, PhaseSample>
150
151export type SessionFigures = {
152 context: number | null
153 percent: number | null
154}
155
156export type Screen = 'run' | 'phase' | 'agent' | 'validate' | 'graph'
157
158export type Prompted = { kind: 'reject' | 'amend' | 'note'; target: string }
159
160export type RunFeed = { runId: string; root: string; work: string; pane: string; reports: Record<string, string> }
161
162export type Navigation = {
163 screen: Screen
164 phase: string | null
165 agentId: string | null
166 back: Screen
167 toggled: string[]
168 lot: string | null
169 prompted?: Prompted | null
170}
171
172declare module 'claude-code' {
173 interface PluginState {
174 'run-lot-pane': { runs: WorkflowRun[]; now: number; usage: SessionFigures; nav: Navigation; history: PhaseSamples; isShown: boolean; feed: RunFeed | null }
175 }
176}
177