SLOPSHOPPER

pr-assistant

Help with a pull request: /pr-assistant:pr map draws it as one page, /pr-assistant:pr walk draws that map and goes through it with you beside a panel of the…

panerowsguardcommandtoasttool
★ 1v1.3.0MITupdated 2026-10-12AdamAwan/LubbDubb/pr-assistant
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pr-assistant
│ ┃ PR walkthrough ✕ › fix the failing auth test and add an audit log call │ ┃ No walkthrough yet. │ ┃ Start one with /pr-assistant:pr walk <PR ⏺ Read(src/auth.ts) │ ┃ number>. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /walk-panel │ ⎿ pr-assistant: PR walkthrough panel opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · PR walkthrough
No walkthrough yet. Start one with /pr-assistant:pr walk <PR number>.
README

<img src="docs/brand/logo.svg" alt="LubbDubb" width="120">

LubbDubb

A self-hosted, always-running orchestration harness for one software engineer's work — a cockpit that watches your inputs (issues, PRs, CI, review comments), decides what to do on a heartbeat, and dispatches Claude Code agents to do it, escalating to you only what genuinely needs judgment.

The name is the heartbeat: the server's core is a periodic pulse that drives everything.

Where to read what. docs/mission.md is why it exists and what it changes about the job. This file is the overview: what the harness does, how work flows through it, and the configuration that matters on day one. docs/workflow.md is the workflow in full, including where a different one slots in. docs/spec/ is the specification of how every part of the application behaves today, written as fact — every config key, every dispatch rule, the agent runtimes, the API, the cockpit. If you want the detail behind anything below, it is in there. docs/feature-timeline.md is how it got this way.


The pulse

One repeating cycle, driven by a heartbeat (heartbeatIntervalMs, default 30s while the fleet is busy; idleHeartbeatIntervalMs, 5 minutes, while it is not) and also triggerable on demand:

snapshot the world  →  diff against the last snapshot  →  reconcile plans
      →  decide (dispatcher)  →  execute (executor)  →  audit

Every step is recorded. The dispatcher's rationale, every action it emitted, and the outcome of each action are persisted — so an idle cycle is as explainable as a busy one. Agents run in pooled git worktrees (code work) or scratch dirs (desk work), and report back over a typed tool channel.

What it does

Grouped by where in the loop it sits. Each line links to the spec that owns it.

Taking work in

FeatureWhat it is
Opt-in watchingOne ${labelPrefix}-watch tag decides what is acted on, on issues and pull requests alike. Nothing outside it is touched. → [06][s06]
Two providersGitHub and Azure DevOps behind per-capability seams, plus a fake provider the whole suite and the demo run on. → [15][s15]
Tracker statesWhere the provider has workflow states, pickup is gated on them and the harness moves the item to in-progress and in-review. → [06][s06]
Priority and orderPriority labels weight pickup; the ranked plan ships as Up next with a cut-line at current headroom, re-orderable by you. → [05][s05]
Tickets boardEvery open and closed item, as a table or a column-per-state board you drag cards across — the drop's cost said before it lands. → [17][s17]
AttachmentsImages attached to a brief follow the issue to whichever agent works it, stored outside every worktree. → [12][s12]

Deciding

FeatureWhat it is
A rule pipelineTwo dozen named rules walked in a declared order, each proposing work from the world. The order is data, not numbers on a comment. → [05][s05]
A bounded vocabularyThe dispatcher can only ever ask for one of eleven validated actions; anything malformed is rejected and audited, never executed. → [05][s05]
Per-check CI policyWhat to do about which check went red — fix it, fix it with guidance, hold it because it is not ours, or escalate once. → [02][s02]
The decision logExecuted, deferred, rejected and skipped alike, each with its reason and the rule that produced it, expandable to why that rule exists. → [18][s18]
Cooldowns and capsPer-origin attempt caps and cooldowns, so a dispatch that keeps failing escalates instead of looping. → [05][s05]

Doing the work

FeatureWhat it is
Agents in worktreesA bounded pool of checkouts leased to branches and switched rather than recreated, so a branch that comes back starts warm. → [09][s09]
A typed tool channelAn MCP server agents call back on — read the world, raise what they learned, open a pull request, report a check. → [11][s11]
A permission backstopAn agent hitting a command outside the allow-list asks you rather than hanging. → [11][s11]
Models per ruleNamed profiles — a model and the depth it runs at — assigned per dispatch rule, so a conflict fix and a plan are not priced alike. → [02][s02]
Jobs and schedulesAn ad-hoc prompt queued from the cockpit, or queued for you on a cron expression. Both wait for a slot like everything else. → [13][s13]
Crash recoveryAgents orphaned by a restart are parked, and the pulse is held, until you restore, requeue or remove each one. → [10][s10]
Live transcriptsClick an agent and read what it is doing, type into it, and see what it produced mid-run. → [10][s10], [12][s12]

Pull requests

FeatureWhat it is
Health predicatesFailing CI, behind or conflicting with its base, unhandled review threads, ready to merge — one agent per branch, top concern first. → [07][s07]
The fleet reviewOff by default: the harness reads a pull request of its own before a person is asked, with a triage that picks how thoroughly. → [07][s07]
Answering a reviewEvery unhandled thread goes to one agent, replied to through the harness — signed, recorded, and resolved on the provider's own threads. → [07][s07]
StacksA part is based on the part it depends on; a red base is attributed to the PR that owns it, and merging is bottom-up. → [07][s07]
Waiting on youA pull request somebody assigned you, who asked, and how long it has been sitting there. → [17][s17]

The funnel, per goal

FeatureWhat it is
Goal appraisalIs there a goal here to work from? A refusal says what is missing, on the ticket, and lifts when the goal text changes. → [08][s08]
PlanningOne pull request, or a dependency-chained decomposition into parts each with its own branch and scope — or "this is already done". → [08][s08]
Plan approvalAlways. A plan carries risks, scope-outs and how anyone will know it worked, and can be discussed with a conversational planner. → [08][s08]
AssessmentAsked of what was delivered, not of the agent's confidence. Its no arm replans, adds a part, or escalates. → [08][s08]
ValidationChecks that can only be answered by running the delivered thing, written for a person — or handed to your own Claude Code. → [20][s20]
RetrospectiveOne write-up per delivered goal, from the shared scratchpad and the harness's own record of what it cost. → [13][s13]
Close-outThe harness never closes a ticket. It files a standing obligation with your name on it, which settles once the tracker stops listing it open. → [13][s13]

After it lands

FeatureWhat it is
EnvironmentsOff by default. The commit each PR landed as, and whether each environment has it yet — asked with your own command, three-valued. → [24][s24]
ArrivalsArriving somewhere can be what opens what a delivered goal owes you, and what puts a line on the ticket. Both opt-in, per environment. → [24][s24]
Post-deploy watchA goal declares what a running system must show; an arrival opens a window, and your telemetry is asked on a schedule. No model in it. → [29][s29]
ObstaclesWhat is in the fleet's way, keyed rather than matched on prose: two independent voices, an owner, and an exit that is never a person. → [27][s27]
The cross-fleet poolThe distance above fleet: one namespace per fleet in a shared repository, with a corroboration model and a digest. → [28][s28]

Watching the harness itself

FeatureWhat it is
Needs youOne rail: escalations, plan approvals, outbound proposals, permission requests, config health, and the obligations a delivery leaves. → [17][s17]
InsightsWhat runs cost, what they yielded and what came out — plus a live burn watch that surfaces a run several times its bucket's median. → [18][s18]
The runwayWhether there is work left for the fleet, measured in fleet time — and whether the reason there is not is you. → [25][s25]
Config healthOne row per setting that can stop the fleet silently, each ending in a check against the real world rather than advice. → [26][s26]
The error logThe one path every caught failure funnels through: persisted, mirrored to stderr, streamed to the cockpit. → [18][s18]
Self-updateThe harness watches its own build, drains, and hands off to a supervisor that replaces it. → [21][s21]
Local runsThe machine's one dev environment, brought up and taken down from the cockpit, with its output in the pane the fleet already has. → [23][s23]
PetsA vivarium at the foot of the rail. Your actions drop eggs; the eggs hatch. It gates nothing. → [22][s22]

The flow of work

Two entry points, one path. A prompt states a goal and a ticket is found or created for it; a ticket states its own. Everything downstream keys on the ticket, so work started from a prompt is as recoverable, reviewable and reportable as work started from the tracker.

flowchart TD
    P([Start with a prompt]) --> G[Goal is stated]
    T([Start with a ticket]) --> TK
    G -- find or create --> TK[Ticket]
    TK --> V{Enough information<br/>to proceed?}
    V -- no --> AL[Say what is missing,<br/>on the ticket]
    AL --> UW([Stop working it])
    UW -. the goal text changes .-> TK
    V -- yes --> PL[Plan the work]
    PL --> AP{Plan accepted?}
    AP -- no, revise --> PL
    AP -- yes --> WK[/Do the work/]
    WK --> QG{Quality gates<br/>review, CI, a person}
    QG -- not satisfied --> WK
    QG -- satisfied --> M[Merge]
    M --> GC{Goal achieved?}
    GC -- no --> PL
    GC -- yes --> DV[Deliver: validate, write up,<br/>hand back what is yours]
    DV --> AR{Configured<br/>environments?}
    AR -- yes --> EN[Watch it arrive,<br/>then watch it behave]
    AR -- no --> D
    EN --> D([Done])

The standard steps

StepWhat happens
IntakeEvery open issue/PR is fetched and shown. What is acted on is decided by the watch tag, plus tracker workflow states where the provider has them.
Enough information?One agent reads the ticket against the repository and says whether there is a goal here to work from. Only an explicit unclear holds anything.
Plan the workA planning agent reads the repo and returns either one PR will do, a decomposition into dependency-chained parts, or this goal is already met.
Plan accepted?Every plan verdict appears in Needs you. Accepting releases the parts to be scheduled; rejecting falls the issue back to the single-PR path, and it can be held.
Do the workAn agent per part (or one for the whole issue), each in its own worktree. Code is the most common arm, not the only one — a part may finish with a report.
Quality gatesThe fleet's own review of the diff (opt-in), then tests, static analysis, pipeline health and human review. Each failing check is classified per check.
MergeA green, approved, mergeable, comment-clear PR is merged — bottom-up for a stack, and never while it is based on another in-flight branch.
Goal achieved?Asked of what was actually delivered, not of the agent's confidence. A no returns to planning, because what is missing may be a different decomposition.
DeliverA validation sheet of checks only a person or a running system can answer; a retrospective written from the record; the tracker state moved and a status comment.
Close outNothing closes the ticket. A standing obligation with your name on it is filed, and settles itself once the tracker stops listing the item open.
ArrivalWhere environments are configured: the commit each PR landed as, whether each environment has it yet, and — where declared — whether it is behaving now it is there.

The gates that carry the loop

Each is a decision something has to make, not a step that always passes.

  • Enough information to proceed rejects a goal nothing can act on, before an agent spends itself discovering that. Refusal is not silent — it says what is missing, on the ticket — and it is not permanent: the hold ends when the goal text changes, or when anyone comments.
  • Plan accepted is where you see the shape of the work before it happens. There is no switch for it: a plan that started itself can only be undone by a replan, which is strictly worse.
  • Quality gates are a set, not a list — tests, static analysis, pipeline health, human review, and the fleet's own review where it is on. The classification is per check, and the third reading is the one that matters: red, but not ours holds and says why, rather than sending an agent at a wall.
  • Goal achieved is asked of the delivered work. Its no arm proposes a replan, a follow-up part, or escalates — depending on what the assessment says fell short.

Priorities when headroom is scarce

The dispatcher ranks every candidate, then applies the concurrency cut. Roughly, highest first:

  1. An operator queued a job from the cockpit — takes the next free slot.
  2. A PR with problems: failing CI, a stale or conflicting base, an unhandled review comment.
  3. A PR that is ready to merge.
  4. Planning, approval, appraisal and assessment for issues.
  5. Plan parts, then fresh issue pickup.

PR work runs before new issue pickup, so a PR in trouble is always worked ahead of starting new tickets. The full ordered plan ships to the cockpit as Up next, with a cut-line at the current headroom; you can re-order it, and the override persists.

Where you are in the loop

The harness owns the loop; you own the verdicts. You are asked when — and only when — a decision is genuinely yours:

  • Needs you collects escalations, plan approvals, outbound-act proposals, permission requests from agents that hit a command outside the allow-list, the config checks, and what a delivered goal still owes you — a validation sheet to run, a ticket to close.
  • Nothing side-effectful leaves without a human, save two standing authorities that are yours: a stack landing you clicked over named pull requests, and sendPrRepliesWithoutApproval, on by default, which sends a drafted review reply straight to the thread. A rejection stands until the world gives a reason to ask again — a push, a CI result, an approval, a comment — and the reason you typed is handed to the next agent that works that item.
  • A restart never decides for you. Agents orphaned by a crash or shutdown are parked, and the heartbeat is held until you restore, requeue or remove each one.

Two things are deliberately fixed: every act reaching the outside world is authorized, and an agent declares that it finished — silence never reads as success.

Getting started

Node >=22.12 and git. A fresh clone installs with npm ci — node-pty is a native build, so it is not instant (on npm 12+ it builds because package.json lists it in allowScripts).

npm ci                                               # native dep: node-pty
cp lubbdubb.config.example.json lubbdubb.config.json # your local config (gitignored)
npm start                                            # builds the cockpit, serves on 127.0.0.1:4300

Every key in the config is optional and the harness boots with no file at all — but the defaults select the real Claude Code runtime, while the shipped example selects the mock one (agentMode: "raw" against the built-in fake providers). So copy it for a first run and the whole loop turns with no model or provider credentials. From then on the cockpit's Config page edits that same file directly, key by key, leaving its comments and ordering alone — hand-editing and the form are two ways at one file.

npm start builds the cockpit bundle and then runs the server. Two variants matter: npm run start:server skips the build and serves whatever web/dist already holds, and npm run serve runs the server under the supervisor that can replace it — which is what self-update needs, and the way to run it under systemd, NSSM or a long-lived terminal. → docs/spec/21

Boot prints what it decided, and the link to open:

[lubbdubb] cockpit listening on 127.0.0.1:4300
[lubbdubb] open the cockpit: http://127.0.0.1:4300/#t=<token>
[lubbdubb] token minted at .lubbdubb/cockpit-token (0600) — reused on the next start
[lubbdubb] heartbeat=300000ms cap=3
[lubbdubb] agent tools: on

Open it once per browser and the cockpit remembers the token. The harness binds loopback only and every route needs that token, because the cockpit can queue a job — and a job spawns a real agent with write access to your repo. The token file is gitignored, along with the rest of .lubbdubb/ (the SQLite database, worktrees, desk scratch dirs and attachments all live under it).

One click: the Claude Code plugin

The harness ships a Claude Code plugin for your own Claude Code: the /lubbdubb:… skills every Open in Claude Code link in the cockpit calls (/lubbdubb:check 284:C, /lubbdubb:plan 284, /lubbdubb:ask 284, …), the desktop tool channel those skills talk to, and a notice board: a status line above your prompt and a panel beside the transcript with what the harness is waiting on you for, feature progress, pull request states, the fleet and what is up next. Boot writes it to ~/.lubbdubb/plugin:

[lubbdubb] Claude Code plugin 1.0.0-… written to ~/.lubbdubb/plugin — install or update it from the cockpit's MCP tab

Until it is installed the cockpit shows a banner under the top bar; Install it opens the MCP tab, whose button runs claude plugin marketplace add and claude plugin install for you at user scope, and removes the hand-registered lubbdubb MCP server and the old /lubbdubb skill if you had them. Restart open Claude Code sessions to pick it up. Skip it and nothing breaks: every check simply falls to the fleet. → docs/spec/11

Then: use Inject event to simulate the world moving (a CI failure, a review comment) and watch the harness react; click an agent to see its live transcript and type into it; answer items in Needs you; use New job to launch an ad-hoc prompt, or New schedule to have one queued on a cron expression (0 9 * * 1-5 — weekdays at nine, read in the harness's own timezone). The Decision log shows what was decided each cycle and which rule produced it; Activity shows how the world itself changed.

Needs you also carries the configuration checks — one row per setting that can stop the fleet silently, each ending in a check against the real world rather than a sentence of advice. On a fresh install that rail is the shortest route from the mock loop to a working deployment. → docs/spec/26

Configuration

Every key is optional, and every key, its default and its precedence is in docs/spec/02-configuration.md. These are the ones that decide whether a deployment works at all:

KeyDefaultWhy it matters
repoRootthe directory you launch inThe git repository worktrees are cut from. Left alone, the harness works on its own checkout.

| integrations | all fake | Which provider serves each capability — sourceControl, issues, pool.

Source 3 files
hooks/register.tsx 489 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderInput } from 'claude-code'
3
4import type { EdgeState, MapNode, MapStatus, Note, StopKind } from '../types'
5import {
6  clip,
7  finish,
8  goto,
9  MAX_HUNK,
10  MAX_STOPS,
11  MAX_TERMS,
12  note,
13  NOTE_KINDS,
14  plain,
15  readDiff,
16  readMap,
17  slice,
18  text,
19  start,
20  STOP_KINDS,
21  where,
22  type Step,
23} from './walk'
24
25const walk = atom({ plugin: 'pr-assistant', key: 'walk' } as const, null)
26const isPanelShut = atom({ plugin: 'pr-assistant', key: 'isPanelShut' } as const, false)
27
28const PANE = 'pr-walk'
29const TITLE = 'PR walkthrough'
30
31
32const NOTE: Record<Note['kind'], { label: string; color: string }> = {
33  likely: { label: 'likely', color: 'red' },
34  check: { label: 'check me', color: 'yellow' },
35}
36
37type Mark = { mark: string; color?: string }
38
39const CHANGE = {
40  changed: { mark: '~', color: 'yellow' },
41  new: { mark: '+', color: 'green' },
42  removed: { mark: '-', color: 'red' },
43} satisfies Record<string, Mark>
44
45const KIND: Record<StopKind, Mark> = { ...CHANGE, unchanged: { mark: '·' } }
46
47const NODE: Record<MapStatus, Mark> = {
48  ...CHANGE,
49  path: { mark: '·', color: 'blue' },
50  outside: { mark: '○' },
51  test: { mark: 't', color: 'magenta' },
52  doc: { mark: 'd' },
53}
54
55const ARROW: Record<EdgeState, Mark> = {
56  normal: { mark: '→' },
57  changed: { mark: '→', color: 'yellow' },
58  blocked: { mark: '✕', color: 'red' },
59  ghost: { mark: '⇢' },
60  absent: { mark: ' ' },
61}
62
63const TOOLS = [
64  {
65    name: 'walk_start',
66    description:
67      'Open the PR walkthrough panel on a pull request and lay out its stops, in reading order. Replaces any walkthrough already on the panel. Call once, after you have read the PR and split it into stops.',
68    inputSchema: {
69      type: 'object',
70      properties: {
71        pr: {
72          type: 'object',
73          properties: { number: { type: 'integer' }, title: { type: 'string' }, url: { type: 'string' } },
74          required: ['number', 'title'],
75        },
76        summary: { type: 'string', description: 'One or two plain sentences: what the PR does.' },
77        background: {
78          type: 'string',
79          description:
80            'A few plain sentences on the area the PR is in, as it stands before the PR: what that part of the system is for and how it works.',
81        },
82        glossary: {
83          type: 'array',
84          maxItems: MAX_TERMS,
85          description: 'The terms a reader needs for this PR, each with a one-sentence meaning.',
86          items: {
87            type: 'object',
88            properties: { term: { type: 'string' }, meaning: { type: 'string' } },
89            required: ['term', 'meaning'],
90          },
91        },
92        map: {
93          type: 'string',
94          description:
95            "Path to the PR map's JSON (the file the map job built from). With it, each walk_goto draws that stop's part of the map in the chat.",
96        },
97        diff: {
98          type: 'string',
99          description:
100            "Path to the PR's whole unified diff, saved to a file (`gh pr diff <n> > file`). With it, each stop names its `hunks` and walk_goto needs only the stop number.",
101        },
102        stops: {
103          type: 'array',
104          minItems: 1,
105          maxItems: MAX_STOPS,
106          items: {
107            type: 'object',
108            properties: {
109              title: { type: 'string', description: 'A few words, what happens at this stop.' },
110              kind: { type: 'string', enum: STOP_KINDS },
111              files: { type: 'array', items: { type: 'string' } },
112              steps: {
113                type: 'array',
114                items: { type: 'integer', minimum: 1 },
115                description: 'The map step numbers (1-based) this stop covers. Needs `map`.',
116              },
117              hunks: {
118                type: 'array',
119                items: { type: 'string' },
120                description:
121                  'The hunks that matter at this stop, as `path:line` (a head-version line inside the hunk) or `path` for all of a file. Needs `diff`.',
122              },
123            },
124            required: ['title', 'kind'],
125          },
126        },
127      },
128      required: ['pr', 'stops'],
129    },
130  },
131  {
132    name: 'walk_goto',
133    description:
134      "Move the panel to a stop (1-based) as you present it. The stop's hunks, named at walk_start, are drawn on the panel and in the chat under this call. Call each time you present a stop, including when going back.",
135    inputSchema: {
136      type: 'object',
137      properties: {
138        stop: { type: 'integer', minimum: 1 },
139        diff: {
140          type: 'string',
141          description: `Only when walk_start had no \`diff\`: unified-diff hunks (each starting with an @@ header) for this stop, at most ${MAX_HUNK} characters. Replaces the stop's own hunks.`,
142        },
143        path: { type: 'string', description: 'The file the hunk is from, for highlighting.' },
144      },
145      required: ['stop'],
146    },
147  },
148  {
149    name: 'walk_note',
150    description:
151      'Add a note to the panel (a possible issue: kind "likely" for one you believe is real, "check" for one you could not confirm), or clear / reopen one by id once the question is settled.',
152    inputSchema: {
153      type: 'object',
154      properties: {
155        action: { type: 'string', enum: ['add', 'clear', 'reopen'], default: 'add' },
156        id: { type: 'integer', description: 'The note to clear or reopen.' },
157        kind: { type: 'string', enum: NOTE_KINDS },
158        text: { type: 'string', description: 'One or two plain sentences.' },
159        file: { type: 'string' },
160        line: { type: 'integer', description: 'A line in the PR head version of the file.' },
161      },
162    },
163  },
164  {
165    name: 'walk_end',
166    description: 'Mark the walkthrough done once you have given the wrap-up. The open notes stay on the panel.',
167    inputSchema: { type: 'object', properties: {} },
168  },
169] as const
170
171const failed = ($: EngineInterface) => (err: unknown) =>
172  $.ui.toast(`PR walkthrough: ${err instanceof Error ? err.message : String(err)}`)
173const say = ($: EngineInterface, text: string) => () =>
174  void $.prompt.submit({ text, asUser: true }).catch(failed($))
175const draft = ($: EngineInterface, text: string) => () => void $.prompt.fill({ text }).catch(failed($))
176
177async function apply($: EngineInterface, step: Step, isStart = false): Promise<{ result: string } | { deny: string }> {
178  if ('refusal' in step) return { deny: step.refusal }
179  await update($, walk, () => step.walk)
180  if (isStart) await reopen($).catch(() => undefined)
181  else await keepOpen($).catch(() => undefined)
182  return { result: step.reply }
183}
184
185async function reopen($: EngineInterface) {
186  await update($, isPanelShut, () => false)
187  await $.ui.open({ id: PANE, title: TITLE })
188}
189
190async function keepOpen($: EngineInterface) {
191  const [isShut, panes] = await Promise.all([read($, isPanelShut), $.ui.panes()])
192  if (isShut || panes.some(p => p.id === PANE)) return
193  await $.ui.open({ id: PANE, title: TITLE })
194}
195
196export const register: Register = on => {
197  on('session.start', async ($, e, next) => {
198    await Promise.all([
199      ...TOOLS.map(t => $.tool.register({ ...t, inputSchema: t.inputSchema as Record<string, unknown> })),
200      $.command.register({ name: 'walk-panel', description: 'Open the PR walkthrough panel' }),
201    ])
202    return next(e)
203  })
204
205  on('command.run', { command: 'walk-panel' }, async $ => {
206    await reopen($)
207    return { text: 'PR walkthrough panel opened.' }
208  })
209
210  on('ui.close', async ($, e, next) => {
211    if (e.id === PANE && e.origin.kind === 'person') await update($, isPanelShut, () => true)
212    return next(e)
213  })
214
215  on('tool.call', { tool: 'mcp__pr-assistant__walk_start' }, async ($, e) => {
216    const args = e as Record<string, unknown>
217    const path = text(args.map)
218    const diffPath = text(args.diff)
219    let diff = null
220    if (diffPath !== null) {
221      const loaded = await $.fs
222        .read(diffPath)
223        .then(readDiff, (err: unknown) => (err instanceof Error ? err.message : String(err)))
224      if (typeof loaded === 'string' || loaded.length === 0)
225        return {
226          deny: `Could not use the diff at ${diffPath}: ${typeof loaded === 'string' ? loaded : 'it holds no hunks.'} Leave \`diff\` out to send each hunk with walk_goto.`,
227        }
228      diff = loaded
229    }
230    let map = null
231    if (path !== null) {
232      const loaded = await $.fs
233        .read(path)
234        .then(t => readMap(JSON.parse(t)))
235        .catch((err: unknown) => (err instanceof Error ? err.message : String(err)))
236      if (typeof loaded === 'string')
237        return { deny: `Could not use the map at ${path}: ${loaded} Leave \`map\` out to walk without it.` }
238      map = loaded
239    }
240    return apply($, start(args, map, diff), true)
241  })
242
243  on('tool.call', { tool: 'mcp__pr-assistant__walk_goto' }, async ($, e) =>
244    apply($, goto(await read($, walk), e as Record<string, unknown>, e.tool_use_id)),
245  )
246
247  on('tool.call', { tool: 'mcp__pr-assistant__walk_note' }, async ($, e) =>
248    apply($, note(await read($, walk), e as Record<string, unknown>)),
249  )
250
251  on('tool.call', { tool: 'mcp__pr-assistant__walk_end' }, async $ => apply($, finish(await read($, walk))))
252
253  on('ui.render', { component: 'ToolResult', props: { tool: 'mcp__pr-assistant__walk_goto' } }, async ($, e, next) => {
254    const now = await read($, walk)
255    if (e.props.isErrored || now === null) return next(e)
256    const view = now.views[e.props.tool_use_id]
257    const stop = view === undefined ? undefined : now.stops[view.stop]
258    if (view === undefined || stop === undefined) return next(e)
259    const at = view.stop
260    const part = now.map === null ? null : slice(now.map, stop.steps)
261    if (part === null && view.hunks.length === 0) return next(e)
262    const { Box, Text, Code } = $.ui.resolve(e)
263    const width = Math.max(24, (e.viewport?.columns ?? 80) - 8)
264
265    const card = (n: MapNode) => (
266      <Box key={`node-${n.id}`} flexDirection="column" paddingLeft={2}>
267        <Box gap={1}>
268          <Text color={NODE[n.status].color} dimColor={NODE[n.status].color === undefined}>
269            {NODE[n.status].mark}
270          </Text>
271          <Text bold>{plain(n.title)}</Text>
272          {n.file !== null && <Text dimColor>{clip(n.file.split('/').pop() ?? n.file, 40)}</Text>}
273        </Box>
274        {n.note !== null && <Text dimColor>{`    ${plain(n.note)}`}</Text>}
275        {n.before !== null && <Text color="red">{`    before: ${plain(n.before)}`}</Text>}
276        {n.after !== null && <Text color="green">{`    after:  ${plain(n.after)}`}</Text>}
277      </Box>
278    )
279
280    const shown = (part?.edges ?? []).filter(x => x.before !== x.after || x.label !== null)
281
282    const link = (mode: 'before' | 'after', state: EdgeState) => (
283      <Text key={mode} color={ARROW[state].color} dimColor={ARROW[state].color === undefined}>
284        {state === 'absent' ? `${mode}: none` : `${mode}: ${ARROW[state].mark}`}
285      </Text>
286    )
287
288    return (
289      <Box flexDirection="column" borderStyle="round" paddingX={1}>
290        <Text dimColor>{clip(`${part === null ? 'Stop' : 'Map · stop'} ${at + 1}: ${stop.title}`, width)}</Text>
291        {(part?.columns ?? []).map((c, i) => (
292          <Box key={`col-${i}`} flexDirection="column">
293            {i > 0 && <Text dimColor>  ↓</Text>}
294            <Text dimColor>{c.label.toUpperCase()}</Text>
295            {c.nodes.map(card)}
296          </Box>
297        ))}
298        {shown.length > 0 && (
299          <Box flexDirection="column" marginTop={1}>
300            {shown.map((x, i) => (
301                <Box key={`edge-${i}`} gap={1}>
302                  <Text>{clip(`${plain(x.fromTitle)} → ${plain(x.toTitle)}`, Math.max(12, width - 28))}</Text>
303                  {x.label !== null && <Text dimColor>{x.label}</Text>}
304                  {x.before !== x.after && [link('before', x.before), link('after', x.after)]}
305                </Box>
306              ))}
307          </Box>
308        )}
309        {(part?.steps ?? []).map(s => (
310          <Box key={`step-${s.n}`} flexDirection="column" marginTop={1}>
311            <Text bold>{`${s.n}. ${plain(s.title)}`}</Text>
312            {s.text !== null && <Text dimColor>{plain(s.text)}</Text>}
313            {s.before !== null && <Text color="red">{`Before: ${plain(s.before)}`}</Text>}
314            {s.after !== null && <Text color="green">{`After:  ${plain(s.after)}`}</Text>}
315          </Box>
316        ))}
317        {view.hunks.map((x, i) => (
318          <Box key={`hunk-${i}`} flexDirection="column" marginTop={1}>
319            {x.path !== null && <Text dimColor>{clip(x.path, width)}</Text>}
320            <Code source={x.source} format="diff" {...(x.path !== null ? { path: x.path } : {})} />
321          </Box>
322        ))}
323      </Box>
324    )
325  })
326
327  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
328    try {
329      return await drawPane($, e)
330    } catch (err) {
331      const { Text } = $.ui.resolve(e)
332      return <Text dimColor>{`The panel could not draw: ${err instanceof Error ? err.message : String(err)}`}</Text>
333    }
334  })
335}
336
337async function drawPane($: EngineInterface, e: RenderInput<'Pane'>) {
338  const { Box, Text, Button, Link, Code } = $.ui.resolve(e)
339  const now = await read($, walk)
340  const width = Math.max(24, e.props.bodyColumns)
341
342  if (now === null) {
343    return (
344      <Box flexDirection="column">
345        <Text dimColor>No walkthrough yet.</Text>
346        <Text dimColor>Start one with /pr-assistant:pr walk &lt;PR number&gt;.</Text>
347      </Box>
348    )
349  }
350
351  const heading = clip(`#${now.pr.number} ${now.pr.title}`, width)
352  const open = now.notes.filter(n => !n.isCleared)
353  const stop = now.current === null ? null : now.stops[now.current]
354  const at = now.current ?? -1
355  const background = now.background ?? null
356  const terms = now.glossary ?? []
357
358  const header = (label: string, count?: string) => (
359    <Box gap={1}>
360      <Text bold>{label}</Text>
361      {count !== undefined && <Text dimColor>{count}</Text>}
362    </Box>
363  )
364
365  const noteRow = (n: Note) => {
366    const place = where(n)
367    return (
368      <Box key={`note-${n.id}`} flexDirection="column">
369        <Box gap={1}>
370          <Text dimColor>{`${n.id}.`}</Text>
371          {n.isCleared ? (
372            <Text dimColor>cleared</Text>
373          ) : (
374            <Text bold color={NOTE[n.kind].color}>
375              {NOTE[n.kind].label}
376            </Text>
377          )}
378          {place !== null && <Text dimColor>{clip(place, Math.max(8, width - 16))}</Text>}
379        </Box>
380        <Text dimColor={n.isCleared} strikethrough={n.isCleared}>
381          {n.text}
382        </Text>
383        {!n.isCleared && (
384          <Button
385            key={`note-${n.id}-ask`}
386            plain
387            dimColor
388            label="Ask about this"
389            onPress={draft($, `About note ${n.id}: `)}
390          />
391        )}
392      </Box>
393    )
394  }
395
396  return (
397    <Box flexDirection="column" gap={1}>
398      <Box flexDirection="column">
399        {now.pr.url !== null ? (
400          <Text bold>
401            <Link href={now.pr.url} label={heading} />
402          </Text>
403        ) : (
404          <Text bold>{heading}</Text>
405        )}
406        {now.summary !== null && <Text dimColor>{now.summary}</Text>}
407      </Box>
408
409      {background !== null && (
410        <Box flexDirection="column">
411          {header('Background')}
412          <Text dimColor>{background}</Text>
413        </Box>
414      )}
415
416      {terms.length > 0 && (
417        <Box flexDirection="column">
418          {header('Terms', `${terms.length}`)}
419          {terms.map((t, i) => (
420            <Box key={`term-${i + 1}`} gap={1}>
421              <Text bold>{t.term}</Text>
422              <Text dimColor>{t.meaning}</Text>
423            </Box>
424          ))}
425        </Box>
426      )}
427
428      <Box flexDirection="column">
429        {header('Stops', now.isDone ? 'done' : now.current === null ? `${now.stops.length}` : `${at + 1} of ${now.stops.length}`)}
430        {now.stops.map((s, i) => {
431          const isHere = i === at
432          const seen = now.seen.includes(i)
433          return (
434            <Box key={`stop-${i + 1}`} gap={1}>
435              <Text color={isHere ? 'cyan' : undefined} dimColor={!isHere && !seen}>
436                {isHere ? '▶' : seen ? '✓' : ' '}
437              </Text>
438              <Text color={KIND[s.kind].color} dimColor={KIND[s.kind].color === undefined}>
439                {KIND[s.kind].mark}
440              </Text>
441              <Button
442                key={`stop-${i + 1}-go`}
443                plain
444                label={clip(`${i + 1}. ${s.title}`, Math.max(8, width - 6))}
445                onPress={say($, `Go to stop ${i + 1}.`)}
446              />
447            </Box>
448          )
449        })}
450      </Box>
451
452      {stop !== undefined && stop !== null && (
453        <Box flexDirection="column">
454          {header(`Stop ${at + 1}`, stop.kind)}
455          {stop.files.map((f, i) => (
456            <Text key={`file-${i}`} dimColor>
457              {clip(f, width)}
458            </Text>
459          ))}
460          {now.hunks.map((x, i) => (
461            <Code key={`hunk-${i}`} source={x.source} format="diff" {...(x.path !== null ? { path: x.path } : {})} />
462          ))}
463        </Box>
464      )}
465
466      {!now.isDone && (
467        <Box gap={2}>
468          <Button key="back" label="Back" onPress={say($, 'Back.')} />
469          <Button key="next" variant="primary" label="Next" onPress={say($, 'Next.')} />
470          <Button key="done" label="Wrap up" onPress={say($, 'Done, wrap up.')} />
471        </Box>
472      )}
473
474      <Box flexDirection="column" gap={1}>
475        {header('Notes', `${open.length} open`)}
476        {now.notes.length === 0 && <Text dimColor>Nothing flagged yet.</Text>}
477        {now.notes.map(noteRow)}
478        {open.length > 0 && (
479          <Button
480            key="review"
481            label="Post open notes as a review"
482            onPress={draft($, `Post the open notes as a pending review on #${now.pr.number}.`)}
483          />
484        )}
485      </Box>
486    </Box>
487  )
488}
489
hooks/walk.ts 248 lines
1import type { EdgeState, Hunk, MapNode, MapStatus, MapStep, Note, NoteKind, PrMap, Slice, Stop, StopKind, Term, Walk } from '../types'
2
3export const STOP_KINDS: StopKind[] = ['changed', 'new', 'removed', 'unchanged']
4export const NOTE_KINDS: NoteKind[] = ['likely', 'check']
5export const MAX_STOPS = 12
6export const MAX_TERMS = 12
7export const MAX_HUNK = 10_000
8
9const MAP_STATUSES: MapStatus[] = ['changed', 'new', 'removed', 'path', 'outside', 'test', 'doc']
10const EDGE_STATES: EdgeState[] = ['normal', 'changed', 'blocked', 'ghost', 'absent']
11
12export type Step = { walk: Walk; reply: string } | { refusal: string }
13
14type Args = Record<string, unknown>
15
16export const text = (v: unknown): string | null => (typeof v === 'string' && v.trim() !== '' ? v.trim() : null)
17const whole = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) ? v : null)
18const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [])
19const oneOf = <T,>(list: readonly T[], v: unknown): T | null => ((list as unknown[]).includes(v) ? (v as T) : null)
20
21type DiffHunk = { path: string; old: [number, number]; new: [number, number]; source: string }
22
23export function readDiff(raw: string): DiffHunk[] {
24  const out: DiffHunk[] = []
25  let from: string | null = null
26  let to: string | null = null
27  let at: DiffHunk | null = null
28  const side = (l: string) => {
29    const p = l.slice(4).replace(/\t.*$/, '').trim()
30    return p === '/dev/null' ? null : p.replace(/^[ab]\//, '')
31  }
32  for (const line of raw.split('\n')) {
33    if (line.startsWith('diff --git ')) {
34      at = null
35      from = to = null
36    } else if (at === null && line.startsWith('--- ')) from = side(line)
37    else if (at === null && line.startsWith('+++ ')) to = side(line)
38    else if (line.startsWith('@@')) {
39      const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
40      const path = to ?? from
41      at = null
42      if (m === null || path === null) continue
43      const span = (a?: string, b?: string): [number, number] => [Number(a), b === undefined ? 1 : Number(b)]
44      at = { path, old: span(m[1], m[2]), new: span(m[3], m[4]), source: `${line}\n` }
45      out.push(at)
46    } else if (at !== null && /^[ +\-\\]/.test(line)) at.source += `${line}\n`
47    else at = null
48  }
49  return out
50}
51
52const covers = ([start, length]: [number, number], line: number) => line >= start && line < start + Math.max(1, length)
53
54function cut(diff: DiffHunk[], refs: string[]): Hunk[] | string {
55  const chosen = new Set<DiffHunk>()
56  for (const ref of refs) {
57    const m = /^(.*?)(?::(\d+))?$/.exec(ref.trim())!
58    const line = m[2] === undefined ? null : Number(m[2])
59    const inFile = diff.filter(h => h.path === m[1] || h.path.endsWith(`/${m[1]}`))
60    const onNew = line === null ? inFile : inFile.filter(h => covers(h.new, line))
61    const found = onNew.length > 0 || line === null ? onNew : inFile.filter(h => covers(h.old, line))
62    if (found.length === 0) return `\`${ref}\` is in no hunk of the diff`
63    for (const h of found) chosen.add(h)
64  }
65  const hunks: Hunk[] = []
66  for (const h of diff.filter(d => chosen.has(d))) {
67    const last = hunks[hunks.length - 1]
68    if (last !== undefined && last.path === h.path) last.source += h.source
69    else hunks.push({ source: h.source, path: h.path })
70  }
71  const big = hunks.find(h => h.source.length > MAX_HUNK)
72  if (big !== undefined)
73    return `its hunks in ${big.path} come to ${big.source.length} characters; the panel shows at most ${MAX_HUNK}. Name single lines instead`
74  return hunks
75}
76
77export function start(args: Args, map: PrMap | null = null, diff: DiffHunk[] | null = null): Step {
78  const pr = (args.pr ?? {}) as Args
79  const number = whole(pr.number)
80  const title = text(pr.title)
81  if (number === null || title === null) return { refusal: '`pr` needs a whole `number` and a `title`.' }
82  const raw = Array.isArray(args.stops) ? (args.stops as Args[]) : []
83  if (raw.length < 1 || raw.length > MAX_STOPS) return { refusal: `Give 1 to ${MAX_STOPS} stops.` }
84  const stops: Stop[] = []
85  for (const [i, s] of raw.entries()) {
86    const title = text(s.title)
87    const kind = oneOf(STOP_KINDS, s.kind)
88    if (title === null || kind === null)
89      return { refusal: `Stop ${i + 1} needs a \`title\` and a \`kind\` (${STOP_KINDS.join(', ')}).` }
90    const files = strings(s.files)
91    const steps = Array.isArray(s.steps) ? s.steps.map(whole) : []
92    if (steps.length > 0 && map === null) return { refusal: `Stop ${i + 1} names map \`steps\` but no \`map\` was given.` }
93    if (map !== null && steps.some(n => n === null || n < 1 || n > map.steps.length))
94      return { refusal: `Stop ${i + 1}: \`steps\` are map step numbers from 1 to ${map.steps.length}.` }
95    const refs = strings(s.hunks)
96    if (refs.length > 0 && diff === null) return { refusal: `Stop ${i + 1} names \`hunks\` but no \`diff\` was given.` }
97    const hunks = diff === null ? [] : cut(diff, refs)
98    if (typeof hunks === 'string') return { refusal: `Stop ${i + 1}: ${hunks}.` }
99    stops.push({ title, kind, files, steps: steps as number[], hunks })
100  }
101  const rawTerms = Array.isArray(args.glossary) ? (args.glossary as Args[]) : []
102  if (rawTerms.length > MAX_TERMS) return { refusal: `Give at most ${MAX_TERMS} glossary terms.` }
103  const glossary: Term[] = []
104  for (const [i, t] of rawTerms.entries()) {
105    const term = text(t.term)
106    const meaning = text(t.meaning)
107    if (term === null || meaning === null) return { refusal: `Glossary entry ${i + 1} needs a \`term\` and a \`meaning\`.` }
108    glossary.push({ term, meaning })
109  }
110  const url = text(pr.url)
111  return {
112    walk: {
113      pr: { number, title, url: url !== null && /^https?:\/\//.test(url) ? url : null },
114      summary: text(args.summary),
115      background: text(args.background),
116      glossary,
117      stops,
118      current: null,
119      seen: [],
120      hunks: [],
121      notes: [],
122      isDone: false,
123      map,
124      views: {},
125    },
126    reply: `Panel open on #${number} with ${stops.length} stops${map === null ? '' : ', the map loaded'}. Call walk_goto as you reach each one.`,
127  }
128}
129
130export function goto(walk: Walk | null, args: Args, call?: string): Step {
131  if (walk === null) return { refusal: 'No walkthrough is running. Call walk_start first.' }
132  const stop = whole(args.stop)
133  if (stop === null || stop < 1 || stop > walk.stops.length)
134    return { refusal: `\`stop\` is a number from 1 to ${walk.stops.length}.` }
135  const source = typeof args.diff === 'string' && args.diff.trim() !== '' ? args.diff : null
136  if (source !== null && source.length > MAX_HUNK)
137    return { refusal: `The diff is ${source.length} characters; the panel shows at most ${MAX_HUNK}. Send the one hunk that matters.` }
138  const index = stop - 1
139  const hunks: Hunk[] = source === null ? walk.stops[index]!.hunks : [{ source, path: text(args.path) }]
140  return {
141    walk: {
142      ...walk,
143      current: index,
144      seen: walk.seen.includes(index) ? walk.seen : [...walk.seen, index],
145      hunks,
146      isDone: false,
147      views: call === undefined ? walk.views : { ...walk.views, [call]: { stop: index, hunks } },
148    },
149    reply: `Panel on stop ${stop} of ${walk.stops.length}.`,
150  }
151}
152
153export function note(walk: Walk | null, args: Args): Step {
154  if (walk === null) return { refusal: 'No walkthrough is running. Call walk_start first.' }
155  const action = args.action ?? 'add'
156  if (action === 'add') {
157    const kind = oneOf(NOTE_KINDS, args.kind)
158    const body = text(args.text)
159    if (kind === null || body === null)
160      return { refusal: `A note needs a \`kind\` (${NOTE_KINDS.join(', ')}) and a \`text\`.` }
161    const id = walk.notes.reduce((max, n) => Math.max(max, n.id), 0) + 1
162    const line = whole(args.line)
163    const added: Note = {
164      id,
165      kind,
166      text: body,
167      file: text(args.file),
168      line: line !== null && line > 0 ? line : null,
169      stop: walk.current === null ? null : walk.current + 1,
170      isCleared: false,
171    }
172    return { walk: { ...walk, notes: [...walk.notes, added] }, reply: `Note ${id} added.` }
173  }
174  if (action !== 'clear' && action !== 'reopen') return { refusal: '`action` is add, clear or reopen.' }
175  const id = whole(args.id)
176  if (id === null || !walk.notes.some(n => n.id === id)) return { refusal: `There is no note ${String(args.id)}.` }
177  const isCleared = action === 'clear'
178  return {
179    walk: { ...walk, notes: walk.notes.map(n => (n.id === id ? { ...n, isCleared } : n)) },
180    reply: `Note ${id} ${isCleared ? 'cleared' : 'reopened'}.`,
181  }
182}
183
184export function finish(walk: Walk | null): Step {
185  if (walk === null) return { refusal: 'No walkthrough is running.' }
186  const open = walk.notes.filter(n => !n.isCleared).length
187  return {
188    walk: { ...walk, current: null, hunks: [], isDone: true },
189    reply: `Walkthrough marked done; ${open} open note${open === 1 ? '' : 's'} left on the panel.`,
190  }
191}
192
193export const where = (n: Note): string | null =>
194  n.file === null ? null : n.line === null ? n.file : `${n.file}:${n.line}`
195
196export const clip = (s: string, room: number): string => (s.length <= room ? s : `${s.slice(0, Math.max(1, room - 1))}…`)
197
198export const plain = (s: string): string => s.replace(/\*\*([^*]+)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1')
199
200export function readMap(raw: unknown): PrMap | string {
201  const d = (raw ?? {}) as Args
202  const list = (v: unknown): Args[] => (Array.isArray(v) ? (v as Args[]) : [])
203  const columns = list(d.columns).map(c => ({ id: text(c.id) ?? '', label: text(c.label) ?? '' }))
204  const nodes: MapNode[] = list(d.nodes).map(n => ({
205    id: text(n.id) ?? '',
206    title: text(n.title) ?? '',
207    file: text(n.file),
208    column: text(n.column) ?? '',
209    status: oneOf(MAP_STATUSES, n.status) ?? 'path',
210    note: text(n.note),
211    before: text(n.before),
212    after: text(n.after),
213  }))
214  const edges = list(d.edges).map(e => ({
215    from: text(e.from) ?? '',
216    to: text(e.to) ?? '',
217    label: text(e.label),
218    before: oneOf(EDGE_STATES, e.before) ?? 'normal',
219    after: oneOf(EDGE_STATES, e.after) ?? (e.changed === true ? 'changed' : 'normal'),
220  }))
221  const steps: MapStep[] = list(d.steps).map(s => ({
222    title: text(s.title) ?? '',
223    nodes: strings(s.nodes),
224    text: text(s.text),
225    before: text(s.before),
226    after: text(s.after),
227  }))
228  if (columns.length === 0 || nodes.length === 0 || steps.length === 0)
229    return 'it has no columns, nodes or steps. Pass the JSON file the map job built.'
230  return { columns, nodes, edges, steps }
231}
232
233export function slice(map: PrMap, steps: number[]): Slice | null {
234  const chosen = steps.flatMap(n => (map.steps[n - 1] === undefined ? [] : [{ ...map.steps[n - 1]!, n }]))
235  if (chosen.length === 0) return null
236  const byId = new Map(map.nodes.map(n => [n.id, n]))
237  const ids = new Set(chosen.flatMap(s => s.nodes).filter(id => byId.has(id)))
238  return {
239    columns: map.columns
240      .map(c => ({ label: c.label, nodes: map.nodes.filter(n => n.column === c.id && ids.has(n.id)) }))
241      .filter(c => c.nodes.length > 0),
242    edges: map.edges
243      .filter(e => ids.has(e.from) && ids.has(e.to))
244      .map(e => ({ ...e, fromTitle: byId.get(e.from)!.title, toTitle: byId.get(e.to)!.title })),
245    steps: chosen,
246  }
247}
248
types/index.d.ts 81 lines
1export type StopKind = 'changed' | 'new' | 'removed' | 'unchanged'
2
3export type Stop = { title: string; kind: StopKind; files: string[]; steps: number[]; hunks: Hunk[] }
4
5export type MapStatus = 'changed' | 'new' | 'removed' | 'path' | 'outside' | 'test' | 'doc'
6
7export type EdgeState = 'normal' | 'changed' | 'blocked' | 'ghost' | 'absent'
8
9export type MapNode = {
10  id: string
11  title: string
12  file: string | null
13  column: string
14  status: MapStatus
15  note: string | null
16  before: string | null
17  after: string | null
18}
19
20export type MapEdge = { from: string; to: string; label: string | null; before: EdgeState; after: EdgeState }
21
22export type MapStep = {
23  title: string
24  nodes: string[]
25  text: string | null
26  before: string | null
27  after: string | null
28}
29
30export type PrMap = {
31  columns: { id: string; label: string }[]
32  nodes: MapNode[]
33  edges: MapEdge[]
34  steps: MapStep[]
35}
36
37export type Slice = {
38  columns: { label: string; nodes: MapNode[] }[]
39  edges: (MapEdge & { fromTitle: string; toTitle: string })[]
40  steps: (MapStep & { n: number })[]
41}
42
43export type NoteKind = 'likely' | 'check'
44
45export type Note = {
46  id: number
47  kind: NoteKind
48  text: string
49  file: string | null
50  line: number | null
51  stop: number | null
52  isCleared: boolean
53}
54
55export type Hunk = { source: string; path: string | null }
56
57export type Term = { term: string; meaning: string }
58
59export type View = { stop: number; hunks: Hunk[] }
60
61export type Walk = {
62  pr: { number: number; title: string; url: string | null }
63  summary: string | null
64  background: string | null
65  glossary: Term[]
66  stops: Stop[]
67  current: number | null
68  seen: number[]
69  hunks: Hunk[]
70  notes: Note[]
71  isDone: boolean
72  map: PrMap | null
73  views: Record<string, View>
74}
75
76declare module 'claude-code' {
77  interface PluginState {
78    'pr-assistant': { walk: Walk | null; isPanelShut: boolean }
79  }
80}
81