SLOPSHOPPER

Accountable Review

Turns a pull request into a published review agenda — what changed, the judgments a reviewer has to make with the exact lines that settle each one, the order…

guardstatusprompttimeragents
★ 42v1.3.0MITupdated 2026-10-26wyeworks/accountable-review
A shopper browsing a rack in a slop shop
README

<h1 align="center"> <img src="examples/assets/logo.png" alt="accountable-review" width="560"> </h1>

AI-assisted code review for teams that want to move faster with coding agents without losing control of their codebase.

accountable-review turns a pull request into a Review Map: a published HTML page that guides a reviewer through what changed, how the new behaviour works, what existing code is affected, and what to understand before merge.

It ships two skills: review-map, which produces the page for a Rails or a Rust codebase — a Rust backend or Rust in general — with or without a separate client such as Next.js, with Elixir/Phoenix and React (a Next.js app or React in general) support still in development; and setup-ci, which arranges for one to be produced automatically on every review-ready pull request.

Built by WyeWorks.


Contents 📑


Motivation ⚡

Comprehension debt

AI coding tools can produce large changes much faster than teams can absorb them.

Tests can pass. AI reviewers can find issues. Coding agents can fix those issues.

And still:

Do you understand how the system works now?

That is the problem accountable-review focuses on.

When code enters the codebase faster than the team understands it, short-term speed can become long-term loss of control. That gap has a name — comprehension debt — and it comes due the first time someone has to change the code nobody read.

The answer is not less AI. It is more reviewer understanding alongside it — more productivity and more comprehension, rather than one bought with the other:

Move faster with AI. Stay in control.

AI code review ≠ AI-assisted code review

AI code review is great at asking:

  • Is there a bug here?
  • Is this implementation suspicious?
  • What should be fixed?

accountable-review helps the human reviewer ask:

  • What behaviour now exists?
  • Why was it introduced?
  • How do the pieces work together?
  • What existing assumptions now matter?
  • What should I remember when maintaining this later?

The plugin does not approve the PR for you.

It helps a competent reviewer understand the change well enough to decide.

No approval verdict. No severity score. No fake confidence badge.

Human judgment stays final. A page good enough to approve from without reading the code would be a failure — the reviewer would be holding a verdict instead of a mental model.

Diffs are necessary. They are no longer sufficient.

Diffs are excellent for reviewing code line by line.

Is this condition correct?
Is this query efficient?
Did this line introduce a regression?

But modern AI-assisted development also pushes review to a higher level:

What behaviour changed?
How does this work across the system?
What must the team understand to maintain it?

A Review Map adds that layer.

Review behaviours, not file lists

A diff is organized by files.

A Rails, Rust, Phoenix or Next.js feature is not.

One behaviour may cross:

routes
  ↓
controller
  ↓
model / service
  ↓
policy
  ↓
job
  ↓
serializer
  ↓
frontend contract

On a Rust backend the hops are different — router and its layers, extractor, handler, error mapping, query, migration — and on Phoenix different again — router, controller or LiveView, context, changeset, Repo, worker, template — and on Next.js different again — page, server component, client component, server action, cache tag, route handler — and the point is the same: no directory contains the behaviour.

accountable-review traces the PR around the behaviour being implemented, not the order of files in the diff — and then publishes the part of that work you have to act on: the handful of judgments the change asks of you, and where to look to make each one.

The most important code may not have changed

A PR can change the meaning of code without changing its lines.

Examples:

  • an existing policy now controls a new flow,
  • an existing model invariant becomes load-bearing,
  • an unchanged serializer gains new meaning,
  • an existing query gets a new caller,
  • a TypeScript type now participates in a changed backend contract.

A normal diff cannot show those relationships. A Review Map can.


What is a Review Map? 🧭

A Review Map is a review agenda: the smallest set of things you have to judge before you can approve a change, with the code that settles each one attached.

Five parts, and a shut evidence block at the foot:

What changed                    one paragraph: what is now true that was not
Context                         when earned: the pieces of this repository the judgments rely
                                on, for a reader who knows the stack but not the codebase
What needs your attention       3-5 checkpoints per independent change the PR makes, 7 at the
                                outside (9 or 11 on a broad change to application code);
                                about behaviour, structure or how the code was built;
                                each one judgment, framed as a question, and at
                                most one small figure where its shape is clearer than prose:
                                a chain, paths converging on one invariant, a lifecycle, or
                                an entity and its relationships
Read the code in this order     3-7 stops, in the order that builds understanding
Impact outside the diff         1-3 chains, from changed code into code it gives new meaning to,
                                each node linked to the file it lives in
▸ Evidence & diff coverage      every changed path, the searches run, the rest of what was found

Claims about unchanged code come with the code attached: a collapsed excerpt of the real source, quoted by a script rather than retyped, that you open when you are ready to check that particular claim. The page reads completely with every excerpt closed — the sentence carries the consequence, the excerpt carries the proof.

The Review Map does not replace the diff.

It helps the diff make sense.

📖 Full anatomy of the page — every section, the checkpoint, the staging behaviour, the excerpt and framework-anchor rules — is in docs/review-map.md.


Installation ⚙️

Claude Code

Add the WyeWorks marketplace and install, from inside Claude Code:

/plugin marketplace add wyeworks/claude-plugins
/plugin install accountable-review@wyeworks

or from a terminal:

claude plugin marketplace add wyeworks/claude-plugins
claude plugin install accountable-review@wyeworks

Restart, and the skills are available in every project as /accountable-review:review-map and /accountable-review:setup-ci. claude plugin update accountable-review@wyeworks takes the next release; you only receive one when the version in the plugin's manifest moves, so an update is something you ask for.

Add --scope project to both commands to declare the plugin in a repository's own settings, so everyone working on it gets the same one.

To run it from a checkout instead — which is what you want if you are changing the plugin, since /reload-plugins then picks up your edits without restarting:

git clone https://github.com/wyeworks/accountable-review.git
cd /path/to/your/app
claude --plugin-dir /path/to/accountable-review

Nothing is installed that way, so git pull in the checkout is how you update, and the skills exist only for sessions started with that flag.

Codex

This repository is its own Codex marketplace. From a terminal:

codex plugin marketplace add wyeworks/accountable-review
codex plugin add accountable-review@accountable-review

Restart Codex, and the skill is available in every project as $accountable-review:review-map — the same name as in Claude Code, behind Codex's $ instead of /. codex plugin marketplace upgrade accountable-review fetches the latest catalogue, and as with Claude Code you only receive a release when the version in the plugin's manifest moves. codex plugin remove accountable-review@accountable-review uninstalls it.

Open the repository you want to review in Codex, then invoke:

$accountable-review:review-map

The result is a local HTML file, linked from the response, using the same template and completeness gate as Claude. To choose its destination, add --output /absolute/path/outside-the-repo; the page is written as index.html there. No hosting service or publishing plugin is required.

High effort is the default and requires Codex subagent tools for the independent falsification pass. If those tools are unavailable, the skill reports the limitation; use --effort low explicitly to run without independent readers. The page never presents that pass as an approval.

Codex CI execution is not supported yet. setup-ci and the CI runner still use Claude Code and Anthropic credentials, so the Codex plugin ships review-map alone.

To run it from a checkout instead — which is what you want if you are changing the skill, since edits apply without reinstalling — link it into Codex's skills directory:

mkdir -p ~/.agents/skills
ln -s /path/to/accountable-review/skills/review-map ~/.agents/skills/review-map

Linked that way it is a standalone skill invoked as $review-map, and git pull in the checkout is how you update. Use the marketplace or the link, not both, or Codex lists the skill twice.

See Codex setup and verification for removal and the boundaries of this integration.

Skills CLI

The skills live under skills/ as ordinary Agent Skills, so the cross-agent skills CLI installs them into Claude Code and Codex without cloning anything:

npx skills add wyeworks/accountable-review

It asks which skills and which agents; answer in flags instead with, for example:

npx skills add wyeworks/accountable-review -g --skill review-map -a claude-code -a codex

Prefer -g. Without it the skills are copied into the current project (.agents/skills/, .claude/skills/ and so on), which puts files in the repository you are about to review. npx skills update takes new commits, and npx skills remove review-map uninstalls.

Installed this way the skill is a standalone one rather than part of a plugin, so in Claude Code it is invoked as /review-map instead of /accountable-review:review-map, and in Codex as $review-map instead of $accountable-review:review-map. --effort high still works in Claude Code: the independent readers are launched as general-purpose subagents handed the same bundled mandate, rather than as the plugin's registered claim-falsifier agent. Install through the plugin or the skills CLI, not both, or Claude Code lists the skill twice.

The CLI can place the skills in any other agent it supports, Pi for example. Outside Claude Code, review-map follows one set of instructions whichever agent it is: the page is a local HTML file, and --effort high needs an independent reader — the agent's own subagents, or else a read-only background run of its own CLI. An agent with neither says so and offers --effort low. Only Claude Code and Codex are tested.

setup-ci is offered too — /setup-ci in Claude Code, the only host it works in. The workflow it writes clones the plugin itself at a pinned tag, so how you installed the skill locally does not matter to CI.


Usage 🚀

Run it from inside the repository you are reviewing:

/accountable-review:review-map              # current branch against its base
/accountable-review:review-map 412          # a PR number
/accountable-review:review-map https://github.com/org/repo/pull/412
/accountable-review:review-map feature/some-branch

In Claude Code you get back a URL. The page is a private Claude Artifact until you share it. Re-running for the same PR publishes a new map and leaves the earlier one where it was; --update edits the earlier map in place, so the Review Map tracks the PR across pushes at one URL.

It publishes early and fills in as parts complete: open it at minute two, watch it arrive, start reading the moment the part you need lands. The checkpoints arrive one at a time, and their questions arrive first — so you know what the change is asking you to judge well before the explanations land. While it is unfinished it says so in a banner, and every part still coming is marked pending, so a half-written page can never be mistaken for a finished one.

While it runs, Claude Code's status line shows what it is doing — tracing consumers, cutting excerpts, writing the page — with the elapsed time and how many checkpoints are written. Every field is read from the run rather than estimated. The one exception is a bar, labelled ~. It measures against earlier runs of the same kind in that repository, so it appears once one such run has finished with its coverage gate passed.

The same line counts what the run spends: tokens across every model request the run makes, its falsifiers' included, and — on a Claude subscription — how far your 5-hour usage window has moved since the run began. When the run ends, the transcript gets one line with the breakdown and each window's before and after. The window percentages are your account's, so anything else you run meanwhile moves them too. In Codex, which has no status line a plugin can draw on, the run reports the same line in chat at the end, read from Codex's own session log.

To have one generated for every pull request instead of by hand, see CI integration below.

Basic usage

This generates the default Review Map for PR #412. The skill works best for PRs that are about to be merged, but it also works well with already-merged PRs when you want to catch up on changes.

/accountable-review:review-map 412

What makes it onto the page is the part you actually need to act on. For a small or medium-sized PR, that usually means around 700 to 1,500 words.

How hard it works

/accountable-review:review-map 412                 # --effort high, the default
/accountable-review:review-map 412 --effort low    # opt out of the falsification pass

Everything the skill writes rests on claims it checked itself — and the context that wrote a claim is the one least able to see what it assumed. --effort high, the default, adds a second reader that does not share that context. The run writes its analysis down first, one note per behaviour, and sends a read-only claim-falsifier subagent at each note before any of it reaches the page, with a single mandate: assume this is wrong in ways that matter, and find evidence in the repository that contradicts it. It rewrites nothing; it returns challenges, each anchored in a line it opened. The run then opens the cited file itself and corrects, downgrades or drops the claim. A challenge it cannot confirm is dropped, exactly as an unconfirmed finding is.

It is on by default because it is very nearly free and it changes what the page finds: on a 28-file pull request the whole pass cost 23 seconds of waiting, under 1% of the run, and the same change reviewed without it missed five things the falsified page carried. --effort low turns it off, which is worth doing when the diff is small enough that a second reader has nothing to find.

Onboarding a reviewer into the stack

A third axis, and the only one that puts anything inside a checkpoint:

/accountable-review:review-map 412 --mentor          # add framework primers
/accountable-review:review-map 412 --mentor rails    # the same, naming the stack

A Review Map normally assumes you know the framework and are meeting this change for the first time. --mentor is for the other case — a reviewer new to Rails, to Rust, to Phoenix or to React, on their first pull requests in an unfamiliar codebase. Where a judgment turns on a framework rule they may not know, the page stops linking to the manual and states the rule: a short primer inside that checkpoint, with the API named, the behaviour explained, a worked example on a generic class, the line in your repository that made it relevant, and the pinned documentation link it came from.

Phoenix and React today: a primer is gated on the documentation link it escalates from, and the Elixir and React catalogues ship closed until a verification run has opened every row in them. So --mentor on a Phoenix, React or Next.js project currently produces no primers and says so. That is the fail-closed rule doing its job — a page with no primer is narrower, a page with an invented link is wrong. The Rust catalogue shipped closed the same way and has since been opened, so a Rust page can carry primers, framed in graphite rather than Rails red.

When the branch keeps moving

/accountable-review:review-map 412 --update    # re-read only the new commits

A Review Map describes one revision, and a pull request that keeps gaining commits after review opens ends up with a map that quietly describes an older one. --update is the cheap way to keep it current: it reads the commits since the page it is updating, re-analyses the judgments those commits reach, and edits that page in place at the same URL. What the new commits did not touch is carried, which is where the saving comes from — tracing consumers across the diff is most of a run's cost, and an update traces only what moved.

You are trading re-reading for speed, and the page says so. A carried judgment is one this run did not verify again. So an updated page names both revisions in its masthead and carries one sentence saying which parts still describe the earlier one. If you want the fuller read, run it again without --update — a map generated from scratch describes one revision throughout, and that is the right call before a final review pass on a branch that has moved a lot.

It refuses rather than guessing. A force-push or rebase, a base branch that moved underneath, a delta covering more than half the diff, a lock file bump, or a recorded search that now finds the changed code — each of those means the previous page is not a safe thing to build on, so the run regenerates from scratch and tells you which one it hit.


What to expect from a map 🔬

Evidence over confidence

The tool separates what is known from what is inferred.

A statement may come from:

  • changed code,
  • unchanged repository code,
  • tests,
  • inference,
  • or uncertain intent.

A claim the diff shows directly carries no label. Everything else is marked — from unchanged code, inferred from tests, inferred, uncertain — so an inference can never pass as a fact. Where the tool cannot establish intent, it says so:

It is unclear whether existing time entries stay editable after archival. No test covers it.

Every claim also carries a file:line into your repository, and by default a second reader attacks those claims before the page is finished (see Usage → effort).

Nor does the page claim to have found everything — see What a Review Map cannot do below. It never reads as a clean bill of health, and it never carries a boilerplate disclaimer saying so either: the limits are the same on every Review Map, so they are written down once, here, rather than reprinted under a heading you have already read a dozen times.

The goal is not to sound confident. The goal is to help the reviewer investigate the change.

What a Review Map cannot do

A Review Map is written by a model reading your repository. That is what lets it trace a consequence into code the diff never opened, and it is also the honest limit on the page.

  • It is a pass, not an audit. Three passes over the same 109-file diff produced eight headline findings between them, only one of which appeared in all three. Explanation is reproducible; defect discovery is sampling.
  • It has blind spots, and they are not random. Behaviour living in configuration, in data, in a queue, in another service or in the gap between two deploys is harder to reach from a diff than behaviour living in a method — so those are the regions a map is quietest about, and quiet is not the same as clear. On a very large diff it also runs out of room before it runs out of diff, and says which region it skimmed.
  • Some of it can simply be wrong — a misread method, a framework default that does not hold for your version, a consequence prevented somewhere the run never looked. Every claim is labelled by how it is known and carries a file:line, so open the citation for anything you would act on.
  • It never decides anything. A map that says nothing about a file is not telling you the file is fine, only that this pass surfaced no judgment there.

And it depends on the model behind it. We develop and test with Claude Opus 5 most of the time, and that is what the page's depth is calibrated against. Other models will trade cost for reach differently — try a few against your own codebase and keep the one whose maps you actually trust.

Ruby on Rails first, then Rust, Phoenix and React

The plugin is optimized and most heavily tested for Rails applications. That matters because Rails behaviour often emerges from several pieces working together:

  • routes
  • controllers
  • Active Record models
  • validations and callbacks
  • policies
  • jobs
  • serializers
  • service objects
  • tests
  • frontend clients

The plugin is designed to help reviewers understand those relationships as a system, and it knows where the framework's own rules bite: update_all at a call site the diff never opened skips the validation this PR adds, a uniqueness validation is not a unique index, --sandbox rolls back so after_commit never fires there.

It also reads the app for what your team already decided. A value object in app/models is ordinary; a value object in app/models when four of its kind live in app/services is a choice someone made, and the page will ask whether it was deliberate — with the four siblings

Source 2 files
hooks/progress.ts 327 lines
1// progress.ts — the e2e progress board (skills/review-map/evals/e2e/progress.rb), as one status
2// line in Claude Code while /accountable-review:review-map runs interactively.
3//
4//   🌔 review map  ▕███████████▍       ▏  47%  11:02 / ~23:30  🔎 tracing consumers  🔧 38  🥊 4  📄 2/4  🪙 3.12M  ⏳ 5h +6%
5//
6// Every field is READ, never guessed, and that is the rule this file keeps: a progress line that
7// invents progress is the verification badge of the terminal, and the page itself is forbidden
8// that badge. Three sources, each one the engine or the run already produces:
9//
10//   * engine events — asking for the skill starts the run, each main-loop tool call names the
11//     activity through hooks/activity.json (the table progress.rb reads too), each claim-falsifier
12//     spawn is counted, and the coverage gate passing then the turn answering ends the run;
13//   * the page the run is staging — checkpoints written against pending ones;
14//   * the clock, against the median of this repository's earlier generations of the same kind,
15//     which this file records itself. With none recorded there is no bar, only elapsed time;
16//   * what the run spent: the usage the API reported for every request the run made, the main
17//     loop's and its falsifiers' (another agent working beside the run is not the run's), and the account's 5-hour window as the engine measures it, from the
18//     run's first reading. When the run ends the transcript gets one line with the breakdown.
19//
20// The activity is the latest tool call by purpose, never a step number: steps interleave and
21// cannot be read off a run (evals/README.md § Profiling one run), and this does not pretend
22// otherwise. It observes and nothing else — every hook passes its event on unchanged, and every
23// one has a .catch that still does, so a bug in the line can never stall a generation.
24
25import type { EngineInterface, Register, Timer } from 'claude-code'
26
27import {
28  type Activity,
29  type Limit,
30  type Usage,
31  type RunKind,
32  type Vars,
33  assignedW,
34  checkpoints,
35  label,
36  line,
37  median,
38  moved,
39  NO_USAGE,
40  addUsage,
41  spent,
42  totalTokens,
43  outputPage,
44  pagePath,
45  parseActivity,
46  repoKey,
47  runKind,
48  runsGate,
49  summary,
50} from './board'
51
52const REVIEW_MAP = /(^|:)review-map$/
53const FALSIFIER = /(^|:)claim-falsifier$/
54const KEEP = 20 // generations remembered per repository and kind
55
56type Run = {
57  started: number
58  paused: number // milliseconds spent waiting between turns, which are not generation
59  waitingSince?: number
60  ended?: 'done' | 'stopped' | 'interrupted'
61  endedAt?: number
62  activity?: string
63  tools: number
64  falsifiers: number
65  page?: string
66  vars: Vars
67  checkpoints?: string
68  sawGate: boolean
69  kind: RunKind
70  eta?: number
71  repo?: string
72  tick: number
73  timer?: Timer
74  usage: Usage
75  falsifierUsage: Usage
76  falsifierIds: Set<string>
77  firstLimits: Limit[] // each window's first reading inside this run
78  lastLimits: Limit[]
79}
80
81// The module's own variables start over on a reload, as register runs again.
82let table: Activity = []
83let run: Run | undefined
84
85function elapsedMs(r: Run, now: number) {
86  return (r.endedAt ?? r.waitingSince ?? now) - r.started - r.paused
87}
88
89const FIVE_HOUR = 'five_hour'
90
91async function draw($: EngineInterface) {
92  if (!run) return
93  const now = await $.clock.now()
94  const at = (ls: Limit[]) => ls.find(l => l.kind === FIVE_HOUR)
95  $.ui.status(line({
96    ...run,
97    waiting: run.waitingSince !== undefined,
98    elapsed: elapsedMs(run, now) / 1000,
99    tokens: totalTokens(run.usage),
100    window: moved(at(run.firstLimits), at(run.lastLimits)),
101  }))
102}
103
104// A window's first reading inside the run is its baseline. A fresh session has no reading before
105// its first response, so there the baseline is the first response's: the share is then short by
106// at most one request, never padded. A window that resets mid-run keeps its old baseline, so it
107// shows no share at all rather than the part since the reset.
108function measured(r: Run, limits: readonly Limit[]) {
109  for (const l of limits) {
110    if (!r.firstLimits.some(f => f.kind === l.kind)) r.firstLimits = [...r.firstLimits, { ...l }]
111  }
112  if (limits.length > 0) r.lastLimits = limits.map(l => ({ ...l }))
113}
114
115async function readLimits($: EngineInterface): Promise<Limit[]> {
116  try {
117    return [...(await $.session.usage()).rateLimits]
118  } catch {
119    return [] // no reading is no reading: the line shows tokens alone
120  }
121}
122
123async function recount($: EngineInterface) {
124  if (!run?.page) return
125  try {
126    run.checkpoints = checkpoints(await $.fs.read(run.page))
127  } catch {
128    // a page mid-Edit or not written yet: the next page-touching call will have it
129  }
130}
131
132function tick($: EngineInterface, r: Run) {
133  r.timer?.cancel()
134  r.timer = $.clock.every(1000, () => {
135    r.tick += 1
136    void draw($)
137  })
138}
139
140function historyKey(repo: string, kind: RunKind) {
141  return `generations:${kind}:${repo}`
142}
143
144// The command as typed, or as the engine records a typed skill command; a sentence that merely
145// mentions review-map is not a request for one.
146function isCommand(text: string) {
147  return /(^\s*|<command-name>)\/(accountable-review:)?review-map(?=\s|<|$)/.test(text)
148}
149
150async function start($: EngineInterface, command: string) {
151  run?.timer?.cancel()
152  if (table.length === 0) {
153    table = parseActivity(await $.fs.read(`${$.plugin.root}/hooks/activity.json`))
154  }
155  const kind = runKind(command)
156  const repo = await $.session.repo()
157  const key = repo ? repoKey(repo.remote, repo.root) : undefined
158  const past = key ? await $.store.get(historyKey(key, kind)) : undefined
159  const mine: Run = {
160    started: await $.clock.now(),
161    paused: 0,
162    tools: 0,
163    falsifiers: 0,
164    sawGate: false,
165    kind,
166    page: outputPage(command),
167    vars: { TMPDIR: await $.env.get('TMPDIR') },
168    tick: 0,
169    repo: key,
170    eta: Array.isArray(past) ? median(past.filter((n): n is number => typeof n === 'number')) : undefined,
171    usage: NO_USAGE,
172    falsifierUsage: NO_USAGE,
173    falsifierIds: new Set(),
174    firstLimits: [],
175    lastLimits: [],
176  }
177  // A reading from before an idle stretch can belong to a window that has since reset: as a
178  // baseline it would match no later reading, and the run would show no share at all.
179  measured(mine, (await readLimits($)).filter(l => !(Date.parse(l.resetsAt ?? '') <= mine.started)))
180  run = mine
181  tick($, mine)
182  await draw($)
183}
184
185export const register: Register = on => {
186  table = []
187  run = undefined
188
189  // A run starts where the skill is asked for, in one of the two ways a person or the model can ask:
190  // the command typed as a prompt, or a Skill tool call naming it. `skill.prompt` would be the
191  // obvious event and is not one this mod can use: the engine's own security module sends it
192  // beneath the user tier, so a plugin's hook on it never runs (the debug log says "skill.prompt
193  // bypassed by cc-plugin-sec-default").
194  //
195  // A prompt typed over a running turn (`turnId`) is a note to that turn, not a new run. Any new
196  // prompt takes down the line a finished run left standing.
197  on('prompt.submit', async ($, e, next) => {
198    if (run?.ended) {
199      run = undefined
200      $.ui.status(undefined)
201    }
202    if (e.turnId === undefined && isCommand(e.text)) await start($, e.text)
203    return next(e)
204  }).catch(($, e, next) => next(e))
205
206  // The main loop only: progress.rb reads the parent transcript, and a falsifier's own reads are
207  // its work, not the run's activity. Its spawn is what gets counted, below.
208  on('tool.call', async ($, e, next) => {
209    if (e.agentId !== undefined) return next(e)
210    const args = e as unknown as Record<string, unknown>
211    const asked = e.tool === 'Skill' && REVIEW_MAP.test(String(args.skill ?? ''))
212    if (asked && (!run || run.ended)) {
213      await start($, `/review-map ${String(args.args ?? '')}`)
214      return next(e)
215    }
216    if (!run || run.ended) return next(e)
217    const mine = run
218    const text = summary(args)
219    mine.tools += 1
220    mine.activity = label(table, text) ?? mine.activity
221    if (typeof args.command === 'string') mine.vars.W = assignedW(args.command, mine.vars) ?? mine.vars.W
222    mine.page = pagePath(args, mine.vars) ?? mine.page
223    await draw($)
224    const result = await next(e)
225    // Passing, not mentioning: the gate exits non-zero when the inventory and the diff disagree.
226    if (runsGate(args) && result.deny === undefined && result.isError !== true) mine.sawGate = true
227    if (mine.page && /page-skeleton\.sh|\.html\b/.test(text)) {
228      await recount($)
229      await draw($)
230    }
231    return result
232  }).catch(($, e, next) => next(e))
233
234  on('agent.spawn', async ($, e, next) => {
235    const mine = run && !run.ended && FALSIFIER.test(e.subagentType) ? run : undefined
236    if (mine) {
237      mine.falsifiers += 1
238      await draw($)
239    }
240    const result = await next(e)
241    if (mine && result.agentId) mine.falsifierIds.add(result.agentId)
242    return result
243  }).catch(($, e, next) => next(e))
244
245  // Every request the run makes, counted once the response is whole: the main loop's and its
246  // falsifiers'. The skill spawns no other agent, so any other subagent is someone else's work
247  // running beside it. A falsifier still reading after the main turn ended is the run's too, so a
248  // waiting run keeps counting. The stream passes through untouched.
249  on('turn.step', async function* ($, e, next) {
250    const mine = run && !run.ended ? run : undefined
251    const result = yield* next(e)
252    const falsifier = e.agentId !== undefined && mine?.falsifierIds.has(e.agentId) === true
253    if (mine && !mine.ended && result.usage && (e.agentId === undefined || falsifier)) {
254      try {
255        mine.usage = addUsage(mine.usage, result.usage)
256        if (falsifier) mine.falsifierUsage = addUsage(mine.falsifierUsage, result.usage)
257        await draw($)
258      } catch {
259        // the count is the line's, never the request's
260      }
261    }
262    return result
263  }).catch(async function* ($, e, next) {
264    return yield* next(e)
265  })
266
267  // The engine's own measurement, pushed after each main-thread turn and whenever a window moves a
268  // whole point.
269  on('session.measure', async ($, e, next) => {
270    if (run && !run.ended) {
271      measured(run, e.rateLimits)
272      await draw($)
273    }
274    return next(e)
275  }).catch(($, e, next) => next(e))
276
277  // A run can span turns: the skill stops to ask (two stacks, say), or the main loop ends its turn
278  // while background falsifiers read and is woken by their notifications. So a turn that answers
279  // before the gate has passed pauses the run rather than ending it, and the next main-loop turn
280  // resumes it; the time between is the person's or the notification's, not generation's.
281  on('turn.start', async ($, e, next) => {
282    if (run && !run.ended && run.waitingSince !== undefined) {
283      run.paused += (await $.clock.now()) - run.waitingSince
284      run.waitingSince = undefined
285      tick($, run)
286      await draw($)
287    }
288    return next(e)
289  }).catch(($, e, next) => next(e))
290
291  // Its length feeds the next run's ETA only when the gate passed and the turn answered, so a run
292  // that stopped early never shortens the bar.
293  on('turn.complete', async ($, e, next) => {
294    if (run && !run.ended && e.agentId === undefined) {
295      const mine = run
296      mine.timer?.cancel()
297      const now = await $.clock.now()
298      if (e.reason === 'answer' && !mine.sawGate) {
299        mine.waitingSince = now
300      } else {
301        mine.endedAt = now
302        mine.ended = e.reason === 'answer' ? 'done' : e.isAborted ? 'interrupted' : 'stopped'
303      }
304      await recount($)
305      if (mine.ended) {
306        measured(mine, await readLimits($))
307        $.ui.log(spent(mine.usage, mine.falsifierUsage, mine.firstLimits, mine.lastLimits))
308      }
309      await draw($)
310      if (mine.ended === 'done' && mine.repo) {
311        const key = historyKey(mine.repo, mine.kind)
312        const past = await $.store.get(key)
313        const kept = Array.isArray(past) ? past.filter(n => typeof n === 'number') : []
314        await $.store.set(key, [...kept, elapsedMs(mine, now) / 1000].slice(-KEEP))
315      }
316    }
317    return next(e)
318  }).catch(($, e, next) => next(e))
319
320  on('session.end', async ($, e, next) => {
321    run?.timer?.cancel()
322    run = undefined
323    $.ui.status(undefined)
324    return next(e)
325  }).catch(($, e, next) => next(e))
326}
327
hooks/board.ts 243 lines
1// board.ts — the pure half of the progress line: what a field says, given what was read. Nothing
2// here reads anything; progress.ts does the reading, and this file turns readings into one line.
3// The rule both keep is progress.rb's: every field is READ, never guessed.
4
5export type Activity = readonly (readonly [RegExp, string])[]
6
7export const MOON = ['🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'] as const
8const BLOCKS = ['▏', '▎', '▍', '▌', '▋', '▊', '▉'] as const
9
10// hooks/activity.json is the one copy of the table, read by this mod and by progress.rb alike.
11export function parseActivity(json: string): Activity {
12  const rows = JSON.parse(json) as [string, string][]
13  return rows.map(([pattern, label]) => [new RegExp(pattern), label] as const)
14}
15
16// The same summary progress.rb#calls builds from a transcript's tool_use block, so the one table
17// matches the same text in both. A tool call's arguments arrive flat on the event.
18export function summary(e: Record<string, unknown>): string {
19  const s = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
20  return `${s('tool')} ${s('subagent_type')} ${s('command')} ${s('file_path')} ${s('pattern')}`
21}
22
23// First match wins, so specific beats general; no match leaves the previous activity standing.
24export function label(table: Activity, text: string): string | undefined {
25  return table.find(([re]) => re.test(text))?.[1]
26}
27
28// Which kind of run the command asked for. An --update re-run reads only the delta and a low-effort
29// run sends no falsifiers, so each finishes on its own clock and keeps its own history: a median
30// over all three would set a full run's bar by a three-minute update.
31export type RunKind = 'update' | 'low' | 'high'
32
33export function runKind(command: string): RunKind {
34  if (/(^|\s)--update(?=\s|$)/.test(command)) return 'update'
35  if (/(^|\s)--effort[= ]low(?=\s|$)/.test(command)) return 'low'
36  return 'high'
37}
38
39// Where --output puts the page: <dir>/index.html, named in the command and nowhere else.
40export function outputPage(command: string): string | undefined {
41  const m = command.match(/(?:^|\s)--output[= ]+("([^"]+)"|'([^']+)'|(\S+))/)
42  const dir = m && (m[2] ?? m[3] ?? m[4])
43  return dir ? `${dir.replace(/\/+$/, '')}/index.html` : undefined
44}
45
46// The shell variables SKILL.md writes the page path with. Step 1 derives
47// W="${TMPDIR:-/tmp}/review-map/<repo>-pr-<N>" and step 9 runs `page-skeleton.sh --out
48// "$W/page.html"`, so the path is read by expanding what the run itself assigned. Whatever is
49// still a variable after that is unknown, and an unknown path is no path.
50export type Vars = { W?: string; TMPDIR?: string }
51
52export function expand(text: string, vars: Vars): string | undefined {
53  const out = text
54    .replace(/\$\{TMPDIR:-([^}]*)\}/g, (_, fallback: string) => vars.TMPDIR || fallback)
55    .replace(/\$\{?(W|TMPDIR)\}?(?![A-Za-z0-9_])/g, (whole, name: 'W' | 'TMPDIR') => vars[name] ?? whole)
56    .replace(/\/{2,}/g, '/')
57  return out.includes('$') ? undefined : out
58}
59
60// The W a Bash command assigns, expanded, or undefined when it assigns none.
61export function assignedW(command: string, vars: Vars): string | undefined {
62  const m = command.match(/(?:^|[\s;&|])W=("([^"]*)"|'([^']*)'|(\S+))/)
63  const raw = m && (m[2] ?? m[3] ?? m[4])
64  return raw === null || raw === undefined ? undefined : expand(raw, vars)
65}
66
67// The page a run is staging: `page-skeleton.sh --out <path>` names it first, and an Edit or a
68// Write of the derived page names it again.
69export function pagePath(e: Record<string, unknown>, vars: Vars = {}): string | undefined {
70  if (typeof e.command === 'string') {
71    const m = e.command.match(/page-skeleton\.sh\b.*?--out[= ]+("([^"]+)"|'([^']+)'|(\S+))/)
72    const path = m && (m[2] ?? m[3] ?? m[4])
73    if (path) return expand(path, vars)
74  }
75  if (typeof e.file_path === 'string' && /\/review-map\/[^/]+\/page\.html$/.test(e.file_path)) {
76    return e.file_path
77  }
78  return undefined
79}
80
81// The coverage gate run, as distinct from read: the script is the command word — first, after a
82// separator, or handed to a shell — rather than the argument of cat, sed or grep.
83export function runsGate(e: Record<string, unknown>): boolean {
84  return (
85    e.tool === 'Bash' &&
86    typeof e.command === 'string' &&
87    /(^|[;&|(]\s*|\b(?:ba)?sh\s+)[^\s;&|]*coverage-gate\.sh(?=\s|$)/m.test(e.command)
88  )
89}
90
91// A pending checkpoint is a <section class="cp"> whose <h3> carries span.pending, so each
92// checkpoint is read up to its own close. Comments are stripped first: the template's own
93// comments describe these sections in the same words.
94export function checkpoints(html: string): string {
95  const bare = html.replace(/<!--[\s\S]*?-->/g, '')
96  const cps = bare.match(/<section class="cp\b[\s\S]*?<\/section>/g) ?? []
97  const written = cps.filter(c => !c.includes('class="pending"')).length
98  return cps.length === 0 ? '📄 page started' : `📄 ${written}/${cps.length}`
99}
100
101// What a repository's generation times are kept under: its remote, so every clone and worktree of
102// one repository shares a history, with any credential an HTTPS remote carries taken out first —
103// the store is a file on disk. A repository with no remote is keyed by its root.
104export function repoKey(remote: string | null, root: string): string {
105  if (!remote) return root
106  return remote.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1')
107}
108
109export function median(secs: readonly number[]): number | undefined {
110  if (secs.length === 0) return undefined
111  const sorted = [...secs].sort((a, b) => a - b)
112  return sorted[Math.floor(sorted.length / 2)]
113}
114
115export function clock(secs: number): string {
116  const s = Math.max(0, Math.floor(secs))
117  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
118}
119
120export function bar(frac: number, cells = 20): string {
121  const full = Math.floor(frac * cells)
122  const part = Math.floor((frac * cells - full) * BLOCKS.length)
123  let s = '█'.repeat(full)
124  if (full < cells && part > 0) s += BLOCKS[part]
125  return `▕${s.padEnd(cells)}▏`
126}
127
128// What the run's model requests cost, as the API counted each one: the four counts summed over every
129// request made while the run was live, the falsifiers' included and also kept apart.
130export type Usage = { input: number; output: number; cacheRead: number; cacheWrite: number }
131export type ApiUsage = {
132  input_tokens: number
133  output_tokens: number
134  cache_read_input_tokens: number
135  cache_creation_input_tokens: number
136}
137
138export const NO_USAGE: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
139
140export function addUsage(t: Usage, u: ApiUsage | null | undefined): Usage {
141  if (!u) return t
142  const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
143  return {
144    input: t.input + n(u.input_tokens),
145    output: t.output + n(u.output_tokens),
146    cacheRead: t.cacheRead + n(u.cache_read_input_tokens),
147    cacheWrite: t.cacheWrite + n(u.cache_creation_input_tokens),
148  }
149}
150
151export function totalTokens(t: Usage): number {
152  return t.input + t.output + t.cacheRead + t.cacheWrite
153}
154
155// Each unit starts where the smaller one would round up into it: 999,700 is 1.00M, never 1000k.
156export function tokens(n: number): string {
157  if (n >= 999_500) return `${(n / 1e6).toFixed(n >= 9_995_000 ? 1 : 2)}M`
158  if (n >= 999.5) return `${Math.round(n / 1e3)}k`
159  return String(Math.round(n))
160}
161
162// One rate-limit window as the engine reads it off the API's responses. `percentUsed` is the
163// account's, not the session's: anything else the account runs meanwhile moves it too.
164export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
165
166const WINDOW: Record<string, string> = { five_hour: '5-hour', seven_day: '7-day', spend_limit: 'spend limit' }
167
168// How far one window moved between the run's first reading and its latest. A window that reset in
169// between has no readable share, so it has no delta rather than a negative or a guessed one.
170export function moved(from: Limit | undefined, to: Limit | undefined): number | undefined {
171  if (!from || !to || from.kind !== to.kind) return undefined
172  if ((from.resetsAt ?? '') !== (to.resetsAt ?? '')) return undefined
173  return Math.round((to.percentUsed - from.percentUsed) * 10) / 10
174}
175
176function points(d: number): string {
177  return `+${Math.max(0, d).toFixed(d < 10 ? 1 : 0).replace(/\.0$/, '')}%`
178}
179
180// The line the transcript gets when a run ends: what it read, nothing it would have to estimate.
181export function spent(
182  total: Usage,
183  falsifiers: Usage,
184  first: readonly Limit[],
185  last: readonly Limit[],
186): string {
187  const all = totalTokens(total)
188  const bits = [
189    `review map used ${tokens(all)} tokens`,
190    `(${tokens(total.input)} input · ${tokens(total.cacheWrite)} cache write · ` +
191      `${tokens(total.cacheRead)} cache read · ${tokens(total.output)} output` +
192      (totalTokens(falsifiers) > 0 ? `; falsifiers ${tokens(totalTokens(falsifiers))} of it)` : ')'),
193  ]
194  const windows = last.flatMap(to => {
195    const name = WINDOW[to.kind] ?? to.kind
196    const from = first.find(f => f.kind === to.kind)
197    const d = moved(from, to)
198    if (d === undefined) return [`${name} window at ${to.percentUsed}%`]
199    return [`${name} window ${from!.percentUsed}% → ${to.percentUsed}% (${points(d)})`]
200  })
201  if (windows.length > 0) bits.push(`— ${windows.join(', ')}, account-wide`)
202  return bits.join(' ')
203}
204
205export type Reading = {
206  tick: number
207  elapsed: number // seconds of generation: frozen once the run ends, paused while it waits
208  eta?: number // the median of this repository's earlier generations; absent with none recorded
209  ended?: 'done' | 'stopped' | 'interrupted'
210  waiting?: boolean // the turn ended with the run unfinished; the next turn resumes it
211  activity?: string
212  tools: number
213  falsifiers: number
214  checkpoints?: string
215  tokens?: number // every request the run made so far, falsifiers included
216  window?: number // how far the 5-hour window moved since the run's first reading
217}
218
219// The bar is the only estimate on the line and it is labelled as one (~), held below 100% until
220// the run ends. With no earlier generation recorded there is no bar at all: the eval harness can
221// fall back to a documented order of magnitude, but here that would be progress invented.
222export function line(r: Reading): string {
223  const icon =
224    r.ended === 'done' ? '✅' : r.ended ? '⏹' : r.waiting ? '⏸' : MOON[r.tick % MOON.length]
225  // The icon carries the state's glyph, so the words beside it carry none.
226  const status = r.ended ?? (r.waiting ? 'waiting for the next turn' : (r.activity ?? '🤔 thinking'))
227  const bits = [`${icon} review map`]
228  if (r.eta !== undefined && r.eta > 0) {
229    const frac = r.ended === 'done' ? 1 : Math.min(r.elapsed / r.eta, 0.99)
230    bits.push(bar(frac), `${String(Math.floor(frac * 100)).padStart(3)}%`,
231      `${clock(r.elapsed)} / ~${clock(r.eta)}`)
232  } else {
233    bits.push(clock(r.elapsed))
234  }
235  bits.push(status)
236  if (r.tools > 0) bits.push(`🔧 ${r.tools}`)
237  if (r.falsifiers > 0) bits.push(`🥊 ${r.falsifiers}`)
238  if (r.checkpoints) bits.push(r.checkpoints)
239  if (r.tokens !== undefined && r.tokens > 0) bits.push(`🪙 ${tokens(r.tokens)}`)
240  if (r.window !== undefined) bits.push(`⏳ 5h ${points(r.window)}`)
241  return bits.join('  ')
242}
243