While /thegraph runs: one line above the prompt with its steps in order, each marked, and the signals that fired, and a button that opens a pane with a gantt…

Personal collection of Claude Code and Codex skills.
Each top-level folder containing a SKILL.md is one skill. This repo is the single source of truth; skills become active by linking them into each agent's skill directory, where Claude Code and Codex discover them.
| Skill | What it does |
|---|---|
thegraph-codex | Codex-native, explicitly invoked version of thegraph's end-to-end discipline: establish the task from repository guidance and primary sources, make routine implementation decisions autonomously, ask only for consequential product or scope decisions, prove behavioural tests can fail, then run verification proportionate to the changed surface. It does not require Claude Code platform skills or create external tracker records without an explicit request. |
to-html | Convert a markdown file — or content already in the conversation — into a single self-contained, styled HTML file: inline CSS, sticky table of contents, callouts, premium layout blocks. No build step. |
brief | Explain the work in flight to the person who has to decide about it — state, the next action, what it changes and what it leaves alone, and what they must decide (including "nothing", which is information). Publishes a one-screen Artifact with its own briefing layout; falls back to chat when there is no structure worth laying out. Status claims are queried with gh/git rather than copied out of the conversation, and measured facts are marked apart from inferred ones. Vocabulary is governed by a structural check — every noun must point at something the user can see or do — not by a banned-word list, because the words that lose someone next are never the ones already on the list. A view, never a source: nothing may exist only in a briefing. Invoked only (/brief, /brief <issue>, /brief session) — judging whether someone understands you is not yours to do. |
gate | The Acceptance Gate — review an AFK agent's finished work on an issue, render a verdict (Pass / Rework / Respec / Escalate) with the matching next action, and run it on the tracker once you approve. Delegates the diff review to the code-review skill. |
to-deck | Retired — no longer installed; moved to retired/, see ADR-0059 and ADR-0027. Turned a study PDF into a reusable JSON question bank through an interactive Korean Q&A session: keeps the workbook's own questions in order (origin: workbook) and adds generated extras (origin: extra) — a mix of explanatory and single-term recall questions — each a plain {question, answer} pair. Offers a one-at-a-time session or batch extraction; no question-type labels — a downstream tool classifies them. |
grill-code | Retired — no longer installed; moved to retired/, see ADR-0058 and ADR-0027. Grilled code along one chosen mode — security, common-component extraction, refactoring, performance, or learning — scanning the scope relentlessly. Defect modes score each finding on severity + effort and rank them by priority (P0–P3); the non-defect learning mode explains AI-written code as Lessons ranked by Value. Report only; standalone (no dependency on code-review/audit). Can save the report as HTML via to-html. |
img-to-pdf | Combine a folder of images (or an explicit file list) into one PDF, one image per page, in natural-sort order (2.jpg before 10.jpg). Default: a searchable PDF — the page image plus an invisible, selectable/searchable text layer via macOS Vision OCR (Korean + English). --image-only instead embeds JPEG/PNG losslessly with no text layer (HEIC/HEIF/WEBP pre-converted via sips; img2pdf auto-installed into a cached venv). OCR mode is macOS-only; the Swift helper compiles once and caches. |
theflow | Retired — no longer installed; moved to retired/, see ADR-0027. The seven-step working discipline for a substantive change to a boundary-defined codebase, succeeded by thegraph which carries every rule it held (ADR-0019). Kept readable because the docs/agents/theflow.md bindings it read still exist in the repos it onboarded — nothing reads them now, grill-the-graph's path for compiling one having gone with ADR-0067. |
grill-the-flow | Retired — no longer installed; moved to retired/, see ADR-0027. The setup half of theflow — it interrogated a maintainer to author the repo's docs/agents/theflow.md bindings. Succeeded by grill-the-graph, which asks a much smaller question and writes a much smaller file. Nothing reads the bindings docs it wrote, that path having gone with ADR-0067. |
read-it | Read the situation before touching anything, and come back with a route. The first act of a change and the only one whose mistakes nothing downstream catches — a wrong proof method fails at the proof and a wrong placement fails at the diff, while a wrong reading of the issue passes everything, a run that solves the wrong problem well having still solved something well. Four reads, three of them conditional on something you check rather than weigh: the build (short, and answering little on purpose); the cluster, where one tracker query finds a parent (spine — the anchor's root is a hypothesis to test); the territory map where the repo keeps one; and always the real sources plus the hidden state (firsthand, one reflex rather than two — the source list widens what you read, it never decides whether you read, and with no outside source named you still enumerate the hidden state of the code you are touching). Doing one of the four and doing all four are both ordinary; what is not is skipping one and being unable to say why. Then restates the issue in its own words and stops to ask — the only guaranteed stop, since every later one is conditional and a run where nothing goes wrong first reaches a person with the work already done and nowhere to have redirected it. Returns a route label, never a skill name, so what runs next stays the caller's to decide. Everything it finds is a candidate; nothing reaches a tracker unasked. |
make-it | Write the change. Calls tdd for the tests and redden after every one of them — a green from a test nobody watched fail is not evidence, which is the one thing tdd does not do. Keeps the narrow exception where compilation itself enforces completeness and a round-trip test replaces strict RED, and the rhythm a whole-suite-at-the-end habit loses: typecheck and the nearby tests often, everything once at the end. Prose changes walk it too, with the test section conditional. Carries the rule that a comment says what the code is, and follows the repo's CLAUDE.md for where the rest goes rather than holding its own copy — comments are written on every edit, and most edits never pass through make-it. Its substance is the four signals that only appear while your hands are in the code, since you cannot schedule the moment you will feel one: "this is a bit odd, I'll just fix it up here" — the tell that the problem is one step further in, tempting because it works and costs nothing visible, until the day somebody fixes the real thing and every patch like it becomes silently wrong; a new file with no obvious home; writing against an outside reference; and a call that is the maintainer's. What you notice and do not fix is carried, never filed. |
check-it | Measure a finished change before anyone calls it done — the hand that shaped a thing is the worst judge of whether it is finished. Eight checks, ordered by cost rather than ceremony, each conditional: the gates bare (bare), whether new or moved files landed where the layout rule said, proof against something real rather than a fake, the diff read for shape (assay), for cost (silt) and for exposure (security-review) at the same time, the whole corpus read for what is missing (lens), and the surfaces that describe the behaviour (sweep). A prose change runs the last two and nothing else. One question runs through all of it — a red, a defect, a defensive line: is it mine? Answered by re-running against the tree without this change and comparing the failure, never the exit code, since a baseline red for its own reason makes every red compare 1 to 1 and inverts the attribution silently. And one shape is hunted assuming the writer left no help at all, because whoever did not notice could not have written it down: for each defensive line, what would have to be true for this to be unnecessary? — if the answer names something you did not change, that is where it belongs. Fixes nothing; measures, attributes, hands on. |
pub-ready | Bring a Dart or Flutter package to the point where only pub publish is left — the maintainer's release bar, held once instead of in each package's CLAUDE.md, where it had been copied into at least seven packages and drifted (ADR-0086). Reads what pub.dev already has first, raw from its API, since that settles whether the version is new, which CHANGELOG entries are frozen and what changed since the last release. Then pubspec (version size against the diff, the 0.x caret trap, the SDK floor, fields checked by pana itself rather than a copied limit), CHANGELOG (an entry per behaviour change, a published one never rewritten), README (every API name it shows grepped in lib/), the CI steps plus the gates CI does not reach — pub get before dart format, the example, the dry-run at 0 warnings on a clean tree with its file list read — all run bare. Never publishes: it ends with the command written out for the maintainer. A package's own guidance adds to it and, where they differ, wins. Runs only when a release is being prepared, in a repo that chose it: grill-the-graph asks, recommending it for an open-source package, and records pub-ready or None. in the build, which this reads first. |
decant | Sort source comments paragraph by paragraph under one policy: a comment says what the code is, and the why, the trap, the measured value and the history move to the repo's map. Six bins; the unit is the paragraph; the drop question is asked last, because a wrong move costs a lookup and a wrong drop costs a measurement. Checks every DESIGN against the code and then its note, and reports what the map is missing (notes owed) and where note and comment give different reasons (two grounds). Runs on a whole repository, territory by territory in an order derived by counting, when a maintainer asks — never per change, because a check after the fact is undone by the next edit made outside it; the write-time rule lives in the repo's CLAUDE.md. Reports and stops — unless the maintainer hands it the writes, and then it moves sentences rather than rewriting them, accounts for every one, and re-points whatever quoted them. The measurements behind it are ADR-0076. In a repository you contribute to, upstream's guidance and closest merged PR replace that policy, and only the comments the branch adds or changes are read (ADR-0079). |
winnow | Cut an always-loaded agent document — CLAUDE.md, AGENTS.md, a skill body — down to what every run needs. Five bins per paragraph: rule stays, detail moves behind a pointer that names its trigger, number stays only where a decision turns on it, roster becomes the command that derives it, history leaves for version control. History is asked last, and an incident story has its rule extracted before the story goes. Shows the table — every history part quoted, not counted — and stops for the maintainer; on approval writes, then proves every rule still has a home by reading the original from version control, and repoints references to moved sections. The case it was cut from is ADR-0077. |
assay | Test what a change is made of, along two axes kept apart because a change can pass one and fail the other: does the code hold up, and does it do what was asked. The first carries this repo's own documented standards — which always outrank it — plus Fowler's twelve code smells as labelled heuristics, never hard violations, covering cohesion (Divergent Change), coupling (Feature Envy, Shotgun Surgery, Message Chains) and duplication (Duplicated Code, Data Clumps, Primitive Obsession); and it opens the module the change landed in, since "edited for several unrelated reasons" is a claim about a module and a diff shows one slice of it. The second asks what the issue wanted and got, what it wanted and did not, and what arrived that nobody asked for. Findings are graded violation / judgement / already-decided — the third is why the records get read, since a finding that contradicts a recorded decision re-opens a call somebody made. Never merged, never ranked across axes, one closing line per axis. |
silt | Read a change for what will make it slow, and refuse to call anything a defect without a number. Silt is what a river drops: nothing dramatic, nothing wrong on any given day, and one season later the channel is shallow — which is the shape of the performance defects that actually cost, since the ones that announce themselves get found. Carries seven shapes with, for each, the cheapest way to find out whether it is real here: registered and never released, a container that only grows, I/O inside a loop, a large structure copied by value, recomputed every time, blocking the thread that must not block, a lookup with nothing to make it fast. A suspicion arrives with the way to settle it or it does not go out at all — that bar is what stops this becoming a list of things that make somebody uneasy. And a number with nothing beside it is not a number: measure the same thing on the tree without the change. Proposes no optimisation, does not widen, and does not accept "it's fine, it's small" — if it is small the measurement is cheap. |
ask-it | Put everything that has been carried in front of a person, once, and file only what they keep — the one door, since nothing may evaporate into a pull-request body or a code comment, where it is buried on merge. envelope owns the collecting and the seven columns; what this adds is that the items arrive from different places with dispositions that share no vocabulary — something to file, something to decide, something belonging to another repository, something a release will oblige — and interleaved, the reader classifies before answering, which is the sorting that presenting one at a time was bought to remove. byartifact searches before anything is opened, and only for items actually being filed. A follow-up is parented through the tracker's own relation in the same act as filing it, and whether it also joins the cluster is a separate judgement: provenance and root are different claims, and the error is not symmetric — missing a sibling costs a reconstruction, counting an adjacent one corrupts the roster that somebody later copies almost verbatim. A release's obligations are the consumer tests that actually broke, named; a purely additive release obliges nothing, and that is an answer worth writing. |
thegraph | Take one change from an issue to done, in a codebase whose identity is a boundary — a core that stays correct by not absorbing the concerns of the things that consume it. Four skills in order — read-it → make-it → check-it → ask-it — with one guaranteed stop before any of them run: the reading of the issue, confirmed by the person who holds it, since a change where no signal fires otherwise reaches a person for the first time at the very end, with the work done and nowhere to have redirected it. Two routes after that, and the one that gets missed is expensive: an issue asking for a choice gets the adversarial read over the options before any proposal, or the enumeration lands after approval and its costs get demoted into follow-ups. Everything else is a signal you cannot schedule — the urge to patch around something one step further in, a test just written, an outside reference about to be relied on, a call that is the maintainer's — acted on where it arrives rather than noted for later. What holds throughout: nothing reaches a tracker unasked; what can be counted is counted; a derivation falls to a better derivation and a judgement falls only to the person who made it, so a record that does not say which it holds reads as the first. Human-invoked (/thegraph). |
grill-the-graph | The setup half of thegraph. Writes one short prose file, docs/agents/thegraph.md, holding what a person already knows and no file in the repo answers — which is very nearly just the real sources the project is built against, each marked how it works or where files go, raw or summarized, an example to follow or a spec that binds. A line earns its place only by clearing three conditions together: no file here answers it, a person already knows it, and something reads it. The second is the one that used to be missing — "only a person could decide it" and "a person already knows it" are different sets, and everything this skill once asked for (sacred paths, the tie-breaker, the seams, a proof method per layer) cleared the first and failed the second, so the answers came back drafted by the builder and ratified by someone who could not have produced them. Generates no scripts and no agents, carries no build stamp, and copies nothing the repo already states; the build grows as runs ask for what it lacks. Run again, it updates: where docs/agents/thegraph.md exists it keeps the build, asks nothing already answered, and brings what it installed — the comment rule, the map hub, the attribution pieces — and the lines pointing at them up to its current text; /grill-the-graph init rebuilds from scratch instead, written only on the maintainer's approval (ADR-0085). An older generated build — scripts/thegraph/, .claude/agents/thegraph-* — is handed to salvage rather than read or updated. A project built against nothing outside itself yet answers none yet, and the file records that the question was put rather than inventing a row. Where the repo has no territory map, it makes the map's folder with a one-line hub instead of building one — the rule needs a destination on disk, and an empty map is a young repo's honest state; notes arrive as edits need them or all at once through grill-map. Then it writes the comment rule into the repo's CLAUDE.md: a comment says what the code is, with the rest sent to the map, the decision records or the commit message, naming only destinations that exist on disk. That is the one place the rule is written, because comments are written on every edit and a pass that checks them afterwards is undone by the next one. In a repository you contribute to rather than own — named by the argument (/grill-the-graph local, or own for your own), and asked first when there is none, with viewerPermission on the receiving repository as the recommendation — it commits nothing: the same file and a rule deferring to upstream's own guidance go in untracked, excluded files, no map is made, and a hook blocks Claude attribution on the way out (ADR-0079). In your own repository attribution stays unless you turn it off when asked, and off installs the same check, locally. In your own repository holding a Dart package for pub.dev, it asks whether pub-ready is the release bar — recommending it when the package is open source — records the answer, and on a yes offers to replace each older copy of the bar with a pointer, keeping what only that package has (ADR-0086). |
salvage | Clear an older grill-the-graph build out of a repo without losing the answers a person gave it. The whole job is telling two things apart: what somebody sat down and answered, which has to survive, and what was copied out of the repository, which is why that build went. Finds what is ours by the build stamp every generated file carries and by the build document's own manifest, and reads both — a stamped file the manifest does not name is the case that matters, the manifest being a copy like any other. Four rings: ours (build doc, generated agents and scripts, the ignore line, and the run-state cache version control never shows you); somebody else's file pointing at ours, where only the line comes out — a repo left with a hook invoking a deleted script cannot commit, so clearing the first ring and reporting the second is a break with a note attached; produced by our rules but not written by us, shown and asked, and any generated file a later commit touched, because that made it theirs; and outside, untouched — decision records describe the world when they were written, broken links included. Lifts the reference list into the short file the current skill defines, drops the rest with a reason each, and re-reads the tree afterwards, since a cleanup reporting success without looking again has checked nothing. |
tickets | Retired — no longer installed; moved to retired/, see ADR-0069 and ADR-0027. Put back what slicing dropped — the third producer in the thegraph family. A general slicer keeps a ticket thin because it cannot know who will execute it; here the executor was known, so the calls a maintainer had already made travelled with the ticket instead of staying behind in the spec. Ran right after the tickets were cut, in the same unbroken window as the grilling: transcribed the settled calls into each ticket, enrolled the parent as the relation the tracker actually renders (which is still why spine's roster is a query and not a body parse), and marked each entry human / derived / unknown. It read thegraph's "What the issue must supply" at runtime rather than hardcoding it, and that is the one thing it demonstrably bought: the schema went from five slots to six and the producer needed zero edits. Retired on the maintainer's call, with the falsification ADR-0045 had written in advance already fired — on the only run anyone measured, every contract entry was marked derived, which licenses nothing. The schema it filled is live; thegraph reads a contract wherever one is written, and a ticket that answers none of it was always the ordinary case. |
| spine | Read the cluster before the ticket, extracted from
hooks/register.tsx 577 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import {
5 closesIssue,
6 focusOf,
7 isClosedStatus,
8 isDone,
9 issueOf,
10 onIssueClosed,
11 isSheetPath,
12 labelOf,
13 minutes,
14 onAnswer,
15 onDismiss,
16 onEdit,
17 onSkill,
18 onTurnEnd,
19 parseSheet,
20 STEP_COLOR,
21 gantt,
22 stepAt,
23 trail,
24 turnSummary,
25 addLog,
26 bandName,
27 runName,
28 sheetLog,
29 testCounts,
30 testOf,
31 baseName,
32 sheetLine,
33 sheetPathFor,
34 routeName,
35 startRun,
36 stepLabel,
37 stepsOf,
38} from './run'
39
40const run = atom({ plugin: 'thegraph-panel', key: 'run' } as const, null)
41const isPaneOpen = atom({ plugin: 'thegraph-panel', key: 'isPaneOpen' } as const, false)
42const now = atom({ plugin: 'thegraph-panel', key: 'now' } as const, 0)
43const turnLines = atom({ plugin: 'thegraph-panel', key: 'turnLines' } as const, {})
44
45const PANE = 'thegraph'
46/** Blank cells at the line's left and right, as usage-band keeps, so both share their edges. */
47const LEFT = 2
48const RIGHT = 1
49/** A running step's minutes redraw this often while nothing else happens. */
50const TICK_MS = 30_000
51
52/** Cells for a step's name: before its gantt bar, and in the log's step column. */
53const STEP_CELLS = 10
54
55/** Turn lines kept, the oldest dropped first. */
56const TURN_LINES_MAX = 200
57
58// When the last main-thread turn ended: a turn's summary counts what the log gained since.
59let lastTurnEnd = 0
60
61// What followed /thegraph on the prompt, waiting for the skill to expand. Lost on a reload: the run starts unlabelled.
62let pendingLabel: string | null = null
63
64// The session's folder, whose name heads each sheet's file name; and the OS temp folder, asked once.
65let cwd: string | null = null
66let tempDir: string | null | undefined
67// The sheet's modification time when it was last read, so an unchanged sheet is not read again.
68let sheetSeen = -1
69
70/** gh is asked whether the run's GitHub issue is closed at most this often. */
71const GH_EVERY_MS = 5 * 60_000
72// The issue file's modification time when last read, and whether it was ever there: a path
73// never seen is a mistyped one, not an archived issue. When gh was last asked.
74let issueSeen = -1
75let isIssueFound = false
76let ghAskedAt: number | null = null
77
78// A new run watches its own sheet and issue from scratch.
79const forgetWatch = () => {
80 sheetSeen = -1
81 issueSeen = -1
82 isIssueFound = false
83 ghAskedAt = null
84}
85
86const closeByIssue = async ($: EngineInterface) => {
87 const t = await $.clock.now()
88 await update($, run, r => (r === null ? r : onIssueClosed(r, t)))
89 await update($, now, () => t)
90}
91
92// A local issue file marked done, or gone once seen (archived, moved): the run's issue is closed.
93const checkIssueFile = async ($: EngineInterface) => {
94 const r = await read($, run)
95 const issue = r === null || r.doneAt !== null ? null : issueOf(r.sheet?.source, cwd)
96 if (issue?.kind !== 'file') return
97 let mtime: number
98 try {
99 mtime = (await $.fs.stat(issue.path)).mtimeMs
100 } catch {
101 if (isIssueFound) await closeByIssue($)
102 return
103 }
104 isIssueFound = true
105 if (mtime === issueSeen) return
106 issueSeen = mtime
107 let text: string
108 try {
109 text = await $.fs.read(issue.path)
110 } catch {
111 return
112 }
113 if (isClosedStatus(text)) await closeByIssue($)
114}
115
116// A GitHub issue closed anywhere (the web, a merged PR): gh is asked, now and then.
117const checkIssueGh = async ($: EngineInterface) => {
118 const r = await read($, run)
119 const issue = r === null || r.doneAt !== null ? null : issueOf(r.sheet?.source, cwd)
120 if (issue?.kind !== 'github') return
121 const t = await $.clock.now()
122 if (ghAskedAt !== null && t - ghAskedAt < GH_EVERY_MS) return
123 ghAskedAt = t
124 const argv = ['gh', 'issue', 'view', String(issue.number), ...(issue.repo === null ? [] : ['-R', issue.repo]), '--json', 'state', '--jq', '.state']
125 try {
126 const out = await $.process.run(argv, { timeoutMs: 10_000 })
127 if (out.exitCode === 0 && out.stdout.trim() === 'CLOSED') await closeByIssue($)
128 } catch {
129 // No gh here, or no network: the next ask may answer.
130 }
131}
132
133// No shell runs the argv: cmd answers on Windows, sh elsewhere.
134const TEMP_ASKS: readonly (readonly string[])[] = [
135 ['cmd', '/c', 'echo %TEMP%'],
136 ['sh', '-c', 'printf %s "${TMPDIR:-/tmp}"'],
137]
138
139const askTempDir = async ($: EngineInterface): Promise<string | null> => {
140 if (tempDir !== undefined) return tempDir
141 tempDir = null
142 for (const argv of TEMP_ASKS) {
143 try {
144 const r = await $.process.run(argv, { timeoutMs: 5_000 })
145 const dir = r.stdout.trim()
146 if (r.exitCode === 0 && dir !== '' && !dir.includes('%')) {
147 tempDir = dir
148 break
149 }
150 } catch {
151 // This one cannot start here; ask the next.
152 }
153 }
154 return tempDir
155}
156
157// Reads the sheet again when its file has changed since the last read.
158const checkSheet = async ($: EngineInterface) => {
159 const path = (await read($, run))?.sheetPath
160 if (path == null) return
161 let mtime: number
162 try {
163 mtime = (await $.fs.stat(path)).mtimeMs
164 } catch {
165 return
166 }
167 if (mtime === sheetSeen) return
168 sheetSeen = mtime
169 await readSheet($, path)
170}
171
172const tick = async ($: EngineInterface) => {
173 const r = await read($, run)
174 if (r !== null && r.doneAt === null) {
175 const t = await $.clock.now()
176 await update($, now, () => t)
177 // A write the tool hooks did not see (another process, a missed call) still shows within a tick.
178 await checkSheet($)
179 await checkIssueFile($)
180 await checkIssueGh($)
181 }
182}
183
184// This plugin's own ui.close hook does not run under its own call, so the flag is cleared here.
185const closePane = async ($: EngineInterface) => {
186 if (await read($, isPaneOpen)) {
187 await $.ui.close({ id: PANE })
188 await update($, isPaneOpen, () => false)
189 }
190}
191
192// Closes the pane whatever this plugin remembers: after /clear its state is gone and the pane is not.
193const shutPane = async ($: EngineInterface) => {
194 try {
195 await $.ui.close({ id: PANE })
196 } catch {
197 // Not open; nothing to close.
198 }
199 await update($, isPaneOpen, () => false)
200}
201
202// A pane open with no run behind it, as /clear or /resume leaves one, is closed.
203const shutOrphanPane = async ($: EngineInterface) => {
204 if ((await read($, run)) !== null) return
205 let isOpen = false
206 try {
207 isOpen = (await $.ui.panes()).some(p => p.id === PANE)
208 } catch {
209 return
210 }
211 if (isOpen) await shutPane($)
212}
213
214const togglePane = async ($: EngineInterface) => {
215 if (await read($, isPaneOpen)) {
216 await closePane($)
217 return
218 }
219 const opened = await $.ui.open({ id: PANE, title: 'thegraph', closeOnEscape: true })
220 await update($, isPaneOpen, () => true)
221 try {
222 await $.ui.scroll({ in: PANE, to: 'end' })
223 } catch {
224 // Nothing drawn yet to scroll; the pane opens at its top.
225 }
226 if (!opened.isPlaced) $.ui.toast(`thegraph: the pane waits (${opened.reason})`)
227}
228
229// A field of a tool's result, which reaches this module untyped.
230const field = (value: unknown, key: string): unknown =>
231 value !== null && typeof value === 'object' && key in value ? (value as Record<string, unknown>)[key] : undefined
232const resultOf = (result: object): unknown => ('result' in result ? result.result : undefined)
233
234// Reads the run sheet as the model left it; one that cannot be read leaves what was there.
235const readSheet = async ($: EngineInterface, path: string) => {
236 let text: string
237 try {
238 text = await $.fs.read(path)
239 } catch {
240 return
241 }
242 const sheet = parseSheet(path, text)
243 const t = await $.clock.now()
244 await update($, run, r => (r === null ? r : sheetLog(r.sheet, sheet, t).reduce(addLog, { ...r, sheet })))
245}
246
247// The person gave the run up: the line goes, and the pane with it.
248const dismiss = async ($: EngineInterface) => {
249 await closePane($)
250 await update($, run, () => null)
251}
252
253export const register: Register = on => {
254 on('session.start', async ($, e, next) => {
255 cwd = e.cwd
256 const result = await next(e)
257 $.clock.every(TICK_MS, () => void tick($))
258 return result
259 })
260
261 on('prompt.submit', async ($, e, next) => {
262 // The person's own words, typed here or through Remote Control; not a notification or another plugin's.
263 if (e.origin.kind === 'composer' || e.origin.kind === 'bridge') {
264 const label = labelOf(e.text)
265 if (label !== null) {
266 // The new run starts here, whatever the first left: its skill restarts it, named, if it expands.
267 pendingLabel = label
268 const t = await $.clock.now()
269 await update($, run, () => startRun(label, t))
270 forgetWatch()
271 await update($, now, () => t)
272 } else {
273 pendingLabel = null
274 await shutOrphanPane($)
275 const t = await $.clock.now()
276 const before = await read($, run)
277 // A slash command (/reload-plugins, /context) answers nothing, though it does move on from a finished run.
278 const isCommand = e.text.trimStart().startsWith('/')
279 if (before !== null && (!isCommand || before.doneAt !== null)) {
280 const after = onAnswer(before, t)
281 await update($, run, () => after)
282 if (after === null) await closePane($)
283 }
284 }
285 }
286 return next(e)
287 }).catch(($, e, next) => next(e))
288
289 on('skill.prompt', async ($, e, next) => {
290 const t = await $.clock.now()
291 if (e.skill === 'thegraph') {
292 // Name this run's sheet now and tell the run, so the one file is known to be ours.
293 const temp = await askTempDir($)
294 const hex = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, '0')
295 const sheetPath = temp === null ? null : sheetPathFor(temp, baseName(cwd ?? '') || 'repo', t, hex)
296 await update($, run, () => ({ ...startRun(pendingLabel, t), sheetPath }))
297 pendingLabel = null
298 forgetWatch()
299 await update($, now, () => t)
300 const result = await next(e)
301 return sheetPath === null ? result : { ...result, text: result.text + sheetLine(sheetPath) }
302 }
303 if ((await read($, run)) !== null) {
304 await update($, run, r => (r === null ? r : onSkill(r, e.skill, t)))
305 }
306 await update($, now, () => t)
307 return next(e)
308 })
309
310 on('turn.complete', async ($, e, next) => {
311 const r = await read($, run)
312 if (e.agentId === undefined && !e.isAborted && r !== null) {
313 const t = await $.clock.now()
314 const since = Math.max(lastTurnEnd, r.startedAt)
315 const focus = focusOf(r)
316 const step = focus?.key ?? r.log.findLast(l => l.kind === 'step')?.text ?? null
317 const line = turnSummary(r.log, since, step)
318 const key = String(e.durationMs)
319 await update($, turnLines, lines => Object.fromEntries([...Object.entries(lines), [key, line]].slice(-TURN_LINES_MAX)))
320 lastTurnEnd = t
321 await update($, run, r2 => (r2 === null ? r2 : onTurnEnd(r2, t)))
322 await update($, now, () => t)
323 }
324 return next(e)
325 })
326
327 // While the run works, the spinner says where it is: `… · thegraph make-it 3/5 · ✎5`.
328 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
329 const r = await read($, run)
330 const focus = r === null ? null : focusOf(r)
331 if (r === null || focus === null) return next(e)
332 const total = stepsOf(r).length
333 const edits = r.log.filter(l => l.kind === 'edit' && l.at >= Math.max(lastTurnEnd, r.startedAt)).length
334 const tail = `… · thegraph ${stepLabel(focus.key, focus.state)} ${focus.index + 1}/${total}${edits > 0 ? ` · ✎${edits}` : ''}`
335 return next({ ...e, props: { ...e.props, suffix: tail } })
336 })
337
338 // A turn's closing line keeps what that turn did, beside the engine's own words.
339 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
340 const line = (await read($, turnLines))[String(e.props.durationMs)]
341 if (line === undefined) return next(e)
342 const { Box, Text } = $.ui.resolve(e)
343 const theirs = await next(e)
344 return (
345 <Box flexDirection="row">
346 {theirs}
347 <Text dimColor={false}>
348 {line.map(seg => (seg.color === null ? <Text dimColor>{seg.text}</Text> : <Text color={seg.color}>{seg.text}</Text>))}
349 </Text>
350 </Box>
351 )
352 })
353
354 // A question put to the person inside a turn: the confirm stop is often asked this way,
355 // and its reply is the answer no prompt would bring.
356 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
357 if (e.agentId !== undefined || (await read($, run)) === null) return next(e)
358 const asked = await $.clock.now()
359 const questions = e.questions.map(q => q.question)
360 await update($, run, r =>
361 r === null ? r : questions.reduce((acc, q) => addLog(acc, { at: asked, kind: 'ask', text: q, detail: null }), onTurnEnd(r, asked)),
362 )
363 const result = await next(e)
364 const t = await $.clock.now()
365 const answers = (field(resultOf(result), 'answers') ?? {}) as Record<string, string>
366 // Esc puts the box away with nothing answered, however the engine words it (a deny, an error,
367 // no answers): no answer at all, and the run is not taken as answered.
368 const isDismissed = !questions.some(q => answers[q] !== undefined)
369 await update($, run, r => {
370 if (r === null) return r
371 // Each question's line, newest first, gets its answer; one left unanswered says so.
372 const log = [...r.log]
373 for (const q of questions) {
374 const i = log.findLastIndex(l => l.kind === 'ask' && l.text === q && l.detail === null)
375 const entry = log[i]
376 if (entry) log[i] = { ...entry, detail: isDismissed ? 'dismissed' : (answers[q] ?? 'no answer') }
377 }
378 // A finished run is moved on from by a prompt, never by a question inside the turn.
379 return isDismissed ? onDismiss({ ...r, log }) : (onAnswer({ ...r, log }, t) ?? { ...r, log })
380 })
381 await update($, now, () => t)
382 return result
383 }).catch(($, e, next) => next(e))
384
385 // A write to the run sheet is the run's own account: read it back once written.
386 // Any other file edit right after the confirm is make-it begun without its skill.
387 on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit'] }, async ($, e, next) => {
388 if (e.agentId !== undefined || (await read($, run)) === null) return next(e)
389 const path = 'file_path' in e ? e.file_path : undefined
390 if (path !== undefined && isSheetPath(path)) {
391 // The run named its own sheet (no path was handed to it, or it kept an older one): follow it.
392 await update($, run, r => (r === null || r.sheetPath === path ? r : { ...r, sheetPath: path }))
393 sheetSeen = -1
394 return next(e)
395 }
396 const t = await $.clock.now()
397 await update($, run, r => (r === null ? r : onEdit(r, t)))
398 const result = await next(e)
399 if (path !== undefined && !('deny' in result && result.deny !== undefined)) {
400 const isNew = field(resultOf(result), 'type') === 'create'
401 const name = path.split(/[\\/]/).filter(Boolean).at(-1) ?? path
402 await update($, run, r => (r === null ? r : addLog(r, { at: t, kind: 'edit', text: name, detail: null, isOk: isNew })))
403 }
404 return result
405 }).catch(($, e, next) => next(e))
406
407 // A shell command that runs tests: its result goes in the log, with the counts it printed.
408 // One that closes the run's GitHub issue ends the run.
409 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
410 const r = e.agentId === undefined ? await read($, run) : null
411 const runner = testOf(e.command)
412 const issue = r === null ? null : issueOf(r.sheet?.source, cwd)
413 const isClose = issue?.kind === 'github' && closesIssue(e.command, issue.number)
414 if (r === null || (runner === null && !isClose)) return next(e)
415 const result = await next(e)
416 const t = await $.clock.now()
417 const done = resultOf(result)
418 const out = `${String(field(done, 'stdout') ?? '')}\n${String(field(done, 'stderr') ?? '')}`
419 const isOk = done !== undefined && !('isError' in result && result.isError === true) && field(done, 'interrupted') !== true
420 if (runner !== null) await update($, run, r2 => (r2 === null ? r2 : addLog(r2, { at: t, kind: 'test', text: runner, detail: testCounts(out), isOk })))
421 if (isClose && isOk) await closeByIssue($)
422 return result
423 }).catch(($, e, next) => next(e))
424
425 // Whatever tool wrote it (Bash, Write, a script), the sheet changes only under a tool call:
426 // look at its modification time once each main-thread call has run.
427 on('tool.call', async ($, e, next) => {
428 const result = await next(e)
429 if (e.agentId === undefined) {
430 await checkSheet($)
431 await checkIssueFile($)
432 }
433 return result
434 }).catch(($, e, next) => next(e))
435
436 // The person's close (its mark, ctrl+x x, Esc) as much as the button's.
437 on('ui.close', async ($, e, next) => {
438 if (e.id === PANE) await update($, isPaneOpen, () => false)
439 return next(e)
440 }).catch(($, e, next) => next(e))
441
442 // One line over whatever the other bands draw: the steps in order, each marked, the time in
443 // the one at hand, a failed last test and the signals; and at the right edge, lined up with
444 // the band's beneath, the pane's button and ×.
445 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
446 const below = await next(e)
447 const r = await read($, run)
448 if (r === null || e.props.hasSurvey) return below
449
450 const isOpen = await read($, isPaneOpen)
451 const { Box, Button, Text } = $.ui.resolve(e)
452 const t = Math.max(await read($, now), r.startedAt)
453 const segs = trail(r, t)
454 const name = runName(r)
455 const line = (
456 <Box flexDirection="row" justifyContent="space-between" paddingLeft={LEFT} paddingRight={RIGHT}>
457 <Text wrap="truncate-end">
458 <Text bold>thegraph</Text>
459 {name !== null && <Text dimColor>{` ${bandName(name)}`}</Text>}
460 <Text>{' '}</Text>
461 {segs.map(g => <Text color={g.color ?? undefined} bold={g.bold} dimColor={g.dim}>{g.text}</Text>)}
462 </Text>
463 <Box flexDirection="row" flexShrink={0}>
464 <Text>{' '}</Text>
465 <Button key="pane" variant="primary" hotkey="g" onPress={() => togglePane($)}>
466 {isOpen ? '▾ close pane' : '▸ pane'}
467 </Button>
468 <Text> </Text>
469 <Button key="dismiss" role="dismiss" hotkey="x" dimColor onPress={() => dismiss($)}>
470 ×
471 </Button>
472 {/* The main screen reports no clicks: name the keys that press them there (ctrl+x tab focuses the band). */}
473 {e.viewport?.isFullscreen === false && <Text dimColor> ^x⇥ g·x</Text>}
474 </Box>
475 </Box>
476 )
477 return (
478 <Box flexDirection="column">
479 {line}
480 {below}
481 </Box>
482 )
483 })
484
485 // The pane: a header, a gantt of the steps, then the log as a table, oldest first, opened at its end.
486 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
487 const { Box, Button, Text } = $.ui.resolve(e)
488 const r = await read($, run)
489 // The pane's own way out: the band's button goes with the run, and /clear takes the run.
490 const close = (
491 <Box flexDirection="row" flexShrink={0}>
492 <Text> </Text>
493 <Button key="close" role="dismiss" hotkey="q" dimColor onPress={() => shutPane($)}>
494 close
495 </Button>
496 {e.viewport?.isFullscreen === false && <Text dimColor> ^x x</Text>}
497 </Box>
498 )
499 if (r === null) {
500 return (
501 <Box flexDirection="row" justifyContent="space-between">
502 <Text dimColor>thegraph is not running.</Text>
503 {close}
504 </Box>
505 )
506 }
507 const t = Math.max(await read($, now), r.startedAt)
508 const route = r.sheet?.route ?? (r.route === null ? null : routeName(r.route))
509 const name = runName(r)
510 // The gantt: a row per step, the run's time across, filled wherever that step ran.
511 const end = Math.max(t, r.doneAt ?? 0)
512 const bars = gantt(r, end, Math.max(8, Math.min(48, e.props.bodyColumns - STEP_CELLS - 5))).map(g => (
513 <Text wrap="truncate-end">
514 <Text bold={g.state === 'run' || g.state === 'wait'} dimColor={g.state === 'todo'}>{g.key.padEnd(STEP_CELLS)}</Text>
515 {g.cells.map(c => (c ? <Text color={STEP_COLOR[g.key] ?? 'white'}>█</Text> : <Text dimColor>·</Text>))}
516 <Text dimColor>{` ${g.ms === null ? '–' : minutes(g.ms)}`.padStart(5)}</Text>
517 </Text>
518 ))
519 const lines = r.log.map((l, i) => {
520 const at = `+${String(Math.floor((l.at - r.startedAt) / 60_000)).padStart(2)}m `
521 const step = stepAt(r, l.at)
522 const prev = r.log[i - 1]
523 const isFirst = prev === undefined || stepAt(r, prev.at) !== step
524 return (
525 <Text wrap="wrap">
526 <Text dimColor>{at}</Text>
527 {isFirst && step !== null
528 ? <Text color={STEP_COLOR[step.split(' ')[0] ?? ''] ?? undefined}>{step.padEnd(STEP_CELLS + 1)}</Text>
529 : <Text dimColor>{(step === null ? '' : '│').padEnd(STEP_CELLS + 1)}</Text>}
530 {l.kind === 'step' && <Text bold>{`▸ ${l.text}`}</Text>}
531 {l.kind === 'ask' && (
532 <Text>
533 <Text color="warning">◆ </Text>
534 <Text>{l.text}</Text>
535 {l.detail === null ? <Text color="warning"> …waiting</Text> : <Text dimColor> → </Text>}
536 {l.detail !== null && <Text bold>{l.detail}</Text>}
537 </Text>
538 )}
539 {l.kind === 'edit' && <Text color="blue">{`${l.isOk ? '+' : '✎'} ${l.text}`}</Text>}
540 {l.kind === 'test' && (
541 <Text>
542 <Text color={l.isOk ? 'success' : 'error'}>{l.isOk ? '✓ ' : '✗ '}</Text>
543 <Text>{l.text}</Text>
544 {l.detail !== null && <Text dimColor>{` ${l.detail}`}</Text>}
545 </Text>
546 )}
547 {l.kind === 'signal' && <Text color="magenta">{`⚑ ${l.text}`}</Text>}
548 {l.kind === 'note' && <Text dimColor>{`→ ${l.text}`}</Text>}
549 {l.kind === 'carry' && <Text color="cyan">{`↗ ${l.text}`}</Text>}
550 {l.kind === 'end' && <Text bold color="success">{`✓ ${l.text}`}</Text>}
551 </Text>
552 )
553 })
554 return (
555 <Box flexDirection="column">
556 <Box flexDirection="row" justifyContent="space-between">
557 {/* Wraps rather than cuts: the pane is where a name the band cut is read whole. */}
558 <Text wrap="wrap">
559 <Text bold>thegraph</Text>
560 {name !== null && <Text dimColor>{` ${name}`}</Text>}
561 {route !== null && <Text color="cyan">{` · ${route}`}</Text>}
562 <Text dimColor>{` · ${minutes((r.doneAt ?? t) - r.startedAt)}`}</Text>
563 {isDone(r) && <Text color="success"> · done</Text>}
564 </Text>
565 {close}
566 </Box>
567 {r.sheet?.source != null && <Text dimColor wrap="wrap">{r.sheet.source}</Text>}
568 <Text dimColor>{'─'.repeat(Math.max(8, Math.min(40, e.props.bodyColumns)))}</Text>
569 {bars}
570 <Text> </Text>
571 <Text dimColor>{`time ${'step'.padEnd(STEP_CELLS + 1)}what`}</Text>
572 {lines.length === 0 ? <Text dimColor>Nothing logged yet.</Text> : lines}
573 </Box>
574 )
575 })
576}
577hooks/run.ts 400 lines1import type { LogEntry, Route, Run, Seg, Sheet, SheetStep, StepRec } from '../types'
2
3/** The stops where a person answers: after read-it, and after lens. */
4export const CONFIRM = 'confirm'
5export const DECIDE = 'decide'
6
7/** Skills that are steps of the order; anything else thegraph calls is ignored. */
8const STEP_SKILLS = ['read-it', 'lens', 'make-it', 'check-it', 'ask-it']
9
10/** Skills that interrupt the order whenever their moment comes. */
11export const SIGNAL_SKILLS = ['redden', 'firsthand', 'boundary']
12
13/** The steps a route walks; before the route is known, the build one. */
14export const plan = (route: Route | null): string[] =>
15 route === 'decision' ? ['read-it', CONFIRM, 'lens', DECIDE] : ['read-it', CONFIRM, 'make-it', 'check-it', 'ask-it']
16
17/** How the pane names a route: read-it says prose or code only in its text, which no event carries. */
18export const routeName = (route: Route): string => (route === 'decision' ? 'open decision' : 'prose/code')
19
20/** `/thegraph #42 band redraw` → `#42 band redraw`; null for a prompt that does not start one. */
21export const labelOf = (text: string): string | null => {
22 const m = /^\/thegraph(?![\w-])\s*(.*)$/s.exec(text.trim())
23 if (!m) return null
24 const rest = (m[1] ?? '').split('\n')[0]?.trim() ?? ''
25 return rest === '' ? '' : [...rest].slice(0, 40).join('')
26}
27
28export const startRun = (label: string | null, now: number): Run => ({
29 label: label === '' ? null : label,
30 startedAt: now,
31 route: null,
32 steps: [],
33 signals: [],
34 isWaiting: false,
35 isDismissed: false,
36 doneAt: null,
37 sheetPath: null,
38 sheet: null,
39 log: [],
40})
41
42/** The log keeps this many lines, the oldest dropped first. */
43const LOG_MAX = 300
44
45/** Adds a line to the log; a step already the last one begun is not logged again. */
46export const addLog = (run: Run, entry: LogEntry): Run => {
47 if (entry.kind === 'step' && run.log.findLast(l => l.kind === 'step')?.text === entry.text) return run
48 return { ...run, log: [...run.log, entry].slice(-LOG_MAX) }
49}
50
51const logged = (run: Run, at: number, kind: LogEntry['kind'], text: string): Run => addLog(run, { at, kind, text, detail: null })
52
53const openStep = (run: Run): StepRec | undefined => run.steps.find(s => s.endedAt === null)
54const closeAll = (steps: StepRec[], now: number) => steps.map(s => (s.endedAt === null ? { ...s, endedAt: now } : s))
55const begin = (run: Run, key: string, now: number): StepRec[] => [...closeAll(run.steps, now), { key, startedAt: now, endedAt: null }]
56
57/** Right after the confirm stop, nothing begun since: where thegraph picks its route. */
58const isAtRoute = (run: Run) => openStep(run) === undefined && run.steps.at(-1)?.key === CONFIRM
59
60/** A skill was expanded while the run is open. */
61export const onSkill = (run: Run, skill: string, now: number): Run => {
62 if (run.doneAt !== null) return run
63 if (SIGNAL_SKILLS.includes(skill)) return logged({ ...run, signals: [...run.signals, { skill, at: now }] }, now, 'signal', skill)
64 if (!STEP_SKILLS.includes(skill)) return run
65 if (skill === 'lens') {
66 // check-it runs lens on every change: only a lens at the route is the open-decision step.
67 if (run.route === 'decision' || (run.route === null && isAtRoute(run))) {
68 return logged({ ...run, route: 'decision', isWaiting: false, steps: begin(run, skill, now) }, now, 'step', skill)
69 }
70 return run
71 }
72 const route: Route | null = skill === 'read-it' ? run.route : (run.route ?? 'build')
73 return logged({ ...run, route, isWaiting: false, steps: begin(run, skill, now) }, now, 'step', skill)
74}
75
76/**
77 * The move passed to the person: a main-thread turn ended, or a question
78 * (AskUserQuestion) went up within one. Whatever runs now waits on them.
79 */
80export const onTurnEnd = (run: Run, now: number): Run => {
81 if (run.doneAt !== null) return run
82 const open = openStep(run)
83 if (open?.key === 'read-it') return logged({ ...run, isWaiting: true, steps: begin(run, CONFIRM, now) }, now, 'step', CONFIRM)
84 if (open?.key === 'lens') return logged({ ...run, isWaiting: true, steps: begin(run, DECIDE, now) }, now, 'step', DECIDE)
85 // Anything else, a trivial end after the confirm included, is the person's to say: the run waits, and × ends it.
86 return { ...run, isWaiting: true }
87}
88
89/**
90 * The person answered: a prompt of their own, or a question's reply. Null once a finished
91 * run has been moved on from, finished by its events or by its sheet checked off whole.
92 */
93export const onAnswer = (run: Run, now: number): Run | null => {
94 if (isDone(run)) return null
95 // After a question put away, the person's words take the step up again: no stop closes, nothing ends.
96 if (run.isDismissed) return { ...run, isWaiting: false, isDismissed: false }
97 if (!run.isWaiting) return run
98 const open = openStep(run)
99 if (open?.key === CONFIRM) return { ...run, isWaiting: false, steps: closeAll(run.steps, now) }
100 if (open?.key === DECIDE || open?.key === 'ask-it') {
101 return logged({ ...run, isWaiting: false, steps: closeAll(run.steps, now), doneAt: now }, now, 'end', 'done')
102 }
103 return { ...run, isWaiting: false }
104}
105
106/** The run's issue was closed, wherever the run had got to: that is its end. */
107export const onIssueClosed = (run: Run, now: number): Run =>
108 run.doneAt !== null ? run : logged({ ...run, isWaiting: false, steps: closeAll(run.steps, now), doneAt: now }, now, 'end', 'issue closed')
109
110/** A question box put away with nothing answered: the run still waits on the person, and is not answered. */
111export const onDismiss = (run: Run): Run => (run.doneAt !== null ? run : { ...run, isWaiting: true, isDismissed: true })
112
113/**
114 * A main-thread file edit. Right after the confirm, with nothing begun, it is
115 * make-it's work started without its skill being expanded: an inference, so it
116 * only ever opens make-it there, and never on the decision route.
117 */
118export const onEdit = (run: Run, now: number): Run =>
119 run.doneAt === null && run.route !== 'decision' && isAtRoute(run) ? onSkill(run, 'make-it', now) : run
120
121export type StepState = 'done' | 'run' | 'wait' | 'todo'
122
123/**
124 * Where one planned step stands: its latest record decides, unless a step before
125 * it in the plan began again since (check-it sending work back to make-it), which
126 * leaves it to do once more.
127 */
128export const stateOf = (run: Run, key: string): StepState => {
129 const rec = run.steps.findLast(s => s.key === key)
130 if (!rec) return 'todo'
131 const keys = plan(run.route)
132 const earlier = keys.slice(0, keys.indexOf(key))
133 if (run.steps.some(s => earlier.includes(s.key) && s.startedAt > rec.startedAt)) return 'todo'
134 if (rec.endedAt !== null) return 'done'
135 return run.isWaiting || key === CONFIRM || key === DECIDE ? 'wait' : 'run'
136}
137
138// --- the run sheet ---------------------------------------------------------------
139
140/** A run sheet's file name: `<repo>-<yyyymmdd>-<hhmm>-<8 hex>.md` in a `thegraph` folder. */
141const SHEET_PATH = /[\\/]thegraph[\\/][^\\/]+-\d{8}-\d{4}-[0-9a-f]{8}\.md$/i
142export const isSheetPath = (path: string): boolean => SHEET_PATH.test(path)
143
144/**
145 * The path a run's sheet gets: `<temp>/thegraph/<repo>-<yyyymmdd>-<hhmm>-<hex>.md`, in the
146 * temp folder's own separator, the time as the engine's clock reads it locally.
147 */
148export const sheetPathFor = (tempDir: string, repo: string, now: number, hex: string): string => {
149 const sep = tempDir.includes('\\') ? '\\' : '/'
150 const d = new Date(now)
151 const two = (n: number) => String(n).padStart(2, '0')
152 const stamp = `${d.getFullYear()}${two(d.getMonth() + 1)}${two(d.getDate())}-${two(d.getHours())}${two(d.getMinutes())}`
153 const name = repo.replace(/[^\w.-]+/g, '-') || 'repo'
154 return `${tempDir.replace(/[\\/]+$/, '')}${sep}thegraph${sep}${name}-${stamp}-${hex}.md`
155}
156
157/** The line added to thegraph's text so the run writes where this plugin watches. */
158export const sheetLine = (path: string): string => `\n\nThis run's run sheet: ${path}\n`
159
160/** The last part of a path, either separator. */
161export const baseName = (path: string): string => path.split(/[\\/]/).filter(Boolean).at(-1) ?? ''
162
163/** The sheet's keys for the two stops, drawn in the line's own words. */
164const SHEET_KEY: Record<string, string> = { confirm: CONFIRM, decide: DECIDE }
165const SHEET_MARK: Record<string, SheetStep['mark']> = { ' ': 'todo', '~': 'doing', x: 'done', X: 'done' }
166
167/** Reads a run sheet's text; lines it does not know are skipped. */
168export const parseSheet = (path: string, text: string): Sheet => {
169 const sheet: Sheet = { path, issue: null, source: null, route: null, steps: [], carried: [] }
170 let isCarried = false
171 for (const line of text.split(/\r?\n/)) {
172 const field = /^(issue|source|route):\s*(.*\S)\s*$/.exec(line)
173 const step = /^- \[([ ~xX])\]\s+(\S+)/.exec(line)
174 const note = /^\s+→\s*(.*\S)\s*$/.exec(line)
175 if (/^##\s/.test(line)) isCarried = /^##\s+Carried\b/i.test(line)
176 else if (isCarried && /^- /.test(line)) sheet.carried.push(line.slice(2).trim())
177 // A template placeholder (`<read-it's label ...>`) is no value yet.
178 else if (field?.[1] === 'issue') sheet.issue = (field[2] ?? '').startsWith('<') ? null : (field[2] ?? null)
179 else if (field?.[1] === 'route') sheet.route = (field[2] ?? '').startsWith('<') ? null : (field[2] ?? null)
180 else if (field?.[1] === 'source') sheet.source = (field[2] ?? '').startsWith('<') ? null : (field[2] ?? null)
181 else if (step) sheet.steps.push({ key: SHEET_KEY[step[2] ?? ''] ?? step[2] ?? '', mark: SHEET_MARK[step[1] ?? ' '] ?? 'todo', note: null })
182 else if (note) {
183 const last = sheet.steps[sheet.steps.length - 1]
184 if (last) last.note = note[1] ?? null
185 }
186 }
187 return sheet
188}
189
190/** The lines a newer reading of the sheet adds: steps begun, notes written, items carried, the end. */
191export const sheetLog = (before: Sheet | null, after: Sheet, at: number): LogEntry[] => {
192 const out: LogEntry[] = []
193 const was = new Map((before?.steps ?? []).map(s => [s.key, s]))
194 for (const step of after.steps) {
195 const old = was.get(step.key)
196 if (step.mark === 'doing' && old?.mark !== 'doing') out.push({ at, kind: 'step', text: step.key, detail: null })
197 if (step.note !== null && step.note !== old?.note) out.push({ at, kind: 'note', text: step.note, detail: null })
198 }
199 const carried = new Set(before?.carried ?? [])
200 for (const item of after.carried) if (!carried.has(item)) out.push({ at, kind: 'carry', text: item, detail: null })
201 const isEnd = (sheet: Sheet | null) => sheet !== null && sheet.steps.length > 0 && sheet.steps.every(s => s.mark === 'done')
202 if (isEnd(after) && !isEnd(before)) out.push({ at, kind: 'end', text: 'done', detail: null })
203 return out
204}
205
206// --- the run's issue -------------------------------------------------------------
207
208export type IssueRef = { kind: 'github'; repo: string | null; number: number } | { kind: 'file'; path: string }
209
210/**
211 * Where the sheet's `source:` says the issue lives: `owner/repo#42` or `#42` on GitHub,
212 * else a file, a relative path taken from the session's folder. Null when there is none.
213 */
214export const issueOf = (source: string | null | undefined, cwd: string | null): IssueRef | null => {
215 if (source == null || source === '') return null
216 const gh = /^(?:([\w.-]+\/[\w.-]+))?#(\d+)$/.exec(source)
217 if (gh) return { kind: 'github', repo: gh[1] ?? null, number: Number(gh[2]) }
218 if (/^(?:[a-z]:[\\/]|[\\/])/i.test(source)) return { kind: 'file', path: source }
219 if (cwd === null) return null
220 const sep = cwd.includes('\\') ? '\\' : '/'
221 return { kind: 'file', path: `${cwd.replace(/[\\/]+$/, '')}${sep}${source}` }
222}
223
224/** The band's cut of a run name: this many characters, then `…`. */
225const NAME_MAX = 40
226
227/**
228 * What the panel calls the run: once the sheet names an issue, its number (or its file's
229 * name) and the title after ` — `; the whole issue line when the sheet has no source;
230 * before any of that, the label. Null for a run with none of them.
231 */
232export const runName = (run: Run): string | null => {
233 const issue = run.sheet?.issue ?? null
234 const source = run.sheet?.source ?? null
235 if (issue === null) return run.label
236 if (source === null) return issue
237 const ref = issueOf(source, null)
238 const front = ref?.kind === 'github' ? `#${ref.number}` : baseName(source).replace(/\.[^.]+$/, '')
239 const at = issue.indexOf(' — ')
240 const title = at < 0 ? '' : issue.slice(at + 3).trim()
241 return title === '' ? front : `${front} ${title}`
242}
243
244/** A run name as the band draws it: cut on whole characters, `…` where it was cut. */
245export const bandName = (name: string): string => {
246 const chars = [...name]
247 return chars.length <= NAME_MAX ? name : `${chars.slice(0, NAME_MAX).join('')}…`
248}
249
250/** Whether a shell command closes issue `n` with gh: `gh issue close 42`, `#42`, or its URL. */
251export const closesIssue = (command: string, n: number): boolean =>
252 [...command.matchAll(/\bgh\s+issue\s+close\s+(?:\S*\/issues\/|#)?(\d+)\b/g)].some(m => Number(m[1]) === n)
253
254/** Whether an issue file's `Status:` line says it is finished. */
255export const isClosedStatus = (text: string): boolean => /^\s*Status:\s*(done|closed|resolved|archived|wontfix)\b/im.test(text)
256
257/** The test runner a shell command calls, by name; null for any other command. */
258const TEST_RUNNER = /\b(vitest|jest|pytest|cargo test|go test|bun test|deno test|(?:npm|pnpm|yarn)(?: run)? test|claude plugin test|check-mods|flutter test|dotnet test|gradle test|mvn test)\b/
259export const testOf = (command: string): string | null => TEST_RUNNER.exec(command)?.[1] ?? null
260
261/** `48 pass · 2 fail`, from what a runner printed; null when it printed neither count. */
262export const testCounts = (output: string): string | null => {
263 const pass = /(\d+)\s+pass(?:ed|ing)?\b/i.exec(output)?.[1]
264 const fail = /(\d+)\s+fail(?:ed|ing|ures?)?\b/i.exec(output)?.[1]
265 const parts = [pass === undefined ? null : `${pass} pass`, fail === undefined || fail === '0' ? null : `${fail} fail`].filter(p => p !== null)
266 return parts.length === 0 ? null : parts.join(' · ')
267}
268
269// --- the trail and the gantt -----------------------------------------------------------
270
271/** Each step's colour: its bar on the gantt, its name in a turn's closing line. */
272export const STEP_COLOR: Record<string, string> = {
273 'read-it': 'cyan', [CONFIRM]: 'warning', 'make-it': 'claude', 'check-it': 'success', 'ask-it': 'magenta', lens: 'blue', [DECIDE]: 'warning',
274}
275
276const TRAIL_MARK: Record<StepState, string> = { done: ' ✓', run: ' ◐', wait: ' ◆', todo: '' }
277const TRAIL_COLOR: Record<StepState, string | null> = { done: 'success', run: 'claude', wait: 'warning', todo: null }
278
279/**
280 * The band's line after the run's name: every step in order with its mark, `×2` on one
281 * begun twice, the time in the step at hand (or `done` and the whole run's), then the last
282 * test when it failed and the count of signals.
283 */
284export const trail = (run: Run, now: number): Seg[] => {
285 const segs: Seg[] = []
286 stepsOf(run).forEach(({ key, state }, i) => {
287 if (i > 0) segs.push({ text: ' › ', color: null, dim: true })
288 const n = run.steps.filter(s => s.key === key).length
289 segs.push({ text: `${key}${n > 1 ? `×${n}` : ''}${TRAIL_MARK[state]}`, color: TRAIL_COLOR[state], bold: state === 'run' || state === 'wait', dim: state === 'todo' })
290 })
291 const focus = focusOf(run)
292 if (focus === null) {
293 segs.push({ text: ' done', color: 'success', bold: true }, { text: ` · ${minutes((run.doneAt ?? now) - run.startedAt)}`, color: null, dim: true })
294 } else if (focus.state !== 'todo') {
295 const ms = stepMs(run, focus.key, now)
296 if (ms !== null) segs.push({ text: ` · ${minutes(ms)}`, color: null, dim: true })
297 }
298 const tail: Seg[] = []
299 const test = run.log.findLast(l => l.kind === 'test')
300 if (test?.isOk === false) tail.push({ text: `✗${test.detail === null ? '' : ` ${test.detail}`}`, color: 'error' })
301 if (run.signals.length > 0) tail.push({ text: `⚑${run.signals.length}`, color: 'magenta' })
302 tail.forEach((t, i) => segs.push({ ...t, text: `${i === 0 ? ' ' : ' '}${t.text}` }))
303 return segs
304}
305
306/**
307 * The gantt: a row per step in the plan, `width` cells across the run from its start to
308 * `now`, a cell filled wherever that step ran; a step begun twice fills two stretches.
309 * `ms` is its time over every run, null for one not begun.
310 */
311export const gantt = (run: Run, now: number, width: number): { key: string; state: StepState; cells: boolean[]; ms: number | null }[] => {
312 const end = Math.max(now, run.startedAt + 1)
313 const per = (end - run.startedAt) / width
314 return stepsOf(run).map(({ key, state }) => {
315 const recs = run.steps.filter(s => s.key === key)
316 const cells = Array.from({ length: width }, (_, i) => {
317 const from = run.startedAt + i * per
318 return recs.some(s => s.startedAt < from + per && (s.endedAt ?? end) > from)
319 })
320 return { key, state, cells, ms: stepMs(run, key, end) }
321 })
322}
323
324/** The step a moment of the run fell in, `#2` on its second time round; null before any. */
325export const stepAt = (run: Run, at: number): string | null => {
326 const i = run.steps.findLastIndex(s => s.startedAt <= at)
327 const rec = run.steps[i]
328 if (rec === undefined) return null
329 const round = run.steps.slice(0, i + 1).filter(s => s.key === rec.key).length
330 return round > 1 ? `${rec.key} #${round}` : rec.key
331}
332
333// --- the conversation's lines ------------------------------------------------------------
334
335/** What a stretch of the log did, as the turn's closing line carries it: the step, then counts. */
336export const turnSummary = (log: readonly LogEntry[], since: number, step: string | null): Seg[] => {
337 const part = log.filter(l => l.at >= since)
338 const edits = part.filter(l => l.kind === 'edit').length
339 const test = part.findLast(l => l.kind === 'test')
340 const asks = part.filter(l => l.kind === 'ask').length
341 const signals = part.filter(l => l.kind === 'signal').length
342 const segs: Seg[] = [{ text: ' · thegraph ', color: null }]
343 if (step !== null) segs.push({ text: step, color: STEP_COLOR[step] ?? null })
344 if (edits > 0) segs.push({ text: ` ✎${edits}`, color: 'blue' })
345 if (test) segs.push({ text: ` ${test.isOk ? '✓' : '✗'}${test.detail === null ? '' : ` ${test.detail}`}`, color: test.isOk ? 'success' : 'error' })
346 if (asks > 0) segs.push({ text: ` ◆${asks}`, color: 'warning' })
347 if (signals > 0) segs.push({ text: ` ⚑${signals}`, color: 'magenta' })
348 return segs
349}
350
351/** Every step's place: from the run sheet once there is one, else from the events. */
352export const stepsOf = (run: Run): { key: string; state: StepState }[] => {
353 const sheet = run.sheet
354 if (sheet === null || sheet.steps.length === 0) return plan(run.route).map(key => ({ key, state: stateOf(run, key) }))
355 const steps = sheet.steps.map(s => ({ key: s.key, state: (s.mark === 'done' ? 'done' : s.mark === 'doing' ? 'run' : 'todo') as StepState }))
356 // The sheet cannot say that the person holds the move; the events can.
357 if (run.isWaiting) {
358 const at = steps.findIndex(s => s.state === 'run')
359 const stop = steps[at >= 0 ? at : steps.findIndex(s => s.state === 'todo')]
360 if (stop) stop.state = 'wait'
361 }
362 return steps
363}
364
365/** Whether the run is over: its events said so, or every step on its sheet is checked. */
366export const isDone = (run: Run): boolean =>
367 run.doneAt !== null || (run.sheet !== null && run.sheet.steps.length > 0 && run.sheet.steps.every(s => s.mark === 'done'))
368
369/**
370 * The step the line names: the one running or waiting, else the next one to do;
371 * null once the run is done. `index` is its place in the plan, from 0.
372 */
373export const focusOf = (run: Run): { key: string; index: number; state: StepState } | null => {
374 if (isDone(run)) return null
375 const steps = stepsOf(run)
376 const at = steps.findIndex(s => s.state === 'run' || s.state === 'wait')
377 const index = at >= 0 ? at : steps.findIndex(s => s.state === 'todo')
378 const step = steps[index]
379 return step === undefined ? null : { key: step.key, index, state: step.state }
380}
381
382/** A step's name as drawn: a step that waits on the person says so. */
383export const stepLabel = (key: string, state: StepState): string => (state === 'wait' ? `${key} · waiting` : key)
384
385/** Milliseconds a step took, or has taken so far, over every time it ran. */
386export const stepMs = (run: Run, key: string, now: number): number | null => {
387 const recs = run.steps.filter(s => s.key === key)
388 if (recs.length === 0) return null
389 return recs.reduce((ms, s) => ms + ((s.endedAt ?? now) - s.startedAt), 0)
390}
391
392export const minutes = (ms: number): string => (ms < 60_000 ? '<1m' : `${Math.round(ms / 60_000)}m`)
393
394/** `redden×2 firsthand`, in the order each first fired. */
395export const signalSummary = (run: Run): string => {
396 const counts = new Map<string, number>()
397 for (const s of run.signals) counts.set(s.skill, (counts.get(s.skill) ?? 0) + 1)
398 return [...counts].map(([k, n]) => (n > 1 ? `${k}×${n}` : k)).join(' ')
399}
400types/index.d.ts 87 lines1/**
2 * Which way the run went after the reading was confirmed: `build` (prose or code,
3 * make-it onwards) or `decision` (lens over the options). A trivial run ends at the
4 * confirm stop with no step after it, which no event tells apart from a pause.
5 */
6export type Route = 'build' | 'decision'
7
8/** One step as it happened: a skill thegraph called, or a stop where a person answers. */
9export type StepRec = { key: string; startedAt: number; endedAt: number | null }
10
11/** A skill that interrupts the order (redden, firsthand, boundary), and when. */
12export type SignalRec = { skill: string; at: number }
13
14/** One step line of a run sheet: `- [~] make-it`, and the note under it for the next step. */
15export type SheetStep = { key: string; mark: 'todo' | 'doing' | 'done'; note: string | null }
16
17/** The run sheet thegraph keeps in the OS temp folder (ADR-0080), as last written. */
18export type Sheet = {
19 path: string
20 /** The issue as read-it resolved it, and its title. */
21 issue: string | null
22 /** Where the issue lives, for this plugin to read: `owner/repo#42`, `#42`, or the issue file's path. */
23 source: string | null
24 /** read-it's route label, verbatim: trivial, open decision, prose, code. */
25 route: string | null
26 steps: SheetStep[]
27 carried: string[]
28}
29
30/**
31 * One line of the run's log, in the order it happened: a step begun, a question and
32 * its answer, a file written, a test run, a signal, a note to the next step, an item
33 * carried, the end.
34 */
35export type LogEntry = {
36 at: number
37 kind: 'step' | 'ask' | 'edit' | 'test' | 'signal' | 'note' | 'carry' | 'end'
38 text: string
39 /** The answer to a question, a test's counts; null while a question waits. */
40 detail: string | null
41 /** A test that passed, a file the write created. */
42 isOk?: boolean
43}
44
45/** A piece of a line drawn in one colour (a theme key or a colour name, or none for the default), bold or dim. */
46export type Seg = { text: string; color: string | null; bold?: boolean; dim?: boolean }
47
48/** One /thegraph run, as its skill calls and the turns between them showed it. */
49export type Run = {
50 /** What followed `/thegraph` on the prompt (an issue number), or null. */
51 label: string | null
52 startedAt: number
53 route: Route | null
54 steps: StepRec[]
55 signals: SignalRec[]
56 /** The turn ended while the run was open: the next move is the person's. */
57 isWaiting: boolean
58 /**
59 * A question box was put away (Esc) with nothing answered: what the person types
60 * next takes the run up again rather than answering, and so never ends it.
61 */
62 isDismissed: boolean
63 doneAt: number | null
64 /** Where this run's sheet lives: the path this plugin named when thegraph expanded, or one the run wrote itself. */
65 sheetPath: string | null
66 /** The run's own account, once it has written a run sheet; it outranks what the events suggest. */
67 sheet: Sheet | null
68 /** What happened, oldest first; the pane draws it. */
69 log: LogEntry[]
70}
71
72declare module 'claude-code' {
73 interface PluginState {
74 'thegraph-panel': {
75 run: Run | null
76 isPaneOpen: boolean
77 /** The clock as last ticked, so a running step's minutes redraw while idle. */
78 now: number
79 /**
80 * What each turn of the run did, keyed by the turn's duration in milliseconds:
81 * the closing line carries no other mark of which turn it closes.
82 */
83 turnLines: Record<string, Seg[]>
84 }
85 }
86}
87