SLOPSHOPPER

ledger

The record of orchestrated work: runs of units and tasks, the subagents spawned for them, each gate's verdict and the findings reviewers report, summed up in…

paneguardcommandtoaststatusprompt
v0.3.0MITupdated 2026-10-12BuddyLim/claude-code-mod-ledger
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ledger
│ ┃ ledger ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ Ledger 0 open · 0 done ⏺ Read(src/auth.ts) │ ┃ ──────────────────────────────────────── ⎿ Read 6 lines │ ┃ ──────────── ⏺ Update(src/auth.ts) │ ┃ Nothing planned yet. ⎿ Added 2 lines, removed 1 line │ ┃ ──────────────────────────────────────── ⏺ Bash(bun test) │ ┃ ──────────── ⎿ 3 pass, 1 fail │ ┃ a: all s: sessions │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /ledger │ ⎿ ledger: Ledger: nothing is planned. The agent records a plan whe │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · ledger
Ledger 0 open · 0 done ──────────────────────────────────────────────────── Nothing planned yet. ──────────────────────────────────────────────────── a: all s: sessions
README

ledger

A Claude Code mod that keeps the record of an orchestrated run: its units and tasks, the subagents spawned for them, each gate's verdict, and the findings reviewers report.

It draws no band. While a run has something to say, the status line carries one short entry: the task work is on and how many more are not done, such as T3 add the retry · 4 more, however many tasks, lanes or findings the run has. Once every task is done with no agent running and no finding open, the entry is empty. /ledger opens a pane with the whole run, drawn as a pipeline.

Install

This mod uses Claude Code's function-hooks plugin API.

Clone it into your personal skills folder, where Claude Code loads it in every session:

git clone https://github.com/BuddyLim/claude-code-mod-ledger ~/.claude/skills/ledger

Or clone it anywhere and load it for one session:

claude --plugin-dir /path/to/claude-code-mod-ledger

It works alone. With the parked mod, a failed gate and each unit's open findings are parked for you; with the lens mod, findings show on their lines and open there.

What it records

  • The plan. The agent calls plan once with the goal and every task: an id, its unit, a title, the tier it is meant for and what its gate checks.
  • What each part is for, and what was done. The plan can say in a line what each unit adds up to and what each task is for; a task marked done can carry its outcome: what changed and where. These are the agent's own account, where gate verdicts and findings are the checked part.
  • Spawns, by themselves. Each subagent the session starts is recorded with its type, model, start, end and tokens. One whose description begins with a task id in brackets ([T3] add the retry) is recorded against that task, which is marked running.
  • Gate verdicts. The agent calls task with done, or gate-failed and a note.
  • Findings. Any agent, a reviewing subagent included, calls finding with a path, a line, a severity and a one-line summary. fixed closes them.

Commands

/ledger          open the pane
/ledger sessions open the pane on the ledgers of other sessions
/ledger print    print the run in the transcript
/ledger hide     empty the status entry (show brings it back)
/ledger clear    forget the run

Runs

Each plan is a run, and a session keeps its runs: planning again adds one. Nothing picks which run is written to: a task update goes to the run that has the task, a spawn to the run whose task its description names, and a finding to the run of the task it names or of the subagent that reported it. So a task id may not be reused while a run of the session that has it is under way. The status line names the task work is on in the newest run under way, and counts the tasks not done across them all.

A plan may split a run into lanes: parallel tracks of one feature that can be worked on at once. Tasks are read in the plan's order: those with no lane run one after another, and tasks in lanes that follow one another are a fork, each lane a branch that joins the line again where the lanes end.

A run is done by itself once every task is done with no agent running and no finding open, and opens again if work comes back to it. The agent is told to settle as it goes: a task is marked done when its gate passes and a finding closed when its fix lands, and a task call that leaves findings open on what it marked done is answered with which ones. The last 40 runs of a session are kept; past that the oldest done ones are dropped.

Sessions

The ledger belongs to the session, not the folder. Its runs are stored under the session's id on every change, so two sessions at work in one project never write each other's ledger, and a session brought back with /resume or claude --resume finds its own as it left it; the subagents it showed running ended with the process that ran them, and one that is sent a message and works again counts as running again. After a /clear or an in-app resume the ledger follows the session the process is then in, from its next prompt.

The ledgers of other sessions, of this project and of others, can be read from the pane (s, or /ledger sessions): this folder's sessions first, the latest changed first. Another session's ledger is shown as it was read and is read only. The last 60 sessions that have a ledger are kept.

Runs kept a folder each by an earlier version are filed by the session that planned them the first time this version starts; what was stored stays.

Keeping it true

  • Cancelled. A task that will not be done is marked cancelled, with why. It holds its run open no more than a done one.
  • Stalled. A task marked running that no subagent is on, in a run nothing has touched for an hour, is drawn as stalled (◌) and turns no mark; so is a session in the list that was at work when its ledger last changed.
  • Out of turn. When a subagent starts on a task before the tasks it needs are done, or one lane of a fork is started and the lanes beside it are left waiting, the agent is told, once, in a note it reads.
  • Reports. What a subagent said as its turn ended is kept, cut short, and shown with its task in the overview: the nearest thing to its log.
  • Room. The ledgers keep to 3 MB of the plugin's store. Over that, the sessions changed longest ago give up their finished runs first, then go whole; the session at work is never touched, and a toast says when it happened.

Following a plan document

A run can be read from a plan document instead of being recorded by the agent, so the plan costs no tokens to enter and the document stays the word on it.

  • Tasks and steps. Each ### Task N: name heading is task TN; the checkboxes under it are its steps; a ## section is a unit. A task with every box ticked is done, with some ticked it is under way.
  • In step. The document is read again each time it is written or edited, and when a session starts.
  • Subagents. One described as the document names a task ("Task 3: …") is recorded against it.
  • Ticking. When a task is marked done, the open boxes under it are ticked. Only [ ] becomes [x], only under a done task.
  • Another layout. A document with no such headings is grouped by a small model, from its headings and checkboxes alone and once per document; the words and ticks are still read from the document itself.

Making a plan parallel

A superpowers plan is written as one task after another. /ledger lanes reads such a plan and writes it back, in the same file, as one that can be worked on in parallel where its tasks allow:

/ledger lanes docs/superpowers/plans/my-plan.md   work out the lanes and write them
/ledger lanes --dry                               say what it would write, for the followed plan

It learns what each task needs, from the task's Needs: line where it has one, else from one model call that is shown only the tasks, their files and their steps; and always from the files themselves, since two tasks that touch one file are never put in two lanes. From that it finds the forks: a task every other comes before or after stays in the line, and the tasks between two such are lanes, each a chain of tasks that need one another. It writes two lines under each task heading and changes nothing else:

### Task 4: API client

**Needs:** Task 1
**Lane:** frontend

A wrong Needs: line is yours to edit; run the command again and the lanes follow, with no model asked. A plan in which every task needs the one before it stays a line. The agent is told to start one subagent per lane at once, and the task after a fork only when every lane is done.

The other lines a task may carry are read the same way: Unit:, Tier: and Gate:. A ## section counts as a unit only where the tasks sit under more than one, so a plan whose tasks all follow a "File Map" section has no units. As tasks change, the ledger writes how each stands under it (Status: done — what was done, or gate failed — why), so the document says where the work is to a session that has no ledger of it.

Two settings in /config, the first off by default:

SettingDoes
Follow superpowers plansa plan saved under docs/superpowers/plans starts a run by itself
Tick finished tasks in the planmarking a task done ticks its missed boxes
/ledger follow docs/roadmap.md   read this document as a run, wherever it is
/ledger tick                     tick the missed boxes of done tasks now
/ledger tick --dry               say how many it would tick

With no plan document, nothing here applies and the agent records the plan.

The pane

/ledger opens it; nothing opens it unasked. It opens on the current run while that is under way, and on the list of runs otherwise.

The list has a row per run: its goal, tasks done of all, failed gates, open findings, tokens and age.

KeyDoes
1–9, Enteropen that run
dclose the focused run by hand, or reopen one closed that way
xclear the focused run for good, after asking
alist done runs too
sthe sessions that have a ledger; h comes back to this one

A run is a pipeline, in two views. The overview draws it across, as a CI run is drawn, a node a task (● done, ✗ gate failed, ○ to do, and a mark that turns for one running):

●─┬─●─⠹─┬─○
  ├─✗───┤
  ╰─○───╯

with words only for what is running or has failed, or with neither, the task that comes next. e turns to details: the same line running down, a line a task, a fork's lanes as rails side by side, each lane's tasks under its name and a unit's name where it starts, with what each is for, what was done, and what its gate cost: the models its subagents ran on, how many, how long they worked and their tokens. A pipeline too wide to draw across is drawn down in both. Under a rule, open findings follow, a line each; in a narrow pane a finding's place keeps its end, the file and line, and its summary goes under it.

KeyDoes
edetails and back: every task on a line, what each unit and task is for, what was done, models, agents, time and tokens, and fixed findings
clickin the overview, a click on a node or on the id beside it shows that task in full
n, pin the overview, walk the pipeline's nodes: the task under the mark is shown in full (how it stands, its lane and unit, what it is for or what was done, its gate, what it cost, its open findings); c goes back to the task work is on
1–9add that finding to the prompt, never sending it
bback to the list
Escclose

A timer runs only while a subagent does, to turn that mark.

For other mods

The run is readable state:

const { value: run } = await $.state.get({ plugin: 'ledger', key: 'run' } as const)

types/index.d.ts is the contract (LedgerRun, LedgerTask, LedgerSpawn, LedgerFinding). Only the ledger writes it. run and runs are the session's own; home is the session they are read from.

Development

claude plugin validate .
claude plugin test .
  • hooks/register.tsx: the tools, the spawn and turn hooks, the command.
  • hooks/run.ts: the run's logic, free of the engine.
  • hooks/book.ts: a session's runs kept together, and the list of sessions.
  • hooks/pipe.ts: a run laid out as a pipeline.
  • hooks/doc.ts: a plan document read into a run, and written back to.
  • hooks/lanes.ts: a sequential plan's tasks put in lanes.
  • hooks/kit/: a copy of the shared mod-kit; edit the source and sync.
  • types/index.d.ts: the state contract.
Source 10 files
hooks/register.tsx 2435 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { LedgerRun, LedgerSessionNote, LedgerTask } from '../types'
5import {
6  PLAN_PATH,
7  labelled,
8  outlineOf,
9  outlineRequest,
10  parsePlan,
11  planFromOutline,
12  runFromDoc,
13  statusLabels,
14  ticked,
15} from './doc'
16import type { PlanDoc } from './doc'
17import { ICON, refIcon } from './kit/icons'
18import type { Book } from './book'
19import {
20  EMPTY,
21  bookOf,
22  STORE_BUDGET,
23  isTurning,
24  overBudget,
25  trimmed,
26  changedAt,
27  clash,
28  cleared,
29  closed,
30  currentOf,
31  isBook,
32  isIndex,
33  listed,
34  nextFinding,
35  noteOf,
36  noted,
37  ownerOf,
38  put,
39  runMarks,
40  runOfAgent,
41  bookStatus,
42  runOfFinding,
43  sessionsListed,
44  settled,
45  splitOld,
46  underWay,
47} from './book'
48import { PAD, ageOf, cut } from './kit/layout'
49import { allNeeds, lanesFrom, needsFromAnswer, needsRequest, shapeText } from './lanes'
50import type { Needs } from './lanes'
51import { NODES, gapFor, idleLanes, rowsOf, stripOf, unmetOf, wrapped } from './pipe'
52import type { StripPiece } from './strip'
53import {
54  SEVERITIES,
55  STALE_MS,
56  isStalled,
57  STATUSES,
58  countsOf,
59  lanesOf,
60  ended,
61  findingText,
62  focusOf,
63  leftOpen,
64  placeOf,
65  spanText,
66  spawnMeta,
67  stepsText,
68  tail,
69  tokensText,
70  unitsOf,
71  fixed,
72  found,
73  orphaned,
74  plan,
75  report,
76  resumed,
77  setTask,
78  spawned,
79  taskOf,
80} from './run'
81import type { NewTask } from './run'
82
83const PLAN = 'mcp__ledger__plan'
84const TASK = 'mcp__ledger__task'
85const FINDING = 'mcp__ledger__finding'
86const FIXED = 'mcp__ledger__fixed'
87const REPORT = 'mcp__ledger__report'
88
89// The run other mods read; null while nothing is planned.
90const run = atom({ plugin: 'ledger', key: 'run' } as const, null)
91const isHidden = atom({ plugin: 'ledger', key: 'isHidden' } as const, false)
92// Whether the pane lists fixed findings and every finished agent too.
93const isAll = atom({ plugin: 'ledger', key: 'isAll' } as const, false)
94// Every run kept for the session, for the pane's list.
95const runs = atom({ plugin: 'ledger', key: 'runs' } as const, [])
96// The session those are read from; another one means the process went on
97// under a new session (a /clear, a resume) or started afresh.
98const home = atom({ plugin: 'ledger', key: 'home' } as const, '')
99// Another session's ledger the pane shows, read only; and the sessions that
100// have one, as last listed.
101const peek = atom({ plugin: 'ledger', key: 'peek' } as const, null)
102const others = atom({ plugin: 'ledger', key: 'others' } as const, [])
103// The pane: the run it shows in full (0 for the list of runs, -1 for the list
104// of sessions), the list's row the focus is on, whether a run shows its
105// details, and the run a clear is waiting to be confirmed for (0 for none).
106const shown = atom({ plugin: 'ledger', key: 'shown' } as const, 0)
107const cursor = atom({ plugin: 'ledger', key: 'cursor' } as const, 0)
108const isDetailed = atom({ plugin: 'ledger', key: 'isDetailed' } as const, false)
109const confirming = atom({ plugin: 'ledger', key: 'confirming' } as const, 0)
110// The frame of the mark that turns beside a running subagent.
111const spin = atom({ plugin: 'ledger', key: 'spin' } as const, 0)
112// The finding the focus ring is on in a run's view, and the place last asked
113// to be shown: the lens mod, where loaded, opens it.
114const pointed = atom({ plugin: 'ledger', key: 'pointed' } as const, 0)
115// The task the overview shows in full, picked with the keys: '' for the one
116// work is on.
117const picked = atom({ plugin: 'ledger', key: 'picked' } as const, '')
118
119const STATUS_WORDS = {
120  todo: 'to do',
121  running: 'running',
122  'gate-failed': 'gate failed',
123  done: 'done',
124  cancelled: 'cancelled',
125} as const
126const jump = atom({ plugin: 'ledger', key: 'jump' } as const, null)
127
128const PANE = 'ledger'
129// The key of the region the pipeline is drawn in, where it takes the pointer.
130const STRIP = 'strip'
131const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
132const SPIN_MS = 150
133// In the pipeline drawn down: the space between a row's lines and its words,
134// so a node does not sit against its task; and the space before a line of a
135// task's details, which stand a little in from its title.
136// The node of a task marked running that nothing has touched for long.
137const STALLED = '◌'
138// Drawn down, the run before is above and the run after below: the marks
139// that lead to them point that way.
140const UP = '△'
141const DOWN = '▽'
142const APART = '   '
143// What a row naming the run before or after takes besides the run's name:
144// its mark, the space after it, the hotkey a button shows ("p: "), and a
145// little room at the pane's edge, so the name is cut before it is clipped.
146const NEIGHBOUR_TAKEN = 1 + 3 + 3 + 3
147const BESIDE = '     '
148// The most sessions their list shows: the latest changed.
149const SESSIONS_SHOWN = 30
150
151// A folder's own name, for a line that has no room for its path.
152const folderOf = (cwd: string): string => cwd.split('/').filter(Boolean).at(-1) ?? cwd
153
154const TASK_ICONS = {
155  todo: ICON.todo,
156  running: ICON.running,
157  'gate-failed': ICON.failed,
158  done: ICON.done,
159  cancelled: NODES.cancelled,
160} as const
161const TASK_TONES = { todo: 'gray', running: 'cyan', 'gate-failed': 'error', done: 'success', cancelled: 'gray' } as const
162const SEVERITY_TONES = { error: 'error', warning: 'warning', note: 'cyan' } as const
163
164// Adds text to the end of the person's draft, on its own line, and never
165// submits it: sending stays theirs.
166const toPrompt = async ($: EngineInterface, text: string) => {
167  const draft = await $.prompt.read().then(
168    box => box.text,
169    () => '',
170  )
171  const lead = draft === '' || draft.endsWith('\n') ? '' : '\n'
172  const filled = await $.prompt.fill({ text: `${lead}${text}\n`, mode: 'append' }).then(
173    answer => answer.isFilled,
174    () => false,
175  )
176
177  $.ui.toast(filled ? 'Ledger: added to the prompt.' : 'Ledger: the prompt could not take it.')
178}
179
180const GUIDE = `# Ledger
181
182The user follows delegated work in a ledger. Keep it true, in few words, with ${PLAN}, ${TASK}, ${FINDING}, ${FIXED} and ${REPORT}.
183
184- Before delegating a settled plan, call ${PLAN} once: the goal, each task (id, lane where the plan has parallel lanes, unit, title, a one-line "about", tier, gate check) and a one-line "about" per unit. List the tasks in the order they run: tasks with no lane run one after another, and tasks in lanes that follow one another run side by side. It starts a new run and keeps earlier ones, so give its tasks ids no run under way uses.
185- Where a run is already read from a plan document (its report says "Plan:"), do not plan it again: its tasks are T1, T2, ... as the document numbers them. The document may carry a line or two under a task heading: "**Lane:** api" puts it in a lane, "**Needs:** Task 1, Task 2" names the tasks it needs first, "**Unit:**", "**Tier:**" and "**Gate:**" say the rest. Leave the "**Status:**" lines alone: the ledger writes them.
186- Lanes are worked at once. Where the report shows lanes, start one subagent per lane in a single step, each working its lane's tasks in order, and start the task after the lanes only when every lane is done. Tasks with no lane are done one at a time, in order.
187- Begin each subagent's description with its task id in brackets: "[T3] add the retry".
188- Settle as you go, never in one sweep at the end. The moment a task's gate passes, call ${TASK} with every task that changed: "done" with a one-line outcome (what changed, in which files), "gate-failed" with a one-line note, or "cancelled" with a one-line note for a task that will not be done (it then holds the run open no longer). When a unit's review passes, mark every task of that unit done in that same step.
189- Tell reviewers to record all their findings in one ${FINDING} call and to answer with the count only, not the findings again. The moment a finding's fix lands, or you decide it needs none, close it with ${FIXED}, in the step that settles it; do not move to the next unit with a finding of this one open and unmentioned.
190- A run closes only once every task is done and no finding is open. Before telling the user the work is finished, read ${REPORT}: mark done what is done, close what is fixed, and name whatever you leave open and why.
191- Make ledger calls in the same step as your other tool calls, never as a step of their own.
192- For a status update, or when resuming, read ${REPORT} and answer from it.`
193
194const SUBAGENT_REFUSAL =
195  'Only the main agent changes the plan and its tasks. Report findings with the finding tool, and the rest in your final answer.'
196
197// A session's book is kept under its id, so a session resumed finds its own
198// and two sessions in one folder never write each other's.
199const bookKey = (sessionId: string) => `book:${sessionId}`
200const keyOf = async ($: EngineInterface) => bookKey(await $.session.id())
201// The sessions that have a book, each in a line; and the mark that the books
202// kept a folder each, as they were before, have been filed by session.
203const INDEX = 'sessions'
204const FILED = 'filed-by-session'
205// Where a folder's runs were kept together, and before that its one run.
206const OLD_BOOK = 'runs:'
207const OLD_RUN = 'run:'
208
209const loadBook = async ($: EngineInterface): Promise<Book> => {
210  const stored = await $.store.get(await keyOf($))
211
212  return isBook(stored) ? stored : EMPTY
213}
214
215const loadIndex = async ($: EngineInterface): Promise<LedgerSessionNote[]> => {
216  const stored = await $.store.get(INDEX)
217
218  return isIndex(stored) ? stored : []
219}
220
221// Writes the index with a session's line as it now stands, and forgets the
222// books of the sessions that fell past the limit.
223const noteSession = async ($: EngineInterface, index: readonly LedgerSessionNote[], note: LedgerSessionNote) => {
224  const kept = noted(index, note)
225
226  await $.store.set(INDEX, kept.index)
227
228  for (const gone of kept.dropped) {
229    await $.store.delete(bookKey(gone))
230  }
231
232  return kept.index
233}
234
235// Keeps the ledgers within `budget` of the store, giving up the least to do
236// it: from the sessions changed longest ago, and never the one at work, first
237// their finished runs, and only if that is not enough, the sessions whole. A
238// run not done is the last thing dropped. Says so once when it had to.
239const makeRoom = async ($: EngineInterface, keep: string, budget: number) => {
240  let index = await loadIndex($)
241
242  // A line written before sizes were kept is measured once.
243  for (const one of index.filter(note => note.size === undefined)) {
244    const stored = await $.store.get(bookKey(one.id))
245
246    index = index.map(note => (note.id === one.id ? { ...note, size: JSON.stringify(stored ?? null).length } : note))
247  }
248
249  const crowded = overBudget(index, keep, budget)
250
251  if (crowded.length === 0) {
252    return
253  }
254
255  for (const id of crowded) {
256    const stored = await $.store.get(bookKey(id))
257    const kept = isBook(stored) ? trimmed(stored) : null
258    const was = index.find(note => note.id === id)
259
260    if (kept === null) {
261      await $.store.delete(bookKey(id))
262      index = index.filter(note => note.id !== id)
263    } else {
264      await $.store.set(bookKey(id), kept)
265      index = index.map(note => (note.id === id ? noteOf(id, kept, was?.at ?? 0) : note))
266    }
267  }
268
269  // Runs not done are all that is left of those sessions; still over, the
270  // oldest of them go whole.
271  for (const id of overBudget(index, keep, budget)) {
272    await $.store.delete(bookKey(id))
273    index = index.filter(note => note.id !== id)
274  }
275
276  await $.store.set(INDEX, index)
277  $.ui.toast(
278    `Ledger: its store was nearly full, so the finished runs of ${crowded.length} older session${crowded.length === 1 ? '' : 's'} were dropped.`,
279  )
280}
281
282// Files the books kept a folder each by the session that planned each run,
283// once. What was stored stays where it was; a session's book already there is
284// left alone.
285const fileBySession = async ($: EngineInterface) => {
286  if ((await $.store.get(FILED)) === true) {
287    return
288  }
289
290  const keys = await $.store.keys()
291  let index = await loadIndex($)
292
293  for (const key of keys) {
294    const isOldBook = key.startsWith(OLD_BOOK)
295    const cwd = key.slice(isOldBook ? OLD_BOOK.length : OLD_RUN.length)
296
297    // A folder's one run was already taken into its book of runs.
298    if (!isOldBook && (!key.startsWith(OLD_RUN) || keys.includes(`${OLD_BOOK}${cwd}`))) {
299      continue
300    }
301
302    const stored = await $.store.get(key)
303
304    for (const [id, book] of splitOld(isOldBook ? bookOf(stored, undefined) : bookOf(undefined, stored), cwd)) {
305      if ((await $.store.get(bookKey(id))) === undefined) {
306        await $.store.set(bookKey(id), book)
307        index = await noteSession($, index, noteOf(id, book, changedAt(book)))
308      }
309    }
310  }
311
312  await $.store.set(FILED, true)
313}
314
315// The current run: the one the tools record against.
316const load = async ($: EngineInterface): Promise<LedgerRun | null> => currentOf(await loadBook($))
317
318// The mark that turns beside a running subagent: a timer moves its frame
319// while any subagent runs, and stops when none does.
320let spinTimer: { cancel: () => void } | undefined
321let spinTicks = 0
322
323const spinWhile = ($: EngineInterface, isBusy: boolean) => {
324  if (isBusy && spinTimer === undefined) {
325    spinTimer = $.clock.every(SPIN_MS, () => {
326      spinTicks += 1
327      void update($, spin, frame => (frame + 1) % SPINNER.length)
328
329      // About once a minute the book is looked at again: a task that has
330      // stalled meanwhile stops the mark, with no write to say so.
331      if (spinTicks % 400 === 0) {
332        void refresh($).catch(() => undefined)
333      }
334    })
335  } else if (!isBusy && spinTimer !== undefined) {
336    spinTimer.cancel()
337    spinTimer = undefined
338  }
339}
340
341// Keeps the state other mods and the pane read, the status line's entry and
342// the spinner's timer in step with the book. The entry is the current run's,
343// and is empty while hidden, once that run is done, or with nothing to say.
344const show = async ($: EngineInterface, book: Book) => {
345  const now = currentOf(book)
346
347  await update($, run, () => now)
348  await update($, runs, () => book.runs)
349  $.ui.status((await read($, isHidden)) ? undefined : bookStatus(book))
350  // The mark turns for a running subagent and for a task marked running, and
351  // in the list of sessions for one that was at work when it last changed.
352  const at = await $.clock.now()
353
354  spinWhile(
355    $,
356    isTurning(book, at) ||
357      ((await read($, shown)) === -1 &&
358        (await read($, others)).some(one => one.busy === true && at - one.at < STALE_MS)),
359  )
360}
361
362const refresh = async ($: EngineInterface) => show($, await loadBook($))
363
364// One change at a time: two hooks recording at once would otherwise both read
365// the book before either wrote it, and the second write would drop the first.
366let changes: Promise<unknown> = Promise.resolve()
367
368// Reads the stored book, applies the change and writes it back; answers the
369// reason when the change was refused or the store failed.
370const changeBookNow = async (
371  $: EngineInterface,
372  apply: (book: Book, now: number) => Book | string,
373): Promise<{ book: Book } | { error: string }> => {
374  try {
375    const before = await loadBook($)
376    const at = await $.clock.now()
377    const made = apply(before, at)
378
379    if (typeof made === 'string') {
380      return { error: made }
381    }
382
383    // Nothing changed: nothing is written, so a session with no run keeps none.
384    if (made === before) {
385      await show($, made)
386
387      return { book: made }
388    }
389
390    const sessionId = await $.session.id()
391    const after = made.cwd === undefined ? { ...made, cwd: await $.session.cwd() } : made
392
393    // A book with no run left is forgotten, and its session leaves the list.
394    const write = async () => {
395      await (after.runs.length === 0 ? $.store.delete(bookKey(sessionId)) : $.store.set(bookKey(sessionId), after))
396      await noteSession($, await loadIndex($), noteOf(sessionId, after, at))
397    }
398
399    // A store that is full refuses the write: room is made from the oldest
400    // sessions' finished runs, well under the budget, and it is written again.
401    await write().catch(async () => {
402      await makeRoom($, sessionId, STORE_BUDGET / 2)
403      await write()
404    })
405    await makeRoom($, sessionId, STORE_BUDGET).catch(() => undefined)
406    await show($, after)
407
408    return { book: after }
409  } catch (error) {
410    return { error: `The ledger could not be saved: ${error instanceof Error ? error.message : String(error)}` }
411  }
412}
413
414const changeBook = (
415  $: EngineInterface,
416  apply: (book: Book, now: number) => Book | string,
417): Promise<{ book: Book } | { error: string }> => {
418  const next = changes.then(() => changeBookNow($, apply))
419  changes = next.catch(() => undefined)
420
421  return next
422}
423
424// Changes the current run: `apply` answers the run as it should be (a new one
425// to plan it, the same one for no change), a refusal, or null to forget it.
426const change = async (
427  $: EngineInterface,
428  apply: (now: LedgerRun | null) => LedgerRun | string | null,
429): Promise<{ run: LedgerRun | null } | { error: string }> => {
430  const changed = await changeBook($, (book, at) => {
431    const before = currentOf(book)
432    const after = apply(before)
433
434    return typeof after === 'string'
435      ? after
436      : after === null
437        ? before === null
438          ? book
439          : cleared(book, before.id)
440        : put(book, after, at)
441  })
442
443  return 'error' in changed ? changed : { run: currentOf(changed.book) }
444}
445
446// The session the hooks last ran in. A hot reload forgets it; `home`, which
447// the host keeps, then says the session is the same one.
448let seen: string | undefined
449
450// Brings what is shown in step with the session the process is now in: a
451// /clear or a resume goes on under another id with no `session.start`, and a
452// session resumed in a new process starts with nothing shown. The subagents
453// its book still shows running ended with the process that ran them; one that
454// is sent a message and works again is seen at its next tool call.
455const sync = async ($: EngineInterface) => {
456  const sessionId = await $.session.id()
457
458  if (seen === sessionId) {
459    return
460  }
461
462  seen = sessionId
463
464  if ((await read($, home)) !== sessionId) {
465    await changeBook($, (book, at) => {
466      const left = book.runs.flatMap(one => one.spawns.filter(spawn => spawn.endedAt === undefined))
467
468      for (const one of left) {
469        over.add(one.agentId)
470      }
471
472      return left.length === 0
473        ? book
474        : { ...book, runs: book.runs.map(one => settled(orphaned(one, at), at)) }
475    })
476    await update($, home, () => sessionId)
477    await update($, peek, () => null)
478    await update($, shown, value => (value === -1 ? 0 : value))
479  }
480
481  await refresh($)
482}
483
484// What a small model answered when asked to lay out a document the parser
485// could not read, by the document's outline with its ticks taken out: one
486// call a document, however often its boxes change.
487const laidOut = new Map<string, string>()
488// The plan documents runs are read from: an edit of one reads it again.
489const followed = new Set<string>()
490
491type PlanRead = { text: string; doc: PlanDoc; isLaidOutByModel: boolean }
492
493// Reads a plan document: by its layout where that is the superpowers one, at
494// no cost; else as a small model groups its headings and checkboxes, from a
495// request of those lines alone. Undefined when it has no checkbox to follow.
496const readPlan = async ($: EngineInterface, path: string): Promise<PlanRead | undefined> => {
497  const text = await $.fs.read(path).catch(() => undefined)
498
499  if (text === undefined) {
500    return undefined
501  }
502
503  const direct = parsePlan(text)
504
505  if (direct !== undefined) {
506    return { text, doc: direct, isLaidOutByModel: false }
507  }
508
509  const outline = outlineOf(text)
510
511  if (!/\[( |x|X)\]/.test(outline)) {
512    return undefined
513  }
514
515  const key = outline.replace(/\[(x|X)\]/g, '[ ]')
516  let answer = laidOut.get(key)
517
518  if (answer === undefined) {
519    // A call that fails is no answer: the document is then not followed.
520    answer = await $.model
521      .complete({ model: 'haiku', prompt: outlineRequest(outline), maxTokens: 1500, timeoutMs: 30000 })
522      .then(
523        said => (said.isAnswered ? said.text : ''),
524        () => '',
525      )
526
527    if (answer !== '') {
528      laidOut.set(key, answer)
529    }
530  }
531
532  const doc = planFromOutline(text, answer)
533
534  return doc === undefined ? undefined : { text, doc, isLaidOutByModel: true }
535}
536
537// Makes a run of a plan document, or brings the run it made in step with it.
538// Answers what happened, in a line.
539const followDoc = async ($: EngineInterface, path: string): Promise<string> => {
540  const plan = await readPlan($, path)
541
542  if (plan === undefined) {
543    return `Ledger: ${path} has no tasks with checkboxes to follow.`
544  }
545
546  const sessionId = await $.session.id()
547  const changed = await changeBook($, (book, at) =>
548    put(
549      book,
550      runFromDoc(
551        plan.doc,
552        path,
553        plan.isLaidOutByModel,
554        at,
555        sessionId,
556        book.runs.find(one => one.doc?.path === path),
557      ),
558      at,
559    ),
560  )
561
562  if ('error' in changed) {
563    return changed.error
564  }
565
566  followed.add(path)
567
568  return `Ledger: following ${path}, ${plan.doc.tasks.length} task${plan.doc.tasks.length === 1 ? '' : 's'}${plan.isLaidOutByModel ? ' (laid out by a small model: its layout is not the superpowers one)' : ''}.`
569}
570
571// Writes a run's state into its plan document: the open boxes under each task
572// the run has as done are ticked (where `withTicks`), and each task's
573// `**Status:**` line says how it stands. `isDry` only counts the boxes.
574// Answers how many boxes.
575const tickDoc = async ($: EngineInterface, path: string, isDry: boolean, withTicks = true): Promise<number> => {
576  const plan = await readPlan($, path)
577  const owner = (await loadBook($)).runs.find(one => one.doc?.path === path)
578
579  if (plan === undefined || owner === undefined) {
580    return 0
581  }
582
583  const after = withTicks ? ticked(plan.text, plan.doc, owner) : { text: plan.text, count: 0 }
584
585  if (isDry) {
586    return after.count
587  }
588
589  // A tick moves no line, so the document as read still says where each is.
590  // A document a small model laid out has no task headings to write under.
591  const written = plan.isLaidOutByModel ? after.text : labelled(after.text, plan.doc, statusLabels(plan.doc, owner))
592
593  if (written !== plan.text) {
594    await $.fs.write(path, written)
595    await followDoc($, path)
596  }
597
598  return after.count
599}
600
601// What `/ledger lanes` last proposed for a document, and the document as it
602// was then: writing it asks no model again, and writes what was shown.
603const proposals = new Map<string, { text: string; said: Needs }>()
604
605// Makes a sequential plan one that can be worked on in parallel, in the same
606// document: learns what each task needs (from its `**Needs:**` line, else from
607// a model's reading of the tasks; and always from the files two tasks share),
608// works out the lanes, and writes a `**Needs:**` and a `**Lane:**` line under
609// each task.
610//
611// What a model read is shown before it is written: the first ask proposes,
612// and `shouldWrite` writes what was proposed while the document is unchanged.
613// A document that already says what every task needs is written at once,
614// since nothing in it is a guess. Answers what it found or did.
615const laneDoc = async ($: EngineInterface, path: string, shouldWrite: boolean): Promise<string> => {
616  const text = await $.fs.read(path).catch(() => undefined)
617  const doc = text === undefined ? undefined : parsePlan(text)
618
619  if (text === undefined || doc === undefined) {
620    return `Ledger: ${path} is not laid out in "Task N" headings, so it has no tasks to put in lanes.`
621  }
622
623  const said: Needs = new Map(doc.tasks.flatMap(one => (one.needs === undefined ? [] : [[one.n, one.needs]])))
624  const unsaid = doc.tasks.filter(one => one.needs === undefined)
625  const proposed = proposals.get(path)
626  const isGuessed = unsaid.length > 0 && doc.tasks.length > 1
627  // What was shown stands while the document it was read from is the same.
628  const isShown = isGuessed && proposed !== undefined && proposed.text === text
629
630  if (isShown) {
631    for (const [n, needs] of proposed.said) {
632      said.set(n, needs)
633    }
634  } else if (isGuessed) {
635    // One call, for the tasks the document does not speak for. A task the
636    // answer leaves out needs the one before it, as the plan was written.
637    const answer = await $.model
638      .complete({ model: 'sonnet', prompt: needsRequest(doc.tasks), maxTokens: 2000, timeoutMs: 60000 })
639      .then(
640        told => (told.isAnswered ? told.text : ''),
641        () => '',
642      )
643    const read = needsFromAnswer(answer, doc.tasks)
644
645    if (read.size === 0) {
646      return 'Ledger: the plan could not be read for what each task needs (the model gave no answer). Nothing was written.'
647    }
648
649    for (const one of unsaid) {
650      const told = read.get(one.n)
651
652      if (told !== undefined) {
653        said.set(one.n, told)
654      }
655    }
656
657    proposals.set(path, { text, said: new Map(said) })
658  }
659
660  const needs = allNeeds(doc.tasks, said)
661  const lanes = lanesFrom(doc.tasks, needs)
662  const count = new Set(lanes.values()).size
663  const found =
664    count === 0
665      ? `no two tasks of ${path} can be worked on at once: each needs one before it`
666      : `${count} lanes in ${path}: ${shapeText(doc.tasks, lanes)}`
667  const each = doc.tasks
668    .map(one => `  Task ${one.n} needs ${(needs.get(one.n) ?? []).join(', ') || 'none'}`)
669    .join('\n')
670
671  // A guess not yet shown is shown, whatever was asked: it is the person who
672  // says it is right.
673  if (isGuessed && !(shouldWrite && isShown)) {
674    return `Ledger proposes ${found}.\n${each}\nNothing is written yet. If that is right, run /ledger lanes --write; if a task needs something else, add a **Needs:** line under it in the document and run /ledger lanes again.`
675  }
676
677  if (!shouldWrite && !isGuessed) {
678    return `Ledger: ${found}, from the **Needs:** lines in the document.\n${each}\nRun /ledger lanes --write to write the lanes.`
679  }
680
681  const after = labelled(
682    text,
683    doc,
684    new Map(
685      doc.tasks.map(one => {
686        const mine = needs.get(one.n) ?? []
687
688        return [
689          one.n,
690          {
691            needs: mine.length === 0 ? 'none' : mine.map(n => `Task ${n}`).join(', '),
692            lane: lanes.get(one.n) ?? null,
693          },
694        ]
695      }),
696    ),
697  )
698
699  proposals.delete(path)
700
701  if (after !== text) {
702    await $.fs.write(path, after)
703
704    // A run read from the document follows it; a document no run is read
705    // from is only written.
706    if ((await loadBook($)).runs.some(one => one.doc?.path === path)) {
707      await followDoc($, path)
708    }
709  }
710
711  return `Ledger: ${found}. ${after === text ? 'The document already says so.' : 'Written under each task; edit a **Needs:** line and run /ledger lanes --write again if one is wrong.'}`
712}
713
714// A file was written: when it is a plan document a run is read from, or a new
715// plan where superpowers saves them and those are followed, the run follows.
716const noteDoc = async ($: EngineInterface, path: string, follows: boolean): Promise<void> => {
717  const isNew = !followed.has(path)
718
719  if (!isNew || (follows && PLAN_PATH.test(path))) {
720    const said = await followDoc($, path).catch(() => '')
721
722    if (isNew && said !== '') {
723      $.ui.toast(said)
724    }
725  }
726}
727
728// A path as typed, made absolute from the session's folder.
729const fullPath = async ($: EngineInterface, typed: string): Promise<string> =>
730  typed.startsWith('/') ? typed : `${await $.session.cwd()}/${typed.replace(/^\.\//, '')}`
731
732// What the agent has already been told about, so each thing is said once.
733const told = new Set<string>()
734// How long after a lane's first subagent starts the other lanes of its fork
735// are looked at: long enough for subagents started in one step to all arrive.
736const LANES_WAIT_MS = 20000
737
738// Tells the agent something of its own run, as a note it reads and the person
739// does not see as typed; and the person, in a toast.
740const tell = async ($: EngineInterface, key: string, words: string) => {
741  if (told.has(key)) {
742    return
743  }
744
745  told.add(key)
746  $.ui.toast(words)
747  await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: words }] } }).catch(() => undefined)
748}
749
750// A subagent started on a task: the agent is told when the task was started
751// before what it needs is done, and, a little later, when the other lanes of
752// its fork are still waiting though they could run beside it.
753const watchSpawn = async ($: EngineInterface, book: Book, agentId: string) => {
754  const home = runOfAgent(book, agentId)
755  const task = home?.spawns.find(one => one.agentId === agentId)?.task
756
757  if (home === undefined || task === undefined) {
758    return
759  }
760
761  const unmet = unmetOf(home, task)
762
763  if (unmet.length > 0) {
764    await tell(
765      $,
766      `needs:${home.id}:${task}`,
767      `Ledger: ${task} was started, but ${unmet.join(', ')} ${unmet.length === 1 ? 'is' : 'are'} not done and the plan puts ${unmet.length === 1 ? 'it' : 'them'} before ${task}. Finish ${unmet.length === 1 ? 'it' : 'them'} first, or say why the order does not matter here.`,
768    )
769  }
770
771  if (idleLanes(home, task).length > 0) {
772    $.clock.after(LANES_WAIT_MS, () => {
773      void (async () => {
774        const now = (await loadBook($)).runs.find(one => one.id === home.id)
775        const idle = now === undefined ? [] : idleLanes(now, task)
776
777        if (idle.length > 0) {
778          await tell(
779            $,
780            `lanes:${home.id}:${idle.join('|')}`,
781            `Ledger: ${task} is under way, but the lane${idle.length === 1 ? '' : 's'} ${idle.join(', ')} beside it ${idle.length === 1 ? 'has' : 'have'} not been started. Lanes of one fork need nothing of one another: start a subagent for each now, in one step, so they run at the same time.`,
782          )
783        }
784      })().catch(() => undefined)
785    })
786  }
787}
788
789// The subagents whose last turn has ended, so a tool call from one is seen as
790// it resuming; and the ends that arrived before their spawn was recorded.
791const over = new Set<string>()
792const earlyEnds = new Map<string, { reason: string; tokens: number | undefined; at: number; report?: string }>()
793
794const NO_RUN =`Nothing is planned. Call ${PLAN} first.`
795const NOTHING = 'Ledger: nothing is planned. The agent records a plan when it delegates one.'
796
797const text = (value: unknown): string | undefined =>
798  typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
799
800// The most characters kept of what the agent writes: a line each, so the
801// ledger stays cheap to write and quick to read.
802const ABOUT_MOST = 160
803const NOTE_MOST = 160
804const OUTCOME_MOST = 240
805const SUMMARY_MOST = 200
806const REPORT_MOST = 600
807// The most lines of a subagent's report the overview shows.
808const REPORT_LINES = 5
809
810// A line of text: its spaces folded, cut at `most`; undefined when empty.
811const brief = (value: unknown, most: number): string | undefined => {
812  const said = text(value)
813
814  return said === undefined ? undefined : cut(said.replace(/\s+/g, ' '), most)
815}
816
817// What a plan call says each unit is for; an entry that names no unit or says
818// nothing of it is left out.
819const unitNotes = (value: unknown): { name: string; about: string }[] =>
820  (Array.isArray(value) ? (value as unknown[]) : []).flatMap(one => {
821    const entry = (typeof one === 'object' && one !== null ? one : {}) as Record<string, unknown>
822    const name = text(entry.name)
823    const about = brief(entry.about, ABOUT_MOST)
824
825    return name === undefined || about === undefined ? [] : [{ name, about }]
826  })
827
828// The tasks of a plan call, or the reason they were refused.
829const tasksOf = (value: unknown): NewTask[] | string => {
830  if (!Array.isArray(value)) {
831    return 'plan needs tasks: a list of { id, unit, title, tier, check }.'
832  }
833
834  const tasks: NewTask[] = []
835
836  for (const one of value as unknown[]) {
837    const entry = (typeof one === 'object' && one !== null ? one : {}) as Record<string, unknown>
838    const id = text(entry.id)
839    const title = text(entry.title)
840    const lane = text(entry.lane)
841
842    if (id === undefined || title === undefined) {
843      return 'Every task needs an id and a title.'
844    }
845
846    const unit = text(entry.unit)
847    const tier = text(entry.tier)
848    const check = brief(entry.check, NOTE_MOST)
849    const about = brief(entry.about, ABOUT_MOST)
850    const needs = (Array.isArray(entry.needs) ? (entry.needs as unknown[]) : []).flatMap(need => text(need) ?? [])
851
852    tasks.push({
853      id,
854      title,
855      ...(lane !== undefined ? { lane } : {}),
856      ...(unit !== undefined ? { unit } : {}),
857      ...(tier !== undefined ? { tier } : {}),
858      ...(check !== undefined ? { check } : {}),
859      ...(about !== undefined ? { about } : {}),
860      ...(needs.length > 0 ? { needs } : {}),
861    })
862  }
863
864  return tasks
865}
866
867export const register: Register = (on, options) => {
868  // Whether a superpowers plan document is read as a run by itself, and
869  // whether finishing a task ticks the boxes under it that were missed.
870  const follows = options.followPlans === true
871  const ticks = options.tickPlans !== false
872
873  on('session.start', async ($, e, next) => {
874    await $.command.register({
875      name: 'ledger',
876      description: 'Show the run: /ledger [sessions | lanes <plan> | hide | show | clear]',
877    })
878    await $.tool.register({
879      name: 'plan',
880      description:
881        'Record the settled plan of an orchestrated run: its goal and every task. It becomes the current run; earlier runs are kept.',
882      inputSchema: {
883        type: 'object',
884        properties: {
885          goal: { type: 'string', description: 'One line naming what the run is for' },
886          units: {
887            type: 'array',
888            description: 'What each unit is for: one line on what its tasks add up to for the user',
889            items: {
890              type: 'object',
891              properties: { name: { type: 'string' }, about: { type: 'string' } },
892              required: ['name', 'about'],
893            },
894          },
895          tasks: {
896            type: 'array',
897            minItems: 1,
898            items: {
899              type: 'object',
900              properties: {
901                id: { type: 'string', description: 'A short id, as in T1' },
902                lane: {
903                  type: 'string',
904                  description: 'Where the plan has parallel lanes (tracks that can be worked on at once): the lane this task is in',
905                },
906                unit: { type: 'string', description: 'The unit the task belongs to; tasks reviewed together share one' },
907                title: { type: 'string' },
908                tier: { type: 'string', description: 'The model the task is meant for: haiku, sonnet or opus' },
909                check: { type: 'string', description: 'What the gate checks to call the task done' },
910                needs: {
911                  type: 'array',
912                  items: { type: 'string' },
913                  description: 'The ids of the tasks that must be done before this one starts, where that is not plain from the order',
914                },
915                about: {
916                  type: 'string',
917                  description:
918                    'One line on what the task is for: what it changes for the user, or which part of the code it touches',
919                },
920              },
921              required: ['id', 'title'],
922            },
923          },
924        },
925        required: ['goal', 'tasks'],
926      },
927    })
928    await $.tool.register({
929      name: 'task',
930      description:
931        'Record the state of every task that changed, in one call: done, gate-failed, or cancelled for one that will not be done.',
932      inputSchema: {
933        type: 'object',
934        properties: {
935          tasks: {
936            type: 'array',
937            minItems: 1,
938            items: {
939              type: 'object',
940              properties: {
941                id: { type: 'string' },
942                status: { type: 'string', enum: [...STATUSES] },
943                note: { type: 'string', description: 'With gate-failed: one line on what failed. With cancelled: why' },
944                outcome: { type: 'string', description: 'With done: one line on what changed, and in which files' },
945              },
946              required: ['id', 'status'],
947            },
948          },
949        },
950        required: ['tasks'],
951      },
952    })
953    await $.tool.register({
954      name: 'finding',
955      description: 'Report every problem a review found, in one call. Subagents call this too.',
956      inputSchema: {
957        type: 'object',
958        properties: {
959          findings: {
960            type: 'array',
961            minItems: 1,
962            items: {
963              type: 'object',
964              properties: {
965                path: { type: 'string', description: 'The file, from the project root' },
966                line: { type: 'integer' },
967                severity: { type: 'string', enum: [...SEVERITIES] },
968                summary: { type: 'string', description: 'One line: what is wrong and what it causes' },
969                task: { type: 'string', description: 'The task id, when known' },
970              },
971              required: ['path', 'severity', 'summary'],
972            },
973          },
974        },
975        required: ['findings'],
976      },
977    })
978    await $.tool.register({
979      name: 'fixed',
980      description: 'Mark findings dealt with, by id.',
981      inputSchema: {
982        type: 'object',
983        properties: { ids: { type: 'array', items: { type: 'integer' }, minItems: 1 } },
984        required: ['ids'],
985      },
986    })
987    await $.tool.register({
988      name: 'report',
989      description: 'Read the run: every task and its state, the agents spawned, and the open findings.',
990      inputSchema: { type: 'object', properties: {} },
991    })
992
993    try {
994      await fileBySession($)
995      seen = undefined
996      await sync($)
997
998      // A plan document may have changed while no session was watching it.
999      for (const one of (await loadBook($)).runs) {
1000        if (one.doc !== undefined) {
1001          followed.add(one.doc.path)
1002
1003          if (one.doneAt === undefined) {
1004            await followDoc($, one.doc.path).catch(() => '')
1005          }
1006        }
1007      }
1008    } catch {
1009      $.ui.toast('The ledger could not be loaded.')
1010    }
1011
1012    return next(e)
1013  })
1014
1015  // The session ends, and after a /clear or a resume the process goes on under
1016  // another: its entry leaves the status line, and the next prompt brings the
1017  // ledger of the session it is then in.
1018  on('session.end', async ($, e, next) => {
1019    const result = await next(e)
1020
1021    seen = undefined
1022    $.ui.status(undefined)
1023
1024    return result
1025  })
1026
1027  on('prompt.submit', async ($, e, next) => {
1028    await sync($).catch(() => undefined)
1029
1030    return next(e)
1031  })
1032
1033  on('prompt.compose', async ($, e, next) => {
1034    const composed = await next(e)
1035
1036    return {
1037      sections: [...composed.sections, { id: 'ledger:guide', text: GUIDE, scope: 'session' }],
1038    }
1039  })
1040
1041  on('tool.call', { tool: PLAN }, async ($, e) => {
1042    if (e.agentId !== undefined) {
1043      return { deny: SUBAGENT_REFUSAL }
1044    }
1045
1046    const tasks = tasksOf(e.tasks)
1047
1048    if (typeof tasks === 'string') {
1049      return { deny: tasks }
1050    }
1051
1052    const sessionId = await $.session.id()
1053    const goal = text(e.goal) ?? ''
1054    const notes = unitNotes(e.units)
1055    // A task id names one task among the runs under way: that is how every
1056    // later write finds its run.
1057    const changed = await changeBook($, (book, at) => {
1058      const taken = clash(
1059        book,
1060        tasks.map(one => one.id),
1061      )
1062      const made = taken ?? plan(goal, tasks, at, sessionId, notes)
1063
1064      return typeof made === 'string' ? made : put(book, made, at)
1065    })
1066
1067    if ('error' in changed) {
1068      return { deny: changed.error }
1069    }
1070
1071    await update($, isHidden, () => false)
1072    await refresh($)
1073
1074    return { result: `Planned ${tasks.length} task${tasks.length === 1 ? '' : 's'}.` }
1075  })
1076
1077  on('tool.call', { tool: TASK }, async ($, e) => {
1078    if (e.agentId !== undefined) {
1079      return { deny: SUBAGENT_REFUSAL }
1080    }
1081
1082    // Every task that changed, in one call; one task's fields alone are taken too.
1083    const entries = (Array.isArray(e.tasks) ? (e.tasks as unknown[]) : [e]).map(
1084      one => (typeof one === 'object' && one !== null ? one : {}) as Record<string, unknown>,
1085    )
1086    const updates = entries.flatMap(entry => {
1087      const id = text(entry.id)
1088      const status = STATUSES.find(one => one === entry.status)
1089
1090      return id === undefined || status === undefined
1091        ? []
1092        : [{ id, status, note: brief(entry.note, NOTE_MOST), outcome: brief(entry.outcome, OUTCOME_MOST) }]
1093    })
1094
1095    if (updates.length === 0 || updates.length < entries.length) {
1096      return { deny: `Each task needs an id and a status, one of ${STATUSES.join(', ')}.` }
1097    }
1098
1099    // Each goes to the run its task is in. All of them or none: one id no run
1100    // has refuses the call, and says which.
1101    const changed = await changeBook($, (book, at) => {
1102      if (book.runs.length === 0) {
1103        return NO_RUN
1104      }
1105
1106      let after = book
1107
1108      for (const one of updates) {
1109        const owner = ownerOf(after, one.id)
1110        const next: LedgerRun | string =
1111          owner === undefined
1112            ? `No task ${one.id}. The tasks under way are ${underWay(after)
1113                .flatMap(run => run.tasks.map(task => task.id))
1114                .join(', ')}.`
1115            : setTask(owner, one.id, one.status, one.note, one.outcome)
1116
1117        if (typeof next === 'string') {
1118          return next
1119        }
1120
1121        after = put(after, next, at)
1122      }
1123
1124      return after
1125    })
1126
1127    if ('error' in changed) {
1128      return { deny: changed.error }
1129    }
1130
1131    // A task of a run read from a plan document changed: how it stands is
1132    // written under it there, and the boxes under a done task that were missed
1133    // are ticked, where the setting asks for that.
1134    for (const one of changed.book.runs) {
1135      if (one.doc !== undefined && updates.some(update => one.tasks.some(task => task.id === update.id))) {
1136        await tickDoc($, one.doc.path, false, ticks).catch(() => 0)
1137      }
1138    }
1139
1140    // What the write leaves to settle is said with it: findings still open on
1141    // a task marked done, or on a run whose tasks are now all done.
1142    const doneIds = updates.flatMap(one => (one.status === 'done' ? [one.id] : []))
1143    const left = changed.book.runs.flatMap(one =>
1144      one.tasks.some(task => doneIds.includes(task.id)) && leftOpen(one, doneIds) !== '' ? [leftOpen(one, doneIds)] : [],
1145    )
1146
1147    return { result: [updates.map(one => `${one.id} ${one.status}`).join(', '), ...left].join('\n') }
1148  })
1149
1150  on('tool.call', { tool: FINDING }, async ($, e) => {
1151    // Every finding of a review, in one call; one finding's fields alone too.
1152    const entries = (Array.isArray(e.findings) ? (e.findings as unknown[]) : [e]).map(
1153      one => (typeof one === 'object' && one !== null ? one : {}) as Record<string, unknown>,
1154    )
1155    const reported = entries.flatMap(entry => {
1156      const path = text(entry.path)
1157      const summary = brief(entry.summary, SUMMARY_MOST)
1158      const severity = SEVERITIES.find(one => one === entry.severity)
1159      const line =
1160        typeof entry.line === 'number' && Number.isInteger(entry.line) && entry.line > 0 ? entry.line : undefined
1161      const task = text(entry.task)
1162
1163      return path === undefined || summary === undefined || severity === undefined
1164        ? []
1165        : [
1166            {
1167              path,
1168              severity,
1169              summary,
1170              ...(line !== undefined ? { line } : {}),
1171              ...(task !== undefined ? { task } : {}),
1172            },
1173          ]
1174    })
1175
1176    if (reported.length === 0 || reported.length < entries.length) {
1177      return { deny: `Each finding needs a path, a summary and a severity, one of ${SEVERITIES.join(', ')}.` }
1178    }
1179
1180    const agentId = e.agentId
1181    let first = 0
1182    // Each goes to the run of the task it names, else to the run the
1183    // reporting subagent was spawned in (and to that subagent's task), else to
1184    // the current run.
1185    const changed = await changeBook($, (book, at) => {
1186      let after = book
1187      first = nextFinding(book)
1188
1189      for (const one of reported) {
1190        const home =
1191          (one.task !== undefined ? ownerOf(after, one.task) : undefined) ??
1192          runOfAgent(after, agentId) ??
1193          currentOf(after)
1194
1195        if (home === null || home === undefined) {
1196          return NO_RUN
1197        }
1198
1199        const own = home.spawns.find(spawn => spawn.agentId === agentId)?.task
1200
hooks/doc.ts 430 lines
1// A plan document as the ledger's input: a superpowers plan (or any document
2// laid out like one) read into tasks and their steps, a run made from it, and
3// its checkboxes ticked. Free of the engine, as run.ts is.
4
5import type { LedgerRun, LedgerStep, LedgerTask } from '../types'
6
7// One task of the document: where its heading is, and where each of its
8// checkbox steps is. Lines are counted from 0.
9export type DocTask = {
10  // The number its heading gives it ("3" of "### Task 3: ..."), or its place.
11  n: string
12  title: string
13  unit: string
14  line: number
15  steps: { line: number; text: string; isDone: boolean }[]
16  // What its labelled lines say (`**Lane:** API`), where it has them: the lane
17  // it is in, the model it is meant for, what its gate checks, and the earlier
18  // tasks it needs done first, by number (none is an empty list; with no such
19  // line, undefined: nobody has said).
20  lane?: string
21  tier?: string
22  check?: string
23  needs?: string[]
24  // How the ledger last wrote it stood, for a reader with no ledger of it.
25  said?: { status: 'done' | 'gate-failed' | 'cancelled'; text: string }
26  // The files its `**Files:**` list names, without line ranges.
27  files: string[]
28  // Where each line the ledger writes is, for the ones the task has.
29  labels: { needs?: number; lane?: number; status?: number }
30}
31
32export type PlanDoc = { title: string; tasks: DocTask[] }
33
34// Where the superpowers skills save their plans.
35export const PLAN_PATH = /(^|\/)docs\/superpowers\/plans\/[^/]+\.md$/
36
37const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/
38const TASK = /^Task\s+([\w.-]+?)\s*[:.)-]?\s+(.+)$/i
39const BARE_TASK = /^Task\s+([\w.-]+)\s*[:.)-]?$/i
40const BOX = /^\s*[-*+]\s+\[( |x|X)\]\s+(.*)$/
41// A labelled line under a task (`**Lane:** API`), and a file its list names
42// (`- Modify: src/queue.ts:10-40`, the path in backticks or bare).
43const LABEL = /^\s*\*\*([A-Za-z]+):\*\*\s*(.*?)\s*$/
44const FILE = /^\s*[-*+]\s+(?:Create|Modify|Test|Delete|Update|Move|Rename)\s*:\s*`?([^`\s]+)`?/i
45
46// The task numbers a `**Needs:**` line names: "Task 1, Task 2", "1 and 2",
47// or "none".
48const numbersOf = (value: string): string[] =>
49  /^(none|nothing|-|—)?$/i.test(value.trim())
50    ? []
51    : value
52        .replace(/\b(tasks?|and)\b/gi, ' ')
53        .split(/[\s,;]+/)
54        .filter(Boolean)
55
56// A step's words without the marks around them.
57const plain = (text: string): string => text.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`/g, '').trim()
58
59// The lines of a document with those inside a code fence blanked: a fenced
60// example may hold headings and checkboxes that are not the plan's.
61const unfenced = (text: string): string[] => {
62  let isFenced = false
63
64  return text.split('\n').map(line => {
65    if (/^\s*(```|~~~)/.test(line)) {
66      isFenced = !isFenced
67
68      return ''
69    }
70
71    return isFenced ? '' : line
72  })
73}
74
75// Reads a document laid out as the superpowers plans are: a `### Task N: name`
76// heading per task, checkbox steps beneath it, and under the heading the
77// labelled lines the ledger's recipe adds (`**Unit:**`, `**Lane:**`,
78// `**Tier:**`, `**Gate:**`, `**Needs:**`, `**Status:**`) and the task's
79// `**Files:**` list. Undefined when it has no such task: it is laid out some
80// other way.
81//
82// A task's unit is what its `**Unit:**` line says. With no such line it is
83// the `##` section the task is under, but only where the tasks are under more
84// than one: a plan whose tasks all follow one section ("File Map") has no
85// units, that section not being one.
86export const parsePlan = (text: string): PlanDoc | undefined => {
87  const lines = unfenced(text)
88  const tasks: DocTask[] = []
89  const named = new Set<DocTask>()
90  let title = ''
91  let section = ''
92  let task: DocTask | undefined
93
94  lines.forEach((line, at) => {
95    const heading = HEADING.exec(line)
96
97    if (heading !== null) {
98      const words = plain(heading[2] ?? '')
99      const head = TASK.exec(words) ?? BARE_TASK.exec(words)
100
101      if (head !== null) {
102        task = { n: head[1] ?? '', title: head[2] ?? words, unit: section, line: at, steps: [], files: [], labels: {} }
103        tasks.push(task)
104      } else {
105        // Any other heading ends the task before it; a `##` one is a section.
106        task = undefined
107
108        if ((heading[1] ?? '').length === 1 && title === '') {
109          title = words
110        } else if ((heading[1] ?? '').length === 2) {
111          section = words
112        }
113      }
114
115      return
116    }
117
118    if (task === undefined) {
119      return
120    }
121
122    const box = BOX.exec(line)
123
124    if (box !== null) {
125      task.steps.push({ line: at, text: plain(box[2] ?? ''), isDone: box[1] !== ' ' })
126
127      return
128    }
129
130    const file = FILE.exec(line)
131
132    if (file !== null) {
133      task.files.push((file[1] ?? '').replace(/:\d+(-\d+)?$/, ''))
134
135      return
136    }
137
138    const label = LABEL.exec(line)
139    const key = (label?.[1] ?? '').toLowerCase()
140    const value = plain(label?.[2] ?? '')
141
142    if (key === 'unit' && value !== '') {
143      task.unit = value
144      named.add(task)
145    } else if (key === 'lane') {
146      task.labels.lane = at
147
148      if (value !== '') {
149        task.lane = value
150      }
151    } else if (key === 'tier' && value !== '') {
152      task.tier = value
153    } else if ((key === 'gate' || key === 'check') && value !== '') {
154      task.check = value
155    } else if (key === 'needs' || key === 'after') {
156      task.labels.needs = at
157      task.needs = numbersOf(value)
158    } else if (key === 'status') {
159      const said = /^(done|gate failed|cancelled)\s*(?:[—:-]\s*)?(.*)$/i.exec(value)
160      const word = (said?.[1] ?? '').toLowerCase()
161
162      task.labels.status = at
163
164      if (said !== null) {
165        task.said = {
166          status: word === 'done' ? 'done' : word === 'cancelled' ? 'cancelled' : 'gate-failed',
167          text: said[2] ?? '',
168        }
169      }
170    }
171  })
172
173  // One section over every task is not a unit; a unit a task names stands.
174  const sections = new Set(tasks.filter(one => !named.has(one)).map(one => one.unit))
175
176  if (sections.size < 2) {
177    for (const one of tasks) {
178      if (!named.has(one)) {
179        one.unit = ''
180      }
181    }
182  }
183
184  return tasks.length === 0 ? undefined : { title, tasks }
185}
186
187// What a small model is given to lay out a document the parser could not
188// read: only its headings and checkboxes, each with its line number, so the
189// request and the answer are both a few lines.
190export const outlineOf = (text: string): string =>
191  unfenced(text)
192    .flatMap((line, at) => (HEADING.test(line) || BOX.test(line) ? [`${at}: ${line.trim().slice(0, 120)}`] : []))
193    .join('\n')
194
195export const outlineRequest = (outline: string): string =>
196  [
197    'Below are the headings and checkboxes of a plan document, each line led by its line number.',
198    'Group them into tasks: a task is a piece of work with checkbox steps under it.',
199    'Answer with JSON only, no prose: [{"title": "short name", "head": <line of its heading or first line>, "steps": [<line of each checkbox>]}].',
200    'Use only line numbers that appear below. Leave out headings that hold no checkbox.',
201    '',
202    outline,
203  ].join('\n')
204
205// The document as a small model laid it out: its answer names lines, and the
206// words and ticks are read from the document itself, so the model cannot
207// misreport them. Undefined when the answer names no usable task.
208export const planFromOutline = (text: string, answer: string): PlanDoc | undefined => {
209  const lines = unfenced(text)
210  let listed: unknown
211
212  try {
213    listed = JSON.parse(answer.slice(answer.indexOf('['), answer.lastIndexOf(']') + 1))
214  } catch {
215    return undefined
216  }
217
218  const tasks = (Array.isArray(listed) ? (listed as unknown[]) : []).flatMap((one, at): DocTask[] => {
219    const entry = (typeof one === 'object' && one !== null ? one : {}) as Record<string, unknown>
220    const steps = (Array.isArray(entry.steps) ? (entry.steps as unknown[]) : []).flatMap(line => {
221      const box = typeof line === 'number' ? BOX.exec(lines[line] ?? '') : null
222
223      return box === null ? [] : [{ line: line as number, text: plain(box[2] ?? ''), isDone: box[1] !== ' ' }]
224    })
225    const head = typeof entry.head === 'number' ? entry.head : (steps[0]?.line ?? -1)
226    const said = typeof entry.title === 'string' ? entry.title.trim() : ''
227
228    return steps.length === 0
229      ? []
230      : [
231          {
232            n: String(at + 1),
233            title: said === '' ? `Task ${at + 1}` : said.slice(0, 120),
234            unit: '',
235            line: head,
236            steps,
237            files: [],
238            labels: {},
239          },
240        ]
241  })
242  const title = plain(HEADING.exec(lines.find(line => /^#\s/.test(line)) ?? '')?.[2] ?? '')
243
244  return tasks.length === 0 ? undefined : { title, tasks }
245}
246
247export const taskIdOf = (task: DocTask): string => `T${task.n}`
248
249const stateOf = (task: DocTask, before: LedgerTask | undefined): LedgerTask['status'] => {
250  const ticked = task.steps.filter(one => one.isDone).length
251
252  // Every box ticked is done. Short of that the ledger's own word stands
253  // where it has one: a task marked done whose boxes were missed stays done
254  // (and its boxes are ticked), and a failed gate stays failed.
255  // A reader with no ledger of the task takes the document's `**Status:**`
256  // line for it: what another session's ledger wrote there.
257  return task.steps.length > 0 && ticked === task.steps.length
258    ? 'done'
259    : before?.status === 'done' || before?.status === 'gate-failed' || before?.status === 'cancelled'
260      ? before.status
261      : before === undefined && task.said !== undefined
262        ? task.said.status
263        : ticked > 0 || before?.status === 'running'
264          ? 'running'
265          : 'todo'
266}
267
268// The run a document makes, or the run it already made brought in step with
269// it: tasks and steps are the document's, and what the ledger added (notes,
270// outcomes, tiers, agents, findings) is kept.
271export const runFromDoc = (
272  doc: PlanDoc,
273  path: string,
274  isLaidOutByModel: boolean,
275  now: number,
276  sessionId: string,
277  before?: LedgerRun,
278): LedgerRun => {
279  const fallback = doc.title === '' ? (path.split('/').pop() ?? 'Plan').replace(/\.md$/, '') : doc.title
280  const tasks = doc.tasks.map((task): LedgerTask => {
281    const was = before?.tasks.find(one => one.id === taskIdOf(task))
282    const steps: LedgerStep[] = task.steps.map(one => ({ text: one.text, isDone: one.isDone }))
283
284    // The lane, tier and gate are the document's while it names them; a lane
285    // it no longer names is gone, so the task is back in the line.
286    const { lane: _lane, needs: _needs, ...kept } = was ?? ({} as Partial<LedgerTask>)
287    const status = stateOf(task, was)
288    const tier = task.tier ?? was?.tier
289    const check = task.check ?? was?.check
290    // What the document says of a task this ledger never saw: its outcome, or
291    // why its gate failed.
292    const told = was === undefined && task.said !== undefined && task.said.text !== '' ? task.said : undefined
293
294    return {
295      ...kept,
296      id: taskIdOf(task),
297      ...(task.lane !== undefined ? { lane: task.lane } : {}),
298      // A plan with no units has every task in "main", which draws no unit.
299      unit: task.unit === '' ? 'main' : task.unit,
300      title: task.title,
301      ...(tier !== undefined ? { tier } : {}),
302      ...(check !== undefined ? { check } : {}),
303      status,
304      ...(told?.status === 'done' ? { outcome: told.text } : {}),
305      ...(told?.status === 'gate-failed' || told?.status === 'cancelled' ? { note: told.text } : {}),
306      // What it needs, as the document numbers its tasks.
307      ...(task.needs !== undefined && task.needs.length > 0 ? { needs: task.needs.map(n => `T${n}`) } : {}),
308      steps,
309    }
310  })
311
312  return {
313    ...(before ?? { id: 0, startedAt: now, spawns: [], findings: [], nextFinding: 1 }),
314    goal: fallback,
315    sessionId,
316    doc: { path, ...(isLaidOutByModel ? { isLaidOutByModel: true as const } : {}) },
317    tasks,
318  }
319}
320
321// The document with the open boxes ticked under each task the run has as
322// done, and how many that was. Only `[ ]` becomes `[x]`, only on a line that
323// is still an open checkbox, and nothing else is changed.
324export const ticked = (text: string, doc: PlanDoc, run: LedgerRun): { text: string; count: number } => {
325  const done = new Set(run.tasks.filter(one => one.status === 'done').map(one => one.id))
326  const lines = text.split('\n')
327  let count = 0
328
329  for (const task of doc.tasks.filter(one => done.has(taskIdOf(one)))) {
330    for (const step of task.steps.filter(one => !one.isDone)) {
331      const line = lines[step.line] ?? ''
332
333      if (/^\s*[-*+]\s+\[ \]\s/.test(line)) {
334        lines[step.line] = line.replace('[ ]', '[x]')
335        count += 1
336      }
337    }
338  }
339
340  return { text: count === 0 ? text : lines.join('\n'), count }
341}
342
343// The lines the ledger writes under a task's heading, in the order it writes
344// them. Everything else in a document is the author's.
345const WRITTEN = [
346  ['needs', 'Needs'],
347  ['lane', 'Lane'],
348  ['status', 'Status'],
349] as const
350
351export type DocLabels = { needs?: string | null; lane?: string | null; status?: string | null }
352
353// The document with the ledger's own lines set under each task named in
354// `labels` (by its number): a value replaces the line or adds it under the
355// heading, null takes the line out, and a label left out is left alone.
356// Nothing else is changed.
357export const labelled = (text: string, doc: PlanDoc, labels: ReadonlyMap<string, DocLabels>): string => {
358  const lines = text.split('\n')
359  let isChanged = false
360
361  // From the last task up, so a line added or taken out moves no task above.
362  for (const task of [...doc.tasks].reverse()) {
363    const wanted = labels.get(task.n)
364
365    if (wanted === undefined) {
366      continue
367    }
368
369    const added: string[] = []
370
371    // The lines the task has, the lowest first for the same reason.
372    for (const [key, word] of [...WRITTEN].sort((a, b) => (task.labels[b[0]] ?? -1) - (task.labels[a[0]] ?? -1))) {
373      const value = wanted[key]
374      const at = task.labels[key]
375
376      if (value === undefined || at === undefined) {
377        continue
378      }
379
380      const line = `**${word}:** ${value}`
381
382      if (value === null) {
383        lines.splice(at, 1)
384        isChanged = true
385      } else if (lines[at] !== line) {
386        lines[at] = line
387        isChanged = true
388      }
389    }
390
391    for (const [key, word] of WRITTEN) {
392      const value = wanted[key]
393
394      if (typeof value === 'string' && task.labels[key] === undefined) {
395        added.push(`**${word}:** ${value}`)
396      }
397    }
398
399    if (added.length > 0) {
400      // Under the heading, a blank line apart from it and from what follows.
401      const isSpaced = (lines[task.line + 1] ?? '').trim() === ''
402
403      lines.splice(task.line + 1, 0, '', ...added, ...(isSpaced ? [] : ['']))
404      isChanged = true
405    }
406  }
407
408  return isChanged ? lines.join('\n') : text
409}
410
411// How each task of a run stands, as the ledger writes it into the run's
412// document: done with what was done, a failed gate with why, and no line for
413// a task that is neither.
414export const statusLabels = (doc: PlanDoc, run: LedgerRun): Map<string, DocLabels> =>
415  new Map(
416    doc.tasks.map(task => {
417      const now = run.tasks.find(one => one.id === taskIdOf(task))
418      const words =
419        now?.status === 'done'
420          ? `done${now.outcome === undefined ? '' : ` — ${now.outcome}`}`
421          : now?.status === 'gate-failed'
422            ? `gate failed${now.note === undefined ? '' : ` — ${now.note}`}`
423            : now?.status === 'cancelled'
424              ? `cancelled${now.note === undefined ? '' : ` — ${now.note}`}`
425              : null
426
427      return [task.n, { status: words }]
428    }),
429  )
430
hooks/kit/icons.ts 60 lines
1// Shared by the lens, parked and ledger mods. The source is the mod-kit folder;
2// each mod carries a copy under hooks/kit, written there by sync.sh. Edit the
3// source and sync, never a copy.
4
5export type Icon = { glyph: string; color: string }
6
7// Nerd Font glyphs, as a terminal file tree draws them, in each language's
8// usual colour. They need a Nerd Font, or a terminal that ships the symbols.
9export const FILE_ICONS: readonly (readonly [pattern: RegExp, glyph: string, color: string])[] = [
10  [/\.pyi?$/, '\u{e73c}', '#ffd43b'],
11  [/\.[cm]?[tj]sx$/, '\u{e7ba}', '#20c2e3'],
12  [/\.[cm]?ts$/, '\u{e628}', '#519aba'],
13  [/\.[cm]?js$/, '\u{e74e}', '#cbcb41'],
14  [/\.json$/, '\u{e60b}', '#cbcb41'],
15  [/\.(tf|tfvars)$/, '\u{e69a}', '#7b42bc'],
16  [/\.(ya?ml|toml|ini|cfg|env)$/, '\u{e615}', '#6d8086'],
17  [/\.(md|mdx)$/, '\u{e73e}', '#dddddd'],
18  [/\.(sh|bash|zsh)$/, '\u{e795}', '#4d5a5e'],
19  [/\.(css|scss|less)$/, '\u{e749}', '#42a5f5'],
20  [/\.html?$/, '\u{e736}', '#e44d26'],
21  [/\.sql$/, '\u{e706}', '#dad8d8'],
22  [/\.(png|jpe?g|gif|svg|webp|ico)$/, '\u{f1c5}', '#a074c4'],
23  [/(^|\/)Dockerfile$/, '\u{f308}', '#458ee6'],
24  [/(^|\/)\.git(ignore|attributes)$/, '\u{e702}', '#f54d27'],
25  [/\.lock$/, '\u{f023}', '#bbbbbb'],
26]
27
28// The glyphs the mods draw for their own things, one name each.
29export const ICON = {
30  file: '\u{f15b}',
31  folder: '\u{f07b}',
32  folderOpen: '\u{f07c}',
33  needs: '\u{f059}',
34  blocking: '\u{f071}',
35  fyi: '\u{f05a}',
36  done: '\u{f058}',
37  failed: '\u{f057}',
38  running: '\u{f110}',
39  todo: '\u{f10c}',
40  thread: '\u{f075}',
41  options: '\u{f0cb}',
42  preferred: '\u{f005}',
43  tasks: '\u{f0ae}',
44  agents: '\u{f085}',
45  finding: '\u{f188}',
46} as const
47
48export const FILE_COLOR = '#6d8086'
49export const FOLDER_COLOR = '#dcb67a'
50export const STAR_COLOR = '#ffd43b'
51
52export const iconOf = (path: string): Icon => {
53  const hit = FILE_ICONS.find(([pattern]) => pattern.test(path))
54
55  return hit === undefined ? { glyph: ICON.file, color: FILE_COLOR } : { glyph: hit[1], color: hit[2] }
56}
57
58// The icon of a ref's file type; a ref is a path, or path:line.
59export const refIcon = (ref: string): Icon => iconOf(ref.replace(/:\d+(?::\d+)?$/, ''))
60
hooks/book.ts 306 lines
1// A session's runs, kept together: every run planned in it, the newest last,
2// and which one is current. A session resumed finds its book as it left it.
3// Free of the engine, as run.ts is.
4
5import type { LedgerRun, LedgerSessionNote } from '../types'
6import { ICON } from './kit/icons'
7import { countsOf, isDone, isOver, isRun, isStalled, statusText, tokensText } from './run'
8
9// `current` is the id of the run the tools record against (0 for none): the
10// one planned last, or the one the user picked. `cwd` is the folder the
11// session ran in, for the list of sessions.
12export type Book = { nextId: number; current: number; runs: LedgerRun[]; cwd?: string }
13
14export const EMPTY: Book = { nextId: 1, current: 0, runs: [] }
15
16// How many runs a session keeps. Past it the oldest done ones are dropped; a
17// run not done is never dropped.
18export const KEPT = 40
19
20export const isBook = (value: unknown): value is Book =>
21  typeof value === 'object' &&
22  value !== null &&
23  typeof (value as Book).nextId === 'number' &&
24  Array.isArray((value as Book).runs) &&
25  (value as Book).runs.every(isRun)
26
27// What the store held before runs were kept together: one run, or nothing.
28export const bookOf = (stored: unknown, old: unknown): Book =>
29  isBook(stored) ? stored : isRun(old) ? { nextId: 2, current: 1, runs: [{ ...old, id: 1 }] } : EMPTY
30
31export const currentOf = (book: Book): LedgerRun | null =>
32  book.runs.find(one => one.id === book.current) ?? null
33
34// Whether a run has nothing left: every task done, no agent running and no
35// finding open.
36export const isSettled = (run: LedgerRun): boolean =>
37  isDone(run) &&
38  run.spawns.every(one => one.endedAt !== undefined) &&
39  run.findings.every(one => one.status === 'fixed')
40
41// A run with its `doneAt` as it should stand: set when it settles or the user
42// closed it, kept while it stays so, and gone when work reopens a run that
43// had only settled.
44export const settled = (run: LedgerRun, now: number): LedgerRun => {
45  const isOver = run.isClosed === true || isSettled(run)
46
47  if (isOver === (run.doneAt !== undefined)) {
48    return run
49  }
50
51  if (isOver) {
52    return { ...run, doneAt: now }
53  }
54
55  const { doneAt: _d, ...rest } = run
56
57  return rest
58}
59
60const pruned = (book: Book): Book => {
61  const extra = book.runs.length - KEPT
62  const drop = new Set(
63    book.runs
64      .filter(one => one.doneAt !== undefined && one.id !== book.current)
65      .slice(0, Math.max(0, extra))
66      .map(one => one.id),
67  )
68
69  return drop.size === 0 ? book : { ...book, runs: book.runs.filter(one => !drop.has(one.id)) }
70}
71
72// Keeps a run: a new one (id 0) is numbered, added and made current; one the
73// book has is replaced. Either way it is settled first.
74export const put = (book: Book, run: LedgerRun, now: number): Book =>
75  run.id === 0
76    ? pruned({
77        ...book,
78        nextId: book.nextId + 1,
79        current: book.nextId,
80        runs: [...book.runs, settled({ ...run, id: book.nextId, changedAt: now }, now)],
81      })
82    : { ...book, runs: book.runs.map(one => (one.id === run.id ? settled({ ...run, changedAt: now }, now) : one)) }
83
84// Forgets a run for good. Clearing the current one leaves none current.
85export const cleared = (book: Book, id: number): Book => ({
86  ...book,
87  current: book.current === id ? 0 : book.current,
88  runs: book.runs.filter(one => one.id !== id),
89})
90
91// The user closes a run by hand, or opens it again.
92export const closed = (book: Book, id: number, isClosed: boolean, now: number): Book | string => {
93  const run = book.runs.find(one => one.id === id)
94
95  if (run === undefined) {
96    return `No run ${id}.`
97  }
98
99  const { isClosed: _c, ...rest } = run
100
101  return put(book, isClosed ? { ...rest, isClosed: true } : rest, now)
102}
103
104// The runs as the list shows them: those not done, the newest first, then
105// (when asked) the done ones, the latest done first.
106export const listed = (book: Book, isAll: boolean): LedgerRun[] => [
107  ...book.runs.filter(one => one.doneAt === undefined).reverse(),
108  ...(isAll
109    ? book.runs
110        .filter(one => one.doneAt !== undefined)
111        .sort((a, b) => (b.doneAt ?? 0) - (a.doneAt ?? 0))
112    : []),
113]
114
115// A run in a few marks, for its row in the list: tasks done of all, then
116// only what is wrong or under way.
117export const runMarks = (run: LedgerRun): string => {
118  const counts = countsOf(run)
119
120  return [
121    `${counts.done}/${counts.tasks}`,
122    counts.failed > 0 ? `${ICON.failed} ${counts.failed}` : '',
123    counts.openFindings > 0 ? `${ICON.finding} ${counts.openFindings}` : '',
124    counts.tokens > 0 ? tokensText(counts.tokens) : '',
125  ]
126    .filter(Boolean)
127    .join(' · ')
128}
129
130// How many subagents are running across every run not done.
131export const busyOf = (book: Book): number =>
132  book.runs
133    .filter(one => one.doneAt === undefined)
134    .reduce((sum, one) => sum + one.spawns.filter(spawn => spawn.endedAt === undefined).length, 0)
135
136// Whether work is under way in a run not done: a subagent running, or a task
137// marked running that has not stalled. It is what the turning mark stands for.
138export const isTurning = (book: Book, now: number): boolean =>
139  busyOf(book) > 0 ||
140  book.runs.some(
141    one => one.doneAt === undefined && one.tasks.some(task => task.status === 'running' && !isStalled(one, task, now)),
142  )
143
144// The runs still under way, the newest first: where a write looks for its run.
145export const underWay = (book: Book): LedgerRun[] =>
146  book.runs.filter(one => one.doneAt === undefined).reverse()
147
148// The run a task belongs to: one under way before one that is done, and of
149// two the newer.
150export const ownerOf = (book: Book, taskId: string): LedgerRun | undefined =>
151  [...underWay(book), ...book.runs.filter(one => one.doneAt !== undefined).reverse()].find(one =>
152    one.tasks.some(task => task.id === taskId),
153  )
154
155// The run a subagent was recorded in.
156export const runOfAgent = (book: Book, agentId: string | undefined): LedgerRun | undefined =>
157  agentId === undefined ? undefined : book.runs.find(one => one.spawns.some(spawn => spawn.agentId === agentId))
158
159// The run a finding is in.
160export const runOfFinding = (book: Book, id: number): LedgerRun | undefined =>
161  book.runs.find(one => one.findings.some(finding => finding.id === id))
162
163// The ids a new plan may not use: a task id must name one task among the runs
164// under way, since that is how a write finds its run. The answer names them.
165export const clash = (book: Book, ids: readonly string[]): string | undefined => {
166  const taken = ids.filter(id => underWay(book).some(one => one.tasks.some(task => task.id === id)))
167
168  return taken.length === 0
169    ? undefined
170    : `Task ${taken.length === 1 ? 'id' : 'ids'} ${taken.join(', ')} ${taken.length === 1 ? 'is' : 'are'} in use by a run still under way. Give this plan's tasks ids of their own, for example with a prefix.`
171}
172
173// The number the next finding takes: one count for the whole book, so a
174// finding's number names it whichever run it is in.
175export const nextFinding = (book: Book): number =>
176  Math.max(1, ...book.runs.map(one => one.nextFinding))
177
178// The status line's entry for the whole book: the task work is on in the
179// newest run under way, and how many more tasks are not done across them all.
180// Nothing with no run under way.
181export const bookStatus = (book: Book): string | undefined => {
182  const [newest, ...rest] = underWay(book)
183
184  return newest === undefined
185    ? undefined
186    : statusText(
187        newest,
188        rest.reduce((sum, one) => sum + one.tasks.filter(task => !isOver(task)).length, 0),
189      )
190}
191
192// The sessions that have a ledger, each in a line, the latest changed first:
193// what the list of sessions reads, so no book is opened to draw it.
194export const isIndex = (value: unknown): value is LedgerSessionNote[] =>
195  Array.isArray(value) &&
196  value.every(
197    one =>
198      typeof one === 'object' &&
199      one !== null &&
200      typeof (one as LedgerSessionNote).id === 'string' &&
201      typeof (one as LedgerSessionNote).cwd === 'string' &&
202      typeof (one as LedgerSessionNote).at === 'number',
203  )
204
205// How many sessions' ledgers are kept. Past it the ones changed longest ago
206// are dropped.
207export const SESSIONS_KEPT = 60
208
209// A session's book in a line, as it stood at `at`.
210export const noteOf = (id: string, book: Book, at: number): LedgerSessionNote => ({
211  id,
212  cwd: book.cwd ?? '',
213  at,
214  goal: (currentOf(book) ?? book.runs.at(-1))?.goal ?? '',
215  open: underWay(book).length,
216  ...(isTurning(book, at) ? { busy: true as const } : {}),
217  size: JSON.stringify(book).length,
218  runs: book.runs.length,
219})
220
221// The index with a session's line put first, or taken out when its book has
222// no run left; and the sessions dropped for being past the limit.
223export const noted = (
224  index: readonly LedgerSessionNote[],
225  note: LedgerSessionNote,
226): { index: LedgerSessionNote[]; dropped: string[] } => {
227  const all = [...(note.runs > 0 ? [note] : []), ...index.filter(one => one.id !== note.id)].sort(
228    (a, b) => b.at - a.at,
229  )
230
231  return { index: all.slice(0, SESSIONS_KEPT), dropped: all.slice(SESSIONS_KEPT).map(one => one.id) }
232}
233
234// The sessions as their list shows them: those of this folder first, each
235// group the latest changed first.
236export const sessionsListed = (index: readonly LedgerSessionNote[], cwd: string): LedgerSessionNote[] => [
237  ...index.filter(one => one.cwd === cwd),
238  ...index.filter(one => one.cwd !== cwd),
239]
240
241// The session a run with no session recorded is filed under: one a folder.
242export const unnamedSession = (cwd: string): string => `before:${cwd}`
243
244// A book kept for a whole folder, as it was before each session kept its own,
245// as one book a session: each run goes to the session that planned it.
246export const splitOld = (old: Book, cwd: string): Map<string, Book> => {
247  const books = new Map<string, Book>()
248
249  for (const run of old.runs) {
250    const id = run.sessionId ?? unnamedSession(cwd)
251    const book = books.get(id) ?? { nextId: old.nextId, current: 0, runs: [], cwd }
252
253    books.set(id, { ...book, runs: [...book.runs, run] })
254  }
255
256  // A session's current run is the folder's where that was its own, else the
257  // one it planned last.
258  for (const [id, book] of books) {
259    books.set(id, {
260      ...book,
261      current: book.runs.some(one => one.id === old.current) ? old.current : (book.runs.at(-1)?.id ?? 0),
262    })
263  }
264
265  return books
266}
267
268// When a book last changed, as far as its runs say.
269export const changedAt = (book: Book): number =>
270  Math.max(0, ...book.runs.map(one => one.doneAt ?? one.startedAt))
271
272// How much of the store the ledgers may take in all, in characters of JSON:
273// under the 4 MiB the engine gives a plugin's store, with room to spare.
274export const STORE_BUDGET = 3_000_000
275
276// A session's book with only the runs not done, to make room: null when it
277// has none, so nothing of it is worth keeping.
278export const trimmed = (book: Book): Book | null => {
279  const open = book.runs.filter(one => one.doneAt === undefined)
280
281  return open.length === 0
282    ? null
283    : { ...book, current: open.some(one => one.id === book.current) ? book.current : 0, runs: open }
284}
285
286// The sessions to make room from when the ledgers are over `budget`, the one
287// changed longest ago first, and never `keep`, the session at work. Enough of
288// them that, were each emptied, the rest would fit.
289export const overBudget = (index: readonly LedgerSessionNote[], keep: string, budget = STORE_BUDGET): string[] => {
290  let total = index.reduce((sum, one) => sum + (one.size ?? 0), 0)
291  const ids: string[] = []
292
293  for (const one of [...index].sort((a, b) => a.at - b.at)) {
294    if (total <= budget) {
295      break
296    }
297
298    if (one.id !== keep) {
299      ids.push(one.id)
300      total -= one.size ?? 0
301    }
302  }
303
304  return ids
305}
306
hooks/kit/layout.ts 24 lines
1// Shared by the lens, parked and ledger mods. The source is the mod-kit folder;
2// each mod carries a copy under hooks/kit, written there by sync.sh. Edit the
3// source and sync, never a copy.
4
5// The cells a pane leaves clear at each side.
6export const PAD = 2
7
8// Text no longer than `most`, an ellipsis standing for what was cut.
9export const cut = (text: string, most: number): string =>
10  text.length > most ? `${text.slice(0, Math.max(0, most - 1))}…` : text
11
12// How long ago `then` was, as one short word: minutes, hours, then days.
13export const ageOf = (then: number, now: number): string => {
14  const minutes = Math.max(0, Math.round((now - then) / 60000))
15
16  if (minutes < 60) {
17    return `${minutes}m`
18  }
19
20  const hours = Math.round(minutes / 60)
21
22  return hours < 48 ? `${hours}h` : `${Math.round(hours / 24)}d`
23}
24
hooks/lanes.ts 235 lines
1// A sequential plan turned into one that can be worked on in parallel, free of
2// the engine: which earlier tasks each task needs, and from that the lanes,
3// tracks of tasks that need nothing of one another and so can run at once.
4
5import type { DocTask } from './doc'
6
7// The earlier tasks each task needs done before it starts, by task number.
8export type Needs = Map<string, string[]>
9
10// What the files alone say: a task needs every earlier task that touches a
11// file it touches, for two tasks on one file cannot be worked on at once.
12export const fileNeeds = (tasks: readonly DocTask[]): Needs =>
13  new Map(
14    tasks.map((task, at) => [
15      task.n,
16      tasks
17        .slice(0, at)
18        .filter(earlier => earlier.files.some(file => task.files.includes(file)))
19        .map(earlier => earlier.n),
20    ]),
21  )
22
23// What a task needs in all: what was said of it (its `**Needs:**` line, or a
24// model's reading of the plan) and what its files say. A task nobody has
25// spoken for needs the task before it, as a plan read top to bottom implies.
26// Only earlier tasks count, so the plan's order always holds.
27export const allNeeds = (tasks: readonly DocTask[], said: Needs): Needs => {
28  const files = fileNeeds(tasks)
29
30  return new Map(
31    tasks.map((task, at) => {
32      const earlier = new Set(tasks.slice(0, at).map(one => one.n))
33      const before = tasks[at - 1]?.n
34      const told = said.get(task.n) ?? (before === undefined ? [] : [before])
35
36      return [task.n, [...new Set([...told, ...(files.get(task.n) ?? [])])].filter(n => earlier.has(n))]
37    }),
38  )
39}
40
41// The folder most of a lane's files are under, as its name: `backend` for
42// `backend/app/x.py`. '' when its tasks name no file.
43const folderOf = (tasks: readonly DocTask[]): string => {
44  const counts = new Map<string, number>()
45
46  for (const file of tasks.flatMap(one => one.files)) {
47    const top = file.replace(/^\.?\//, '').split('/')[0] ?? ''
48
49    // A file at the root names no folder.
50    if (top !== '' && file.includes('/')) {
51      counts.set(top, (counts.get(top) ?? 0) + 1)
52    }
53  }
54
55  return [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? ''
56}
57
58// The lane of each task that is in one, by task number; a task not here is
59// in the line, done by itself before what follows it.
60//
61// A task every other task comes before or after is in the line. The tasks
62// between two such are a fork: those tied by a need, directly or through
63// others, are one lane, worked in the plan's order, and the lanes need nothing
64// of one another. A fork of one lane is no fork: its tasks are in the line.
65export const lanesFrom = (tasks: readonly DocTask[], needs: Needs): Map<string, string> => {
66  const at = new Map(tasks.map((one, index) => [one.n, index]))
67  // Everything each task comes after, through the tasks it needs.
68  const before: Set<number>[] = []
69
70  tasks.forEach((task, index) => {
71    const mine = new Set<number>()
72
73    for (const n of needs.get(task.n) ?? []) {
74      const need = at.get(n)
75
76      if (need !== undefined && need < index) {
77        mine.add(need)
78
79        for (const further of before[need] ?? []) {
80          mine.add(further)
81        }
82      }
83    }
84
85    before.push(mine)
86  })
87
88  const isOrdered = (a: number, b: number) => before[a]?.has(b) === true || before[b]?.has(a) === true
89  const isInLine = tasks.map((_, index) => tasks.every((__, other) => other === index || isOrdered(index, other)))
90  const lanes = new Map<string, string>()
91  const taken = new Set<string>()
92  let from = 0
93
94  while (from < tasks.length) {
95    if (isInLine[from] === true) {
96      from += 1
97      continue
98    }
99
100    let to = from
101
102    while (to < tasks.length && isInLine[to] !== true) {
103      to += 1
104    }
105
106    // The fork's tasks, grouped: each joins the group of the tasks it needs.
107    const group = new Map<number, number>()
108
109    for (let index = from; index < to; index++) {
110      const tied = [...(before[index] ?? [])].filter(need => need >= from).map(need => group.get(need) ?? need)
111      const home = tied.length === 0 ? index : Math.min(...tied)
112
113      group.set(index, home)
114
115      // A task that needs tasks of two groups makes them one.
116      for (const [member, was] of group) {
117        if (tied.includes(was)) {
118          group.set(member, home)
119        }
120      }
121    }
122
123    const homes = [...new Set(group.values())].sort((a, b) => a - b)
124
125    if (homes.length > 1) {
126      homes.forEach(home => {
127        const mine = [...group].filter(([, was]) => was === home).map(([index]) => tasks[index] as DocTask)
128        // Named for its folder. A second lane of one folder, or one with no
129        // folder, is named for its first task; failing that it is numbered.
130        const folder = folderOf(mine)
131        const first = (mine[0]?.title ?? '')
132          .toLowerCase()
133          .replace(/[^a-z0-9\s-]/g, ' ')
134          .split(/\s+/)
135          .filter(Boolean)
136          .slice(0, 2)
137          .join(' ')
138        let name = folder !== '' && !taken.has(folder) ? folder : first
139        let count = 2
140
141        while (name === '' || taken.has(name)) {
142          name = `${first === '' ? 'lane' : first} ${count}`
143          count += 1
144        }
145
146        taken.add(name)
147
148        for (const task of mine) {
149          lanes.set(task.n, name)
150        }
151      })
152    }
153
154    from = to
155  }
156
157  return lanes
158}
159
160// What a model is asked, to learn what each task needs: the plan's tasks with
161// their files and steps, and nothing else of the document.
162export const needsRequest = (tasks: readonly DocTask[]): string =>
163  [
164    'Below are the tasks of an implementation plan, in the order it was written, each with the files it touches and its steps.',
165    'For each task, list the EARLIER tasks whose result it needs before it can start: it uses a type, function, schema, endpoint, component or file that the earlier task creates or changes.',
166    'Two tasks that only belong to the same feature, but use nothing of one another, do not need each other: they can be worked on at the same time.',
167    'A final task that verifies, integrates or documents the whole needs every task it checks.',
168    'When you cannot tell, list the earlier task: a need too many only costs time, a need missed breaks the work.',
169    'Answer with JSON only, no prose, one entry per task: [{"task": "3", "needs": ["1", "2"]}]. Use the task numbers given.',
170    '',
171    ...tasks.flatMap(task => [
172      `Task ${task.n}: ${task.title}`,
173      ...(task.files.length > 0 ? [`  files: ${task.files.slice(0, 12).join(', ')}`] : []),
174      ...task.steps.slice(0, 10).map(step => `  - ${step.text.slice(0, 120)}`),
175    ]),
176  ].join('\n')
177
178// What the model answered, kept for the tasks it names: the needs of each,
179// among the plan's own task numbers. A task it left out is not here.
180export const needsFromAnswer = (answer: string, tasks: readonly DocTask[]): Needs => {
181  const known = new Set(tasks.map(one => one.n))
182  const needs: Needs = new Map()
183  let listed: unknown
184
185  try {
186    listed = JSON.parse(answer.slice(answer.indexOf('['), answer.lastIndexOf(']') + 1))
187  } catch {
188    return needs
189  }
190
191  for (const one of Array.isArray(listed) ? (listed as unknown[]) : []) {
192    const entry = (typeof one === 'object' && one !== null ? one : {}) as Record<string, unknown>
193    const n = String(entry.task ?? '').replace(/^task\s*/i, '')
194
195    if (known.has(n) && Array.isArray(entry.needs)) {
196      needs.set(
197        n,
198        (entry.needs as unknown[]).map(need => String(need).replace(/^task\s*/i, '')).filter(need => known.has(need)),
199      )
200    }
201  }
202
203  return needs
204}
205
206// The plan's shape in a line, for the person who asked: the tasks in the
207// line by number, and each fork's lanes with theirs.
208export const shapeText = (tasks: readonly DocTask[], lanes: ReadonlyMap<string, string>): string => {
209  const parts: string[] = []
210  let fork: Map<string, string[]> | undefined
211
212  const close = () => {
213    if (fork !== undefined) {
214      parts.push(`[${[...fork].map(([name, mine]) => `${name}: ${mine.join(', ')}`).join(' ∥ ')}]`)
215      fork = undefined
216    }
217  }
218
219  for (const task of tasks) {
220    const lane = lanes.get(task.n)
221
222    if (lane === undefined) {
223      close()
224      parts.push(task.n)
225    } else {
226      fork = fork ?? new Map()
227      fork.set(lane, [...(fork.get(lane) ?? []), task.n])
228    }
229  }
230
231  close()
232
233  return parts.join(' → ')
234}
235
hooks/pipe.ts 303 lines
1// A run laid out as a pipeline, free of the engine: its tasks in the plan's
2// order are stages one after another, and tasks in lanes are a fork, each lane
3// a branch of its own that joins the line again where the lanes end.
4
5import type { LedgerRun, LedgerTask, LedgerTaskStatus } from '../types'
6import { isOver } from './run'
7
8export type PipeLane = { name: string; tasks: LedgerTask[] }
9
10export type Stage = { kind: 'one'; task: LedgerTask } | { kind: 'fork'; lanes: PipeLane[] }
11
12// The node drawn for a task, by how it stands. Plain marks one cell wide in
13// any font, so the lines between rows meet.
14export const NODES: Record<LedgerTaskStatus, string> = {
15  todo: '○',
16  running: '◉',
17  'gate-failed': '✗',
18  done: '●',
19  cancelled: '⊘',
20}
21
22// The stages in the plan's order. Tasks in lanes that follow one another are
23// one fork, its lanes in the order the plan first names them.
24export const stagesOf = (run: LedgerRun): Stage[] => {
25  const stages: Stage[] = []
26
27  for (const task of run.tasks) {
28    const last = stages.at(-1)
29
30    if (task.lane === undefined) {
31      stages.push({ kind: 'one', task })
32    } else if (last?.kind === 'fork') {
33      const lane = last.lanes.find(one => one.name === task.lane)
34
35      if (lane === undefined) {
36        last.lanes.push({ name: task.lane, tasks: [task] })
37      } else {
38        lane.tasks.push(task)
39      }
40    } else {
41      stages.push({ kind: 'fork', lanes: [{ name: task.lane, tasks: [task] }] })
42    }
43  }
44
45  return stages
46}
47
48// A row of the pipeline drawn downwards. `rail` is the lines that pass
49// through the row; under a task it is what its details are drawn beside.
50export type PipeRow =
51  | { kind: 'task'; lead: string; trail: string; rail: string; task: LedgerTask }
52  | { kind: 'lane'; lead: string; trail: string; name: string }
53  | { kind: 'unit'; rail: string; name: string; lane?: string }
54  | { kind: 'link'; rail: string }
55
56// The pipeline top to bottom: a node a task, a fork's lanes side by side as
57// rails, each lane's tasks under its name, and a unit's name where it starts.
58//
59// `gap` is the cells between two rails: the wider, the more the fork reads as
60// a graph. A row's lines are as wide as the fork it is in, and one cell wide
61// for a task in the line, so its words stand beside its node.
62//
63// `isOpenEnded` is for a pipeline with something drawn before its first task
64// and after its last (what is beside it, or its start and end): the line then
65// comes in above the first and runs on past the last.
66export const rowsOf = (run: LedgerRun, gap = 1, isOpenEnded = false): PipeRow[] => {
67  const stages = stagesOf(run)
68  // A run whose tasks name no unit is all "main": its name says nothing.
69  const hasUnits = run.tasks.some(one => one.unit !== 'main')
70  const rows: PipeRow[] = []
71  const space = ' '.repeat(gap)
72  const dash = '─'.repeat(gap)
73  let unit: string | undefined
74
75  stages.forEach((stage, at) => {
76    const isLast = !isOpenEnded && at === stages.length - 1
77
78    if (stage.kind === 'one') {
79      if (hasUnits && stage.task.unit !== unit) {
80        rows.push({ kind: 'unit', rail: rows.length === 0 && !isOpenEnded ? ' ' : '│', name: stage.task.unit })
81      }
82
83      unit = stage.task.unit
84      rows.push({ kind: 'task', lead: '', trail: '', rail: isLast ? ' ' : '│', task: stage.task })
85
86      return
87    }
88
89    unit = undefined
90    const count = stage.lanes.length
91    const rail = stage.lanes.map(() => '│').join(space)
92
93    if (count > 1) {
94      rows.push({ kind: 'link', rail: `${at === 0 && !isOpenEnded ? '┌' : '├'}${`${dash}┬`.repeat(count - 2)}${dash}╮` })
95    }
96
97    stage.lanes.forEach((lane, index) => {
98      const lead = `│${space}`.repeat(index)
99      const trail = `${space}│`.repeat(count - 1 - index)
100      let laneUnit: string | undefined
101
102      rows.push({ kind: 'lane', lead, trail, name: lane.name })
103
104      for (const task of lane.tasks) {
105        if (hasUnits && task.unit !== laneUnit) {
106          rows.push({ kind: 'unit', rail, name: task.unit, lane: lane.name })
107        }
108
109        laneUnit = task.unit
110        rows.push({ kind: 'task', lead, trail, rail, task })
111      }
112    })
113
114    if (count > 1) {
115      rows.push({ kind: 'link', rail: `${isLast ? '└' : '├'}${`${dash}┴`.repeat(count - 2)}${dash}╯` })
116    }
117  })
118
119  return rows
120}
121
122// How many cells the rails of a run's widest fork take, `gap` cells apart.
123export const railsWide = (run: LedgerRun, gap = 1): number =>
124  Math.max(1, ...stagesOf(run).map(one => (one.kind === 'fork' ? (one.lanes.length - 1) * (gap + 1) + 1 : 1)))
125
126// The widest gap between rails, up to `GAP_MOST`, that leaves the words
127// beside them at least two thirds of `columns`: a wide pane draws the fork
128// wide, and a narrow one keeps the room for the titles.
129export const gapFor = (run: LedgerRun, columns: number): number => {
130  let gap = GAP_MOST
131
132  while (gap > 1 && railsWide(run, gap) > columns / 3) {
133    gap -= 1
134  }
135
136  return gap
137}
138
139export const GAP_MOST = 5
140
141// A text broken into lines no longer than `width`, at its spaces; a word
142// longer than a line is cut. One empty line for an empty text.
143export const wrapped = (text: string, width: number): string[] => {
144  const most = Math.max(4, width)
145  const lines: string[] = []
146  let line = ''
147
148  for (const word of text.split(/\s+/).filter(Boolean)) {
149    let rest = word
150
151    if (line !== '' && line.length + 1 + rest.length > most) {
152      lines.push(line)
153      line = ''
154    }
155
156    while (rest.length > most) {
157      lines.push(rest.slice(0, most))
158      rest = rest.slice(most)
159    }
160
161    line = line === '' ? rest : `${line} ${rest}`
162  }
163
164  return line === '' && lines.length > 0 ? lines : [...lines, line]
165}
166
167// A piece of the pipeline drawn across: a line, or the node of a task.
168export type PipeCell = { text: string; task?: LedgerTask }
169
170// The pipeline left to right, as a CI run is drawn: a node a task, a line
171// from each to the next, a fork's lanes one under another between the two
172// points where the line splits and joins. The lines between nodes are as long
173// as `columns` lets them be, up to `LINK_MOST`, so the pipeline takes the
174// width it is given. Undefined when it is wider than `columns` with the
175// shortest lines, or is one node alone.
176//
177// `hasTail` keeps the line running past the last node, for what is drawn
178// after it (what comes next, or the pipeline's end): a fork that ends the
179// run then joins the line again, as one in its middle does.
180export const stripOf = (run: LedgerRun, columns: number, hasTail = false): PipeCell[][] | undefined => {
181  const stages = stagesOf(run)
182  const shapes = stages.map(stage => {
183    const lanes = stage.kind === 'fork' ? stage.lanes : [{ name: '', tasks: [stage.task] }]
184
185    return { lanes, isSplit: lanes.length > 1, most: Math.max(...lanes.map(one => one.tasks.length)) }
186  })
187  // Every node, split and join is one place on the line, a link after each
188  // but the last: `places` of them are `places * (1 + link) - link` wide.
189  const places = shapes.reduce((sum, one) => sum + one.most + (one.isSplit ? 2 : 0), 0)
190  // With a tail there is a link after the last place too.
191  const link = Math.min(LINK_MOST, places > 1 ? Math.floor((columns - places) / (hasTail ? places : places - 1)) : 0)
192
193  if (link < 1 || run.tasks.length < 2) {
194    return undefined
195  }
196
197  const height = Math.max(1, ...shapes.map(one => one.lanes.length))
198  const lines: PipeCell[][] = Array.from({ length: height }, () => [])
199  const add = (row: number, text: string, task?: LedgerTask) =>
200    lines[row]?.push({ text, ...(task !== undefined ? { task } : {}) })
201  const line = '─'.repeat(link)
202  const gap = ' '.repeat(link)
203
204  shapes.forEach(({ lanes, isSplit, most }, at) => {
205    const isLast = !hasTail && at === shapes.length - 1
206
207    for (let row = 0; row < height; row++) {
208      const lane = lanes[row]
209
210      if (lane === undefined) {
211        add(row, ' '.repeat((most + (isSplit ? 2 : 0)) * (1 + link)))
212        continue
213      }
214
215      const isEnd = row === lanes.length - 1
216
217      if (isSplit) {
218        add(row, `${row === 0 ? '┬' : isEnd ? '╰' : '├'}${line}`)
219      }
220
221      for (const task of lane.tasks) {
222        add(row, '', task)
223        add(row, line)
224      }
225
226      if (lane.tasks.length < most) {
227        add(row, `─${line}`.repeat(most - lane.tasks.length))
228      }
229
230      if (isSplit) {
231        add(row, row === 0 ? (isLast ? `╮${gap}` : `┬${line}`) : `${isEnd ? '╯' : '┤'}${gap}`)
232      }
233    }
234  })
235
236  // The line stops at the last node: nothing follows it.
237  const first = lines[0]
238  const tail = first?.at(-1)
239
240  if (!hasTail && first !== undefined && tail !== undefined && tail.task === undefined && /^─+$/.test(tail.text)) {
241    first.pop()
242  }
243
244  return lines
245}
246
247// The longest a line between two nodes is drawn.
248export const LINK_MOST = 8
249
250// A strip's line as plain text, each node the mark of its task's state.
251export const stripText = (line: readonly PipeCell[]): string =>
252  line.map(one => (one.task === undefined ? one.text : NODES[one.task.status])).join('')
253
254// The tasks that should be over before a task starts and are not: the ones
255// its plan says it needs, every task of the stages before its own, and the
256// tasks before it in its lane. By id, in the plan's order.
257export const unmetOf = (run: LedgerRun, id: string): string[] => {
258  const before = new Set<string>(run.tasks.find(one => one.id === id)?.needs ?? [])
259
260  for (const stage of stagesOf(run)) {
261    const mine =
262      stage.kind === 'one'
263        ? stage.task.id === id
264          ? []
265          : undefined
266        : stage.lanes.find(lane => lane.tasks.some(one => one.id === id))?.tasks
267
268    if (mine !== undefined) {
269      for (const one of mine.slice(0, Math.max(0, mine.findIndex(task => task.id === id)))) {
270        before.add(one.id)
271      }
272
273      break
274    }
275
276    for (const one of stage.kind === 'one' ? [stage.task] : stage.lanes.flatMap(lane => lane.tasks)) {
277      before.add(one.id)
278    }
279  }
280
281  return run.tasks.filter(one => before.has(one.id) && !isOver(one)).map(one => one.id)
282}
283
284// The other lanes of a task's fork that nothing has started on: every task
285// still to do, and no subagent ever spawned for one. They could be worked on
286// at the same time as the task's own lane.
287export const idleLanes = (run: LedgerRun, id: string): string[] => {
288  const fork = stagesOf(run).find(
289    stage => stage.kind === 'fork' && stage.lanes.some(lane => lane.tasks.some(one => one.id === id)),
290  )
291
292  return fork === undefined || fork.kind !== 'fork'
293    ? []
294    : fork.lanes
295        .filter(
296          lane =>
297            !lane.tasks.some(one => one.id === id) &&
298            lane.tasks.every(one => one.status === 'todo') &&
299            !run.spawns.some(spawn => lane.tasks.some(one => one.id === spawn.task)),
300        )
301        .map(lane => lane.name)
302}
303
hooks/strip.tsx 87 lines
1// The pipeline drawn across, where it can be pointed at: a surface module, so
2// a click on a node (or on the id beside it) picks that task, as a job is
3// picked in a CI run's graph. It draws what it is handed and reports the
4// click; what a pick means is the hooks module's to say.
5
6import type { ClientModule } from 'claude-code'
7
8// A piece of one line of the pipeline: its text and how it is drawn, and for
9// a node or its id, the task it stands for.
10export type StripPiece = {
11  text: string
12  color?: string
13  isDim?: boolean
14  isBold?: boolean
15  isInverse?: boolean
16  id?: string
17  // For what is drawn after the last node: the run that comes next.
18  run?: number
19}
20
21export type StripProps = { lines: StripPiece[][] }
22
23// What a click posts to the hooks module: the task to show, or the run to open.
24export type StripPick = { pick: string } | { open: number }
25
26// The task under the pointer: '' for a line, or nothing.
27type State = { over: string }
28
29const Strip: ClientModule<StripProps, State> = (props, surface) => {
30  const { Box, Text } = surface.elements
31  const over = surface.state?.over ?? ''
32  // What a piece is pointed at as: its task, the run it leads to, or nothing.
33  const nameOf = (piece: StripPiece): string => piece.id ?? (piece.run === undefined ? '' : `run ${piece.run}`)
34  // The piece at a cell of the region.
35  const pieceAt = (x: number, y: number): StripPiece | undefined => {
36    let column = 0
37
38    for (const piece of props.lines[y] ?? []) {
39      if (x >= column && x < column + piece.text.length) {
40        return piece
41      }
42
43      column += piece.text.length
44    }
45
46    return undefined
47  }
48
49  // Set on every call, so it reads the lines as they now are.
50  surface.onPointer(event => {
51    const piece = event.type === 'leave' ? undefined : pieceAt(event.x, event.y)
52    const name = piece === undefined ? '' : nameOf(piece)
53
54    if (event.type === 'down' && piece?.id !== undefined) {
55      surface.post({ pick: piece.id })
56    } else if (event.type === 'down' && piece?.run !== undefined) {
57      surface.post({ open: piece.run })
58    }
59
60    if (name !== (surface.state?.over ?? '')) {
61      surface.setState({ over: name })
62    }
63  })
64
65  return (
66    <Box flexDirection="column">
67      {props.lines.map(line => (
68        <Text wrap="truncate-end">
69          {line.map(piece => (
70            <Text
71              {...(piece.color !== undefined ? { color: piece.color } : {})}
72              dimColor={piece.isDim === true && nameOf(piece) !== over}
73              bold={piece.isBold === true || (over !== '' && nameOf(piece) === over)}
74              inverse={piece.isInverse === true}
75              underline={over !== '' && nameOf(piece) === over}
76            >
77              {piece.text}
78            </Text>
79          ))}
80        </Text>
81      ))}
82    </Box>
83  )
84}
85
86export default Strip
87
hooks/run.ts 528 lines
1// A run's logic, free of the engine: every change takes a run and answers the
2// next one, or a string saying why it was refused.
3
4import type {
5  LedgerFinding,
6  LedgerRun,
7  LedgerSeverity,
8  LedgerSpawn,
9  LedgerTask,
10  LedgerTaskStatus,
11  LedgerUnitNote,
12} from '../types'
13import { ICON } from './kit/icons'
14import { cut } from './kit/layout'
15
16export type NewTask = {
17  id: string
18  lane?: string
19  unit?: string
20  title: string
21  about?: string
22  tier?: string
23  check?: string
24  // The tasks it needs done first, by id.
25  needs?: string[]
26}
27
28export type NewFinding = {
29  path: string
30  line?: number
31  severity: LedgerSeverity
32  summary: string
33  task?: string
34  agentId?: string
35}
36
37export const SEVERITIES: readonly LedgerSeverity[] = ['error', 'warning', 'note']
38export const STATUSES: readonly LedgerTaskStatus[] = ['todo', 'running', 'gate-failed', 'done', 'cancelled']
39
40// Whether nothing is left to do on a task: it is done, or will not be.
41export const isOver = (task: LedgerTask): boolean => task.status === 'done' || task.status === 'cancelled'
42
43// How long a task may stand as running with nothing touching its run and no
44// subagent on it before it counts as stalled.
45export const STALE_MS = 60 * 60 * 1000
46
47// Whether a task marked running has stalled: no subagent runs for it, and
48// nothing of its run has changed for `STALE_MS`. An agent that forgot to
49// settle it, or a session that ended, leaves it so.
50export const isStalled = (run: LedgerRun, task: LedgerTask, now: number): boolean =>
51  task.status === 'running' &&
52  !run.spawns.some(one => one.task === task.id && one.endedAt === undefined) &&
53  now - (run.changedAt ?? run.startedAt) > STALE_MS
54
55export const isRun = (value: unknown): value is LedgerRun =>
56  typeof value === 'object' &&
57  value !== null &&
58  typeof (value as LedgerRun).goal === 'string' &&
59  Array.isArray((value as LedgerRun).tasks) &&
60  Array.isArray((value as LedgerRun).spawns) &&
61  Array.isArray((value as LedgerRun).findings)
62
63// A new run from the settled plan. A task with no unit is in the unit "main".
64export const plan = (
65  goal: string,
66  tasks: readonly NewTask[],
67  now: number,
68  sessionId?: string,
69  units: readonly LedgerUnitNote[] = [],
70): LedgerRun | string => {
71  if (tasks.length === 0) {
72    return 'A plan needs at least one task.'
73  }
74
75  const ids = tasks.map(one => one.id.trim())
76  const twice = ids.find((id, at) => id === '' || ids.indexOf(id) !== at)
77
78  if (twice !== undefined) {
79    return twice === '' ? 'Every task needs an id.' : `Task id ${twice} is used twice.`
80  }
81
82  // What each unit is for, for the units the plan has tasks in.
83  const planned = new Set(tasks.map(one => one.unit?.trim() || 'main'))
84  const described = units
85    .map(one => ({ name: one.name.trim(), about: one.about.trim() }))
86    .filter(one => planned.has(one.name) && one.about !== '')
87
88  return {
89    id: 0,
90    goal: goal.trim(),
91    startedAt: now,
92    ...(sessionId !== undefined ? { sessionId } : {}),
93    ...(described.length > 0 ? { units: described } : {}),
94    tasks: tasks.map(one => ({
95      id: one.id.trim(),
96      ...(one.lane?.trim() ? { lane: one.lane.trim() } : {}),
97      unit: one.unit?.trim() || 'main',
98      title: one.title.trim(),
99      ...(one.tier ? { tier: one.tier.trim() } : {}),
100      ...(one.about?.trim() ? { about: one.about.trim() } : {}),
101      ...(one.check ? { check: one.check.trim() } : {}),
102      // Only tasks of this plan count, and never the task itself.
103      ...((one.needs ?? []).some(need => ids.includes(need.trim()) && need.trim() !== one.id.trim())
104        ? { needs: (one.needs ?? []).map(need => need.trim()).filter(need => ids.includes(need) && need !== one.id.trim()) }
105        : {}),
106      status: 'todo' as const,
107    })),
108    spawns: [],
109    findings: [],
110    nextFinding: 1,
111  }
112}
113
114export const setTask = (
115  run: LedgerRun,
116  id: string,
117  status: LedgerTaskStatus,
118  note?: string,
119  outcome?: string,
120): LedgerRun | string =>
121  run.tasks.some(one => one.id === id)
122    ? {
123        ...run,
124        tasks: run.tasks.map(one => {
125          if (one.id !== id) {
126            return one
127          }
128
129          const { note: _n, ...rest } = one
130
131          return {
132            ...rest,
133            status,
134            ...(note?.trim() ? { note: note.trim() } : {}),
135            // What was done stands until it is said again.
136            ...(outcome?.trim() ? { outcome: outcome.trim() } : {}),
137          }
138        }),
139      }
140    : `No task ${id}. The tasks are ${run.tasks.map(one => one.id).join(', ')}.`
141
142const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
143
144// The task a subagent was spawned for: the one its description names in
145// brackets ("[T3] add the retry"), else the one named there as a word of its
146// own, else the one its prompt names in brackets.
147//
148// Where several are named, the one named first in the text wins, and of two
149// starting at one place the longer id (T10 over T1, 1.2 over 1).
150export const taskOf = (run: LedgerRun, description: string, prompt = ''): string | undefined => {
151  const named = (text: string, isBare: boolean) =>
152    run.tasks
153      .flatMap(one => {
154        const hit = new RegExp(
155          isBare ? `(?<![A-Za-z0-9_])${escaped(one.id)}(?![A-Za-z0-9_])` : `\\[${escaped(one.id)}\\]`,
156        ).exec(text)
157
158        return hit === null ? [] : [{ id: one.id, at: hit.index }]
159      })
160      .sort((a, b) => a.at - b.at || b.id.length - a.id.length)[0]?.id
161
162  // A run read from a plan document numbers its tasks T1, T2, ...: there a
163  // description that says "Task 3", as the document does, names T3.
164  const spoken =
165    run.doc === undefined
166      ? undefined
167      : run.tasks.find(one =>
168          new RegExp(`(?<![A-Za-z0-9_])Task\\s+${escaped(one.id.replace(/^T/, ''))}(?![A-Za-z0-9_.-])`, 'i').test(
169            description,
170          ),
171        )?.id
172
173  return named(description, false) ?? named(description, true) ?? spoken ?? named(prompt, false)
174}
175
176// Records a subagent as started. Its task, when still to do, is now running.
177// One recorded before keeps the tokens it had used.
178export const spawned = (run: LedgerRun, spawn: LedgerSpawn): LedgerRun => {
179  const before = run.spawns.find(one => one.agentId === spawn.agentId)?.tokens
180
181  return {
182    ...run,
183    tasks: run.tasks.map(one =>
184      one.id === spawn.task && one.status === 'todo' ? { ...one, status: 'running' as const } : one,
185    ),
186    spawns: [
187      ...run.spawns.filter(one => one.agentId !== spawn.agentId),
188      { ...spawn, ...(before !== undefined ? { tokens: before + (spawn.tokens ?? 0) } : {}) },
189    ],
190  }
191}
192
193// A subagent that had ended is at work again (it was sent a message): it
194// counts as running until its next turn ends.
195export const resumed = (run: LedgerRun, agentId: string): LedgerRun => ({
196  ...run,
197  spawns: run.spawns.map(one => {
198    if (one.agentId !== agentId) {
199      return one
200    }
201
202    const { endedAt: _e, reason: _r, ...rest } = one
203
204    return rest
205  }),
206})
207
208// A run another session left: the subagents it still shows running ended with
209// that session.
210export const orphaned = (run: LedgerRun, now: number): LedgerRun => ({
211  ...run,
212  spawns: run.spawns.map(one =>
213    one.endedAt === undefined ? { ...one, endedAt: now, reason: 'session ended' } : one,
214  ),
215})
216
217// Records a subagent's turn as over, with what it said as it ended; a run
218// that never saw it start is unchanged.
219export const ended = (
220  run: LedgerRun,
221  agentId: string,
222  reason: string,
223  tokens: number | undefined,
224  now: number,
225  report?: string,
226): LedgerRun => ({
227  ...run,
228  spawns: run.spawns.map(one =>
229    one.agentId === agentId
230      ? {
231          ...one,
232          endedAt: now,
233          reason,
234          ...(tokens !== undefined ? { tokens: (one.tokens ?? 0) + tokens } : {}),
235          ...(report !== undefined && report !== '' ? { report } : {}),
236        }
237      : one,
238  ),
239})
240
241export const found = (run: LedgerRun, finding: NewFinding, now: number): LedgerRun => ({
242  ...run,
243  nextFinding: run.nextFinding + 1,
244  findings: [
245    ...run.findings,
246    {
247      id: run.nextFinding,
248      path: finding.path.trim(),
249      ...(finding.line !== undefined ? { line: finding.line } : {}),
250      severity: finding.severity,
251      summary: finding.summary.trim(),
252      ...(finding.task !== undefined ? { task: finding.task } : {}),
253      ...(finding.agentId !== undefined ? { agentId: finding.agentId } : {}),
254      at: now,
255      status: 'open',
256    },
257  ],
258})
259
260export const fixed = (run: LedgerRun, ids: readonly number[]): LedgerRun | string => {
261  const missing = ids.find(id => !run.findings.some(one => one.id === id))
262
263  return missing !== undefined
264    ? `No finding #${missing}.`
265    : {
266        ...run,
267        findings: run.findings.map(one => (ids.includes(one.id) ? { ...one, status: 'fixed' as const } : one)),
268      }
269}
270
271export type LedgerUnit = { name: string; lane?: string; about?: string; tasks: LedgerTask[] }
272
273// The units in the order the plan first names them. Two lanes may each have a
274// unit of one name: they are two units.
275export const unitsOf = (run: LedgerRun): LedgerUnit[] =>
276  [...new Set(run.tasks.map(one => `${one.lane ?? ''}\n${one.unit}`))].map(key => {
277    const [lane = '', name = ''] = key.split('\n')
278    const about = run.units?.find(one => one.name === name)?.about
279
280    return {
281      name,
282      ...(lane !== '' ? { lane } : {}),
283      ...(about !== undefined ? { about } : {}),
284      tasks: run.tasks.filter(one => (one.lane ?? '') === lane && one.unit === name),
285    }
286  })
287
288export type LedgerLane = {
289  // '' for the tasks of a run that names no lane for them.
290  name: string
291  units: LedgerUnit[]
292  tasks: number
293  done: number
294  failed: number
295  // The subagents running on this lane's tasks.
296  agents: number
297}
298
299// Whether the plan split the run into lanes: parallel tracks of one feature.
300export const hasLanes = (run: LedgerRun): boolean => run.tasks.some(one => one.lane !== undefined)
301
302// The run's lanes in the order the plan first names them. A run with no lanes
303// is one lane with no name.
304export const lanesOf = (run: LedgerRun): LedgerLane[] => {
305  const units = unitsOf(run)
306
307  return [...new Set(units.map(one => one.lane ?? ''))].map(name => {
308    const mine = units.filter(one => (one.lane ?? '') === name)
309    const tasks = mine.flatMap(one => one.tasks)
310    const ids = new Set(tasks.map(one => one.id))
311
312    return {
313      name,
314      units: mine,
315      tasks: tasks.length,
316      done: tasks.filter(one => one.status === 'done').length,
317      failed: tasks.filter(one => one.status === 'gate-failed').length,
318      agents: run.spawns.filter(
319        one => one.endedAt === undefined && one.task !== undefined && ids.has(one.task),
320      ).length,
321    }
322  })
323}
324
325export type LedgerCounts = {
326  units: number
327  // The unit work is on, counted from 1: the first with a task not done; the
328  // last unit once every task is done.
329  unitAt: number
330  unitName: string
331  tasks: number
332  done: number
333  // The tasks that will not be done.
334  cancelled: number
335  failed: number
336  running: number
337  agents: number
338  openFindings: number
339  errors: number
340  tokens: number
341}
342
343export const countsOf = (run: LedgerRun): LedgerCounts => {
344  const units = unitsOf(run)
345  const at = units.findIndex(unit => unit.tasks.some(one => !isOver(one)))
346  const here = at === -1 ? units.length - 1 : at
347  const open = run.findings.filter(one => one.status === 'open')
348
349  return {
350    units: units.length,
351    unitAt: here + 1,
352    unitName: units[here]?.name ?? '',
353    tasks: run.tasks.length,
354    done: run.tasks.filter(one => one.status === 'done').length,
355    cancelled: run.tasks.filter(one => one.status === 'cancelled').length,
356    failed: run.tasks.filter(one => one.status === 'gate-failed').length,
357    running: run.tasks.filter(one => one.status === 'running').length,
358    agents: run.spawns.filter(one => one.endedAt === undefined).length,
359    openFindings: open.length,
360    errors: open.filter(one => one.severity === 'error').length,
361    tokens: run.spawns.reduce((sum, one) => sum + (one.tokens ?? 0), 0),
362  }
363}
364
365// Whether no task is left: each is done, or cancelled.
366export const isDone = (run: LedgerRun): boolean => run.tasks.every(isOver)
367
368const few = (count: number, one: string, many = `${one}s`) => `${count} ${count === 1 ? one : many}`
369
370export const tokensText = (tokens: number): string =>
371  tokens >= 999_500
372    ? `${(tokens / 1_000_000).toFixed(1)}M`
373    : tokens >= 1000
374      ? `${Math.round(tokens / 1000)}k`
375      : String(tokens)
376
377// The task work is on: one a subagent is running for, else one marked running,
378// else a failed gate waiting to be dealt with, else the next still to do.
379export const focusOf = (run: LedgerRun): LedgerTask | undefined => {
380  const live = new Set(
381    run.spawns.flatMap(one => (one.endedAt === undefined && one.task !== undefined ? [one.task] : [])),
382  )
383
384  return (
385    run.tasks.find(one => !isOver(one) && live.has(one.id)) ??
386    run.tasks.find(one => one.status === 'running') ??
387    run.tasks.find(one => one.status === 'gate-failed') ??
388    run.tasks.find(one => one.status === 'todo')
389  )
390}
391
392// The most of a task's title the status line shows.
393export const STATUS_MOST = 36
394
395// The status line's entry: the task work is on, and how many more are not
396// done (`others` counts those of other runs under way). Undefined once the run
397// has nothing left to say: every task done, no agent running and no finding
398// open.
399export const statusText = (run: LedgerRun, others = 0): string | undefined => {
400  const counts = countsOf(run)
401
402  if (isDone(run) && counts.agents === 0 && counts.openFindings === 0) {
403    return undefined
404  }
405
406  const now = focusOf(run)
407
408  // Every task is done: what keeps the run open is all there is to say.
409  if (now === undefined) {
410    return [
411      `${ICON.tasks} all ${few(counts.done, 'task')} done${counts.cancelled > 0 ? `, ${counts.cancelled} cancelled` : ''}`,
412      counts.openFindings > 0 ? `${few(counts.openFindings, 'finding')} open` : '',
413      counts.agents > 0 ? `${few(counts.agents, 'agent')} running` : '',
414      others > 0 ? `${others} more` : '',
415    ]
416      .filter(Boolean)
417      .join(' · ')
418  }
419
420  const more = counts.tasks - counts.done - counts.cancelled - 1 + others
421
422  return `${ICON.tasks} ${now.status === 'gate-failed' ? `${ICON.failed} ` : ''}${now.id} ${cut(now.title, STATUS_MOST)}${more > 0 ? ` · ${more} more` : ''}`
423}
424
425// The end of a text no longer than `most`, an ellipsis standing for what was
426// cut from its start: a path keeps its file's name.
427export const tail = (text: string, most: number): string =>
428  text.length > most ? `…${text.slice(text.length - Math.max(0, most - 1))}` : text
429
430// What a write is answered with when it leaves something to settle: the
431// findings left open once every task is done, else the open findings of the
432// tasks just marked done. '' with nothing to say.
433export const leftOpen = (run: LedgerRun, doneIds: readonly string[]): string => {
434  const open = run.findings.filter(one => one.status === 'open')
435  const mine = open.filter(one => one.task !== undefined && doneIds.includes(one.task))
436  const named = (list: readonly LedgerFinding[]) => list.map(one => `#${one.id}`).join(', ')
437
438  return isDone(run) && open.length > 0
439    ? `Every task is done, but ${few(open.length, 'finding')} still open (${named(open)}): fix and close with the fixed tool, or tell the user why it stays open.`
440    : mine.length > 0
441      ? `${few(mine.length, 'finding')} still open on the tasks marked done (${named(mine)}): close with the fixed tool once dealt with.`
442      : ''
443}
444
445const MARKS: Record<LedgerTaskStatus, string> = {
446  todo: ICON.todo,
447  running: ICON.running,
448  'gate-failed': ICON.failed,
449  done: ICON.done,
450  cancelled: '⊘',
451}
452
453export const placeOf = (finding: LedgerFinding): string =>
454  finding.line === undefined ? finding.path : `${finding.path}:${finding.line}`
455
456// A finding as the prompt takes it: where it is, then what is wrong.
457export const findingText = (finding: LedgerFinding): string =>
458  `Finding #${finding.id} (${finding.severity}) ${placeOf(finding)}: ${finding.summary}`
459
460export const spanText = (ms: number): string => {
461  const seconds = Math.max(0, Math.round(ms / 1000))
462
463  return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`
464}
465
466// What the pane shows beside a subagent: its model, how long it ran (or has
467// been running), and the tokens it used.
468export const spawnMeta = (spawn: LedgerSpawn, now: number): string =>
469  [
470    spawn.model,
471    spanText((spawn.endedAt ?? now) - spawn.startedAt),
472    spawn.tokens !== undefined ? tokensText(spawn.tokens) : '',
473  ]
474    .filter(Boolean)
475    .join(' · ')
476
477// The run as text: what /ledger print shows and what the model reads back.
478// A task's steps done of all, where its run is read from a plan document: ''
479// for a task with no steps.
480export const stepsText = (task: LedgerTask): string =>
481  task.steps === undefined || task.steps.length === 0
482    ? ''
483    : `${task.steps.filter(one => one.isDone).length}/${task.steps.length}`
484
485const laneDone = (run: LedgerRun, name: string): string => {
486  const lane = lanesOf(run).find(one => one.name === name)
487
488  return `${lane?.done ?? 0}/${lane?.tasks ?? 0} done`
489}
490
491export const report = (run: LedgerRun, isPlain = false): string => {
492  const counts = countsOf(run)
493  const open = run.findings.filter(one => one.status === 'open')
494  const mark = (status: LedgerTaskStatus) => (isPlain ? `[${status}]` : MARKS[status])
495
496  return [
497    `Ledger: ${run.goal === '' ? '(no goal given)' : run.goal}`,
498    ...(run.doc !== undefined ? [`Plan: ${run.doc.path}`] : []),
499    ...unitsOf(run).flatMap((unit, at, units) => [
500      // A lane's heading comes before its first unit.
501      ...(unit.lane !== undefined && units[at - 1]?.lane !== unit.lane
502        ? [`Lane ${unit.lane} (${laneDone(run, unit.lane)})`]
503        : []),
504      `${unit.name} (${unit.tasks.filter(one => one.status === 'done').length}/${unit.tasks.length} done)`,
505      ...(unit.about !== undefined ? [`  ${unit.about}`] : []),
506      ...unit.tasks.flatMap(one => [
507        `  ${mark(one.status)} ${one.id}${one.tier ? ` (${one.tier})` : ''} ${one.title}${stepsText(one) === '' ? '' : ` [${stepsText(one)}]`}${one.note ? `: ${cut(one.note, 160)}` : ''}`,
508        // Once it is done, what was done says more than what it was for.
509        ...(one.outcome !== undefined
510          ? [`      Outcome: ${cut(one.outcome, 300)}`]
511          : one.about !== undefined
512            ? [`      What it does: ${cut(one.about, 300)}`]
513            : []),
514      ]),
515    ]),
516    run.spawns.length > 0
517      ? `Agents: ${counts.agents} running, ${run.spawns.length - counts.agents} finished, ${tokensText(counts.tokens)} tokens`
518      : '',
519    open.length > 0 ? `Findings: ${open.length} open, ${run.findings.length - open.length} fixed` : '',
520    ...open.map(
521      one =>
522        `  #${one.id} ${one.severity} ${placeOf(one)} ${cut(one.summary, 200)}${one.task ? ` (${one.task})` : ''}`,
523    ),
524  ]
525    .filter(Boolean)
526    .join('\n')
527}
528
types/index.d.ts 153 lines
1// The ledger's contract. Another mod reads a run with
2// `$.state.get({ plugin: 'ledger', key: 'run' })`; only the ledger writes it.
3
4// `cancelled` is a task that will not be done: it holds a run open no more
5// than a done one does.
6export type LedgerTaskStatus = 'todo' | 'running' | 'gate-failed' | 'done' | 'cancelled'
7
8export type LedgerTask = {
9  id: string
10  // The lane the task is in, where the plan has parallel lanes: tracks of one
11  // feature that can be worked on at once.
12  lane?: string
13  // The unit of work the task belongs to; tasks of one unit are reviewed together.
14  unit: string
15  title: string
16  // The model the task is meant for: haiku, sonnet or opus.
17  tier?: string
18  // What the task is for, in a line: what it changes for the user, or which
19  // part of the code it touches. Written when the run is planned.
20  about?: string
21  // How the task is known to be done: what its gate checks.
22  check?: string
23  status: LedgerTaskStatus
24  // The last gate's verdict, or how the task ended.
25  note?: string
26  // What was done, once it is: what changed and where. The agent's own
27  // account, not a checked one.
28  outcome?: string
29  // The checkbox steps of a task read from a plan document, in its order.
30  steps?: LedgerStep[]
31  // The tasks it needs done before it starts, by id, where the plan says.
32  needs?: string[]
33}
34
35export type LedgerStep = { text: string; isDone: boolean }
36
37// A unit of the plan, where the plan describes it: what its tasks add up to.
38export type LedgerUnitNote = { name: string; about: string }
39
40export type LedgerSpawn = {
41  agentId: string
42  // The task the subagent was spawned for, when its description names one.
43  task?: string
44  description: string
45  // The agent type, and the model it ran on.
46  type: string
47  model: string
48  startedAt: number
49  // Set once its turn completed: when, why it ended, and the tokens it used.
50  endedAt?: number
51  reason?: string
52  tokens?: number
53  // What it said as its turn ended, cut short: its report, as close as the
54  // ledger has to a log of the work.
55  report?: string
56}
57
58export type LedgerSeverity = 'error' | 'warning' | 'note'
59
60export type LedgerFinding = {
61  id: number
62  path: string
63  line?: number
64  severity: LedgerSeverity
65  summary: string
66  task?: string
67  // The subagent that reported it; absent when the main agent did.
68  agentId?: string
69  at: number
70  status: 'open' | 'fixed'
71}
72
73// A session's ledger in a line, for the list of sessions: the session, the
74// folder it ran in, when its ledger last changed, the goal of its current
75// run, and how many of its runs are not done, of how many.
76export type LedgerSessionNote = {
77  id: string
78  cwd: string
79  at: number
80  goal: string
81  open: number
82  runs: number
83  // Whether work was under way when it last changed: a subagent running, or a
84  // task marked running. A session that ended so keeps the mark until resumed.
85  busy?: true
86  // How much of the store its ledger takes, in characters of JSON.
87  size?: number
88}
89
90export type LedgerRun = {
91  // Its number among the session's runs; 0 until the ledger has kept it.
92  id: number
93  goal: string
94  startedAt: number
95  // The session that planned the run; another session finds its agents ended.
96  sessionId?: string
97  // When the run was done: by itself once every task is done with no agent
98  // running and no finding open, or when the user closed it (`isClosed`).
99  doneAt?: number
100  isClosed?: true
101  // When the ledger last changed anything of the run: a task marked running
102  // that nothing has touched for long has stalled.
103  changedAt?: number
104  // The plan document the run is read from, where it is: the document is then
105  // the word on its tasks and steps. `isLaidOutByModel` says a small model
106  // grouped its lines, the document not being laid out as superpowers plans are.
107  doc?: { path: string; isLaidOutByModel?: true }
108  tasks: LedgerTask[]
109  // What each unit is for, for the units the plan described.
110  units?: LedgerUnitNote[]
111  spawns: LedgerSpawn[]
112  findings: LedgerFinding[]
113  nextFinding: number
114}
115
116declare module 'claude-code' {
117  interface PluginState {
118    ledger: {
119      run: LedgerRun | null
120      // Every run kept for the session, the newest last; `run` is the current
121      // one, which the tools record against.
122      runs: LedgerRun[]
123      isHidden: boolean
124      // The session `run` and `runs` are read from: '' until the ledger loads.
125      home: string
126      // Another session's ledger the pane is showing, read only; null while
127      // it shows this session's. And the sessions that have one, the latest
128      // changed first, as last listed.
129      peek: { id: string; cwd: string; runs: LedgerRun[] } | null
130      others: LedgerSessionNote[]
131      // The pane: the run it shows in full (0 for the list of runs, -1 for
132      // the list of sessions), the list's row the
133      // focus is on, whether done runs are listed, whether a run shows its
134      // details, the run a clear is waiting to be confirmed for, and the frame
135      // of the mark that turns while a subagent runs.
136      shown: number
137      cursor: number
138      isAll: boolean
139      isDetailed: boolean
140      confirming: number
141      spin: number
142      // The finding the focus is on in a run's view, and the place last asked
143      // to be shown, which the lens mod opens where it is loaded: a path from
144      // the session's folder, a line (0 for the file), and a count of the asks.
145      pointed: number
146      // The task a run's overview shows in full, by id: '' for the one work
147      // is on.
148      picked: string
149      jump: { path: string; line: number; n: number } | null
150    }
151  }
152}
153