SLOPSHOPPER

cairn

Milestone-driven development workflow and tracking system for Claude Code projects: a language-agnostic core with per-repo toolchain profiles (R, Python…

panebandguardcommandtoastprompt
★ 4v2.1.0MITupdated 2026-10-25jmgirard/cairn
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cairn
│ ┃ cairn ✕ › fix the failing auth test and add an audit log call │ ┃ no cairn ROADMAP found │ ⏺ Read(src/auth.ts) │ ⎿ 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 │ │ › /cairn-pane │ ⎿ cairn: no cairn ROADMAP found │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · cairn
no cairn ROADMAP found
README

cairn

A cairn is built one stone at a time, and marks the trail for whoever comes next.

A Claude Code plugin for milestone-driven development. It keeps a governed LLM Wiki for project state: the agent maintains it, you gate it. One canonical workflow covers planning, implementation, review, hotfixes, releases, and expert escalation, with all project state in plain markdown under cairn/, kept in bounds by weight caps and a self-auditing health check. Rigor scales to stakes: each milestone is classified user-facing or internal when it's planned, and the criteria audit and the review fan-out size themselves to that. The core is language-agnostic; each repo declares a toolchain profile (R, Python, Claude Code plugin, Quarto extension, Docker image, or generic) that supplies its language-specific commands. Work lands as small stacked milestones, and any session, today's or next month's, can find the path from the files alone.

cairn grew out of maintaining many R packages with Claude Code and rebuilding similar-but-diverging tracking systems in each. This plugin centralizes the logic (skills, rules, templates) so every repo works identically; each repo holds only its own state.

Release history lives in CHANGELOG.md; design rationale in cairn/DESIGN.md and the append-only decision log it points to.

Install

Two paths; pick one. Running both installs the plugin twice, and the duplicates will confuse skill routing.

Dev install (recommended): clone and symlink into your skills directory. The plugin loads from your checkout, so git pull updates it with no re-install step:

git clone https://github.com/jmgirard/cairn
ln -s /path/to/cairn ~/.claude/skills/cairn

One caution: the symlink is live. Whatever branch the checkout has is what loads at your next session start, in every repo, enforcement hooks included. Keep the checkout on main unless you're developing cairn itself. For a one-off trial without installing anything, use claude --plugin-dir /path/to/cairn (that session only).

Marketplace install: a frozen snapshot; re-install to pick up new releases. In Claude Desktop: Customize → Plugins. From the CLI:

claude plugin marketplace add jmgirard/cairn
claude plugin install cairn@cairn

Either way, the install includes the guardrail hooks: the blocking ones (merge approval, a force-push guard on your default branch), the housekeeping ones (session-start tracking re-injection, the uncommitted-tracking stop guard), and the advisory nudges, none of which block anything you're doing. A nudge fires when an idea gets captured somewhere other than the roadmap, when something durable is headed for Claude's memory instead of your tracking files, and when a commit on your default branch reaches outside cairn/. The hooks activate at the next session start and are no-ops in repos that aren't cairn-tracked.

Then, in your package repo, run /cairn-init. Fresh repos get scaffolding; repos with an older tracking system get an interactive, PR-based migration. Run /milestone any time you're unsure where things stand.

Give /milestone an issue number (#12, 12, or issue 12) or an issue URL, and it looks into that one GitHub issue instead. It reads the issue and the code the issue names, then reports one verdict (reply, hotfix, or milestone) and how much maintainer input the work needs (none, confirm, or decide). One question then lets you start the work now, add a candidate row, leave the issue, or stop. Leave is offered only for noise, a duplicate, or an item cairn already covers. A reply declines a request only when the reason to decline is already on record. For a reply, cairn writes the draft to a file in the system temp directory and shows a gh issue comment --body-file command for you to run, so no shell quoting touches the reply. You can edit the file first. It never posts the reply itself. In guest mode, the commands name the upstream repo, and the draft uses no cairn terms.

The milestone band

The plugin also ships a Claude Code mod: a band above the prompt that shows one row for the milestone in flight, or between milestones for the next one you can start, or a row to start planning when there is no such milestone. The milestone in flight is the first in-progress row of cairn/ROADMAP.md, else its first review row. While /milestone-review runs, it is the first review row when one exists. The row gives no sign of the other active milestones. The id in bold and the milestone's title sit at the left of the row. The flow track and the percent sit at its right edge. One of the band's test fixtures gives this row when M010 is its only active milestone, shown here with the track as [track]:

M010 Nested tasks and a capital X  [track] 88%

The track is one rounded bar of three equal parts: plan, implement, then review. On a milestone row, plan is full. Implement fills by the checked boxes of ## Tasks, and it is full on a review row. Review fills by the checked boxes of ## Acceptance criteria. Specks fill the track from its left end to the edge of the current phase's fill. They start sparse and gray, and they grow dense near the edge, where more of them take the phase's color: blue or teal for plan, orange for implement, and green for review (blue in the colorblind themes). A pill on that edge names the phase and its counts, such as Implement 1/3 or Review 1/2, in the phase's color. A section with no boxes shows no tasks or no criteria in the pill. The percent of the whole flow follows the track. Each part counts for a third, and the percent rounds down. So it reads 100% only on a review row whose criteria are all checked, and a review row with no criteria reads 66%.

In the desktop app, and on any other surface that can draw an image, the track is an image. Two thin marks divide the three parts. In the current part, a tick marks each item edge past the fill when the items are 6 pixels apart or more. The image cannot follow your theme's colors, so it draws from one fixed palette meant for a light or a dark background: translucent grays, and the phase colors rgb(71,103,158) blue, rgb(152,85,57) orange, and rgb(68,113,81) green. The pill's white text has a contrast of at least 4.5:1 on its color, the WCAG 2.2 minimum for text, whatever the background. In the terminal the track is a run of braille characters on your theme's userMessageBackground color. Its dots are the specks, a dim mark divides the parts past the fill, and the pill is bold text in your theme's inverseText color on the phase's color. There the phase colors are your Claude Code theme's own keys: planMode (teal) for plan, claude (orange) for implement, and success (green) for review. The colorblind themes draw success in blue, and the ANSI themes use your terminal's own colors.

The desktop app draws the track at 7 pixels a column, up to 52 columns and at most 360 pixels. The terminal draws it at most 52 characters wide. In a narrower window the track gets shorter, so that the title keeps 10 columns, or its full width when the title is shorter. The track keeps at least 12 columns. When the whole pill would take more than a third of the track, the pill shows the counts alone, such as 1/3, or none for a section with no boxes. The band counts one column per character, so a short title of wide characters, such as CJK characters or emoji, can get less room than it draws. A title too long for the width is cut at its end, and the right part stays at the right edge.

A row whose File/Archive path names no regular file the band can read shows no milestone file in place of the track, or no file in a narrow window, in your theme's warning color. The rest of the row draws in the theme's gray. If another plugin draws a band in the same place, its rows show under cairn's.

The band draws nothing of the running cairn skill. It keeps track of the skill for two things: the row it shows during /milestone-review, and when a hidden band shows again (below). A cairn skill counts from its start, by its plain name or its cairn: name. It stays until Claude stops with no background work in flight and no one-shot wakeup pending, such as after the skill's closing summary. A question chip the skill asks you waits inside the turn, so the skill stays while you answer it. A question asked in plain text ends the turn. With no background work in flight, the skill ends with it, and otherwise your typed answer ends it. When Claude ends a turn to wait for background work, such as the reviewers that /milestone-review starts, the skill stays through the wait and through the turns that the work's notices start. A prompt you type while Claude is idle ends the skill. A prompt you type while Claude works keeps it, and so does a message from another session. An interrupt with Esc keeps it too, because an interrupted turn has no stop, so the skill stays until your next prompt or until Claude next stops with no background work in flight. A cairn skill that starts again, the same one included, or a session end, a /clear included, also ends it. A subagent that loads a cairn skill also counts, because the skill event does not say which agent loaded it.

When Claude stops while a one-shot wakeup (ScheduleWakeup) is pending, the skill stays. A prompt you type that a hook blocks or drops keeps the skill too.

The rule has three limits. A recurring scheduled task, such as a /loop with a fixed interval, does not keep the skill, so a skill that waits on one ends when Claude stops. Background work that the skill did not start, such as a server or a monitor started earlier, keeps a finished skill until your next prompt, because the band does not tell the skill's own work from other work. A one-shot wakeup that the skill did not set also keeps a finished skill, for the same reason. A /loop with no interval schedules one-shot wakeups, so it keeps a finished skill this way.

With no milestone active, the band shows an idle row for the next milestone you can start, whether or not a cairn skill runs. That milestone is the first planned row whose Depends on milestones are all done, by priority and then by id, the one cairn_next.py recommends. When no milestone is workable, cairn_next.py recommends planning. It then names the first [high] candidate row that no counted started token hides, by its short title, for example /milestone-plan Fix the pane's slow refresh. A — started M<n> token counts while that milestone's row is planned or blocked, but not for a blocked row whose file was archived. A — started #<n> token of up to 15 digits always counts, since the script reads no PRs. A token hides every row with its row's short title. Rows inside an HTML comment do not count. A dependency is done when its row is done or its file is in cairn/milestones/archive/. In guest mode with # Push remote: base, one dependency can instead be a change that waits for the maintainers' review (see "A milestone can build on one that waits for review" under guest mode). The idle row draws the id in bold and the title, then a track with plan full and the pill Planned:

M021 Waiting to start  [track]

After the track, an Implement button and a Status button show while no cairn skill runs and Claude is not working, where the row has room for them. After a cairn skill ends, a Clear button also shows before them. A press of Implement runs /clear and then, in the cleared conversation, /cairn:milestone-implement with the milestone's id, as if you typed both. It does not ask first, because the press is your consent to drop the conversation, as a press of Clear is. The second command starts when the session that /clear ends is over. Until then, a press of a next-step, Status, or Clear button does nothing. If the session refuses /clear, the second command does not run, and /clear goes after the text in the prompt box with a toast that says why. If the session ends for another reason first, such as a resume, the second command does not run, and its command line goes into the prompt box with a toast. If the session end itself fails, the same happens. The row draws no command as text, so while the buttons do not show, the row shows the id, the title, the track, and the ≡ and close buttons. In a narrow window the idle row drops its track, so that the title keeps room.

With no active milestone and no workable planned milestone, the band shows the empty row: No milestone ready in gray, with no id and no track. A planned milestone that waits on a dependency, or a blocked one, does not make a milestone workable, so the empty row shows then too. The row carries two buttons before its ≡ and close buttons. They show while no cairn skill runs and Claude is not working, in a band 37 columns wide or more. Plan runs /clear and then /cairn:milestone-plan in the cleared conversation, as Implement does with its command. Its argument is the short title of the first [high] candidate row that the pane's Candidates list (below) shows. With no such row, Plan runs planning with no arguments. Status runs /cairn:milestone. A press runs the command as if you typed it. A second press while the first run is going does nothing. So does a press while Plan waits for its /clear to end the session. If the run is refused, the command goes after the text in the prompt box, and a toast says why. If the session refuses Plan's /clear, /clear goes there and planning does not run. If the planning run itself is refused, /cairn:milestone-plan goes there. If Plan names a row, the row's title follows the command.

When a cairn skill ends, a Clear button shows on any row that carries the next-step and Status buttons, before them. A press runs /clear at once and does not ask first. It does not check that the skill's work is committed. The button goes away when you send a prompt while Claude is idle and no hook drops it, when a cairn skill starts, or when the session ends. A /clear that the session refuses goes into the prompt box, as above. Where the row has no room for three buttons, it drops Clear first.

The row ends in a close button: × in the terminal, and in the desktop app a ✕ that is dim at rest. On a row drawn from a ROADMAP, a ≡ button before it opens the cairn pane (below). Pressing the close button hides the band. Until the session ends, the band stays hidden while the list of active milestones stays the same: their ids, their statuses, and their ROADMAP order. For example, a milestone that moves from implement to review, or a milestone that becomes active or leaves both statuses, shows the band again. A cairn skill that starts or ends keeps it hidden, unless /milestone-review moves the band to another row, a review row when an in-progress row would show without it. A hidden idle row shows again when another milestone takes its place, or when no milestone is workable any more and the empty row takes its place. A hidden empty row shows again when a milestone becomes active or workable. A checked box or an edited title does not bring the band back. A session end shows a hidden band again, whatever its reason. In the desktop app, a /clear stops the session, and the band draws again at your next message. If the band finds the ROADMAP but cannot read it, or the file is empty, the band keeps its row. It keeps the row only when the row came from the same repo. The failed read alone does not hide or show it. After the session moves to another repo, a failed read shows no row. A working directory that cannot be read also shows no row. So the band never shows another repo's milestones. A press of the close button that lands as the session ends does nothing, so the band shows after the session end.

The band finds the ROADMAP in the session's working directory or the nearest directory above it. On Windows, the search stops at a network share's root (\\server\share). It reads the files when the session starts and at the end of each turn. It also reads them when a cairn skill starts or ends, and after Claude edits or writes a file under a cairn/ directory, so a box Claude checks moves the track inside a long turn. A box you check or a status you change shows after the next of these. Outside a cairn repo, it draws nothing. It also gives way while Claude Code shows a survey there. The band draws on the terminal and in the desktop app.

The cairn pane

The /cairn-pane command opens a pane that shows more than the band. Run it again to close the pane, or use the pane's own close mark. The band's ≡ button also opens it. In the desktop app the pane docks beside the conversation. In the terminal it docks beside a fullscreen conversation of 110 columns or more, and otherwise it sits above the prompt.

The pane opens with a summary card in a round border. Its first line shows the project's name in bold. After the name it shows the number of open pull requests and open issues on the base remote's repo, from every author. The name is the repo's name on a github.com base remote. With a remote on another host, or none, it is the name of the folder that holds the repo's .git directory. A worktree thus shows the repo's name. Before the first read for a repo folder, the name is that folder's own name, so a worktree shows its own name until the read. If git cannot say, the name is also that folder's own name. If the git dir is not a .git folder, as in a submodule or a bare repo, the same holds. A name too long for the pane is cut with …. Outside the terminal, for example in the desktop app, on a github.com base remote, the name is a link to the repo's GitHub page. The pull request count and its word open the repo's pull requests list, and the issue count and its word open its issues list. Before the first read, these items are not links. A remote on another host, or no remote, also gives no links. So does an owner or repo name with a character other than an ASCII letter, a digit, ., _, or -, a name that is . or .., and a name longer than GitHub allows. The terminal pane draws no links, so its row keeps room for its buttons. The card's second line shows the candidate rows at each level, with the level's mark: [high], normal, [low], and [parked]. It counts the rows that the Candidates list (below) would show, also while a milestone is active. Its third line shows the planned and blocked milestones. A fourth line shows the latest release, for example v2.1.0 · 12 days ago · 4 done since. The tag is the newest v* tag that git describe finds. The days run from that tag's commit to the read, and the count is the milestone files added to cairn/milestones/archive/ since the tag. The PR and issue numbers come from one gh api graphql query on a github.com base remote, at the same times as the PR states (below). A remote on another host runs no query. Until a read gives numbers for the repo folder, they show ?. A read that fails or runs no query keeps the last numbers for the same repo folder, and the card holds one folder's numbers at a time. The release line needs the three git calls to succeed, and guest mode draws none.

For each in-progress or review milestone, the pane shows the id, in the phase's color, and the title in bold, with the band's percent for the milestone at the end of that line when its file reads, and the goal from the milestone file. The goal wraps at the pane's width. The lines of one paragraph join, and each list item (- , * , or 1. ) starts a new line. It lists every task and acceptance criterion. A checked box shows a filled circle with a check, an open box a dashed circle, and the first open task of an in-progress milestone, the one being worked, a circle with three dots. In the desktop app these marks, the candidate marks, and the PR state marks are small icons of one size, in fixed colors, since an image cannot follow the theme. The terminal draws them as ●, ◌, ⊙, and the glyphs named below. The pane does not show the work log. Each item takes one line, and a long item ends in …. In the desktop app, holding the pointer over a milestone's line, a task, a criterion, or a workable, waiting, blocked, or hotfix line opens a card above it with the whole text. A candidate row opens its card from an info icon (ⓘ) instead. That card holds the row's whole text after the priority token, with any HTML comments left out. The row itself shows only its short title. When the card fits above the row, it opens there. When it fits only below the row, it opens below. A card too tall for either side opens on the side with more room and is cut to fit. When that side has fewer than 3 rows, no card opens. The pane only estimates the rows a card takes. A card can still come out a row or two shorter or longer than its room. The pointer over the row shows the icon, and on a row with a ✎, the ✎ beside it. The pointer over the icon opens the card. Each section starts after a blank row with its name in bold. The Blocked, Hotfixes, and Candidates headings show their count as a badge right after the heading name. The badge is a gray rounded pill with a white number. The terminal draws the badge as the number with a space on each side, on the theme's gray. The Tasks and Criteria headings show their count at the right end with a six-cell meter, ━ for the checked share and ─ for the rest. The next command follows a →, with the milestone's id after it. When the next step is planning and the Candidates list (below) shows a row, the pane shows no Next line. Each candidate line with a short title carries a ✎ that plans its row. With no row shown, the line shows /milestone-plan alone. The pane shows no line that says no milestone is active. While no cairn skill runs or waits on its background work, a button after the command reads Implement, Resume, Review, or Plan, the label of the band's next-step button, and a press runs the command as that button does, so Plan and Implement run /clear first. A press while Claude works outside a cairn skill runs the command when Claude is idle. At the same times, the Next line carries a Status button after that button, which runs /cairn:milestone. The Next line has no Clear button. The pane's ⌂ button, described below, clears the conversation. Each press runs the command of the band's button of the same name. As with the next-step button, a press while Claude works outside a cairn skill runs when Claude is idle. In a narrow pane, the command is cut first. In the desktop app, a click on the pane while it does not have keyboard focus only gives it focus. Then press the button again. The id and the meter of a milestone draw in its phase's color, the theme's claude orange for implement and success green for review. The Next line draws in the color of the phase that its command runs, planMode for planning. A high-priority candidate's ↑ draws in the implement color. The percent counts boxes as the band does, so a box inside an HTML comment counts there but not in the Tasks and Criteria counts, and the two can differ. A missing or unreadable milestone file shows no milestone file. Below the milestones, the pane shows the next command, the workable planned milestones, and the planned milestones that wait on others, as scripts/cairn_next.py gives them. When no milestone is in-progress or review, the pane also lists the ROADMAP's candidate rows under a Candidates heading with their count. Each row takes one line: ↑ for a [high] row, ○ for a normal one, ↓ for a [low] one, and ⧗ for a [parked] one, then the row's short title. A [low] row's mark and title are gray. A [parked] row waits on a promotion condition that has not held, such as "promote when a second repo needs it". Its title, and its mark in t

Source 10 files
hooks/status/register.tsx 1767 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { CairnBandHidden, CairnHotfixRead, CairnRepoRead, CairnStep } from '../../types'
5import type { BandLine, Span } from './band'
6import { actionsFit, cairnSkill, GAP, GRAY, knownStep, mark, PX_PER_COLUMN, same, stepLines, width } from './band'
7import { countsArgv, prRead } from './counts'
8import { BADGE_H, badgeSvg, badgeWidth } from './badge'
9import { ICON_PX, iconSvg } from './icons'
10import { archivedArgs, COMMON_DIR_ARGS, DESCRIBE_ARGS, doneSince, projectName, repoArgv, repoCounts, tagTimeArgs, webOf } from './repo'
11import type { CardPlace, HotfixPr, PaneButton, PrRead, StartedRow } from './pane'
12import {
13  cardCut,
14  cardPlaces,
15  CHECK_LABEL,
16  CLEAR_LABEL,
17  CLEARS_FIRST,
18  FINISH_LABEL,
19  HOME_LABEL,
20  hotfixPrs,
21  INFO_LABEL,
22  METER_EMPTY_KEY,
23  nextTitle,
24  startedRefs,
25  startedRows,
26  nextLabel as labelOf,
27  NO_ROADMAP,
28  paneLines,
29  PLAN_CANDIDATE_LABEL,
30  PLAN_LABEL,
31  PR_BUTTON,
32  PR_VIEW_FIELDS,
33  prViewRead,
34  READING_LABEL,
35  REFRESH_LABEL,
36  REVISE_LABEL,
37  STATUS_LABEL,
38} from './pane'
39import type { BandState, FileSource, PaneState } from './reader'
40import { collaborationMode, join, NO_PANE, readCairn } from './reader'
41import { brailleSpans, TRACK_H, TRACK_PX, trackSvg } from './track'
42
43// The milestone band above the prompt (M191, M193 to M201, M206): one row
44// for one `in-progress` or `review` ROADMAP row, refreshed when the session
45// starts, at the end of each turn, when a cairn skill's prompt is expanded,
46// and when a step ends. The row is the bold id and the title, then the flow
47// track and its percent (band.ts picks the row and its widths). With no
48// active milestone, an idle row names the next workable planned milestone,
49// and its `Implement` Button, not a command, starts it (M220). With none
50// workable, a found ROADMAP draws the empty row (M213). A press of `Plan`
51// or `Implement` runs `/clear`, and its command at the session end that
52// the clear brings (M221).
53// The track draws as an `Svg` on the desktop and as braille cells in the
54// terminal (track.ts). The running cairn skill draws nothing of its own:
55// /milestone-review picks the row it shows. A skill's step
56// ends at the first main-loop Stop with no background work in flight and no
57// one-shot wakeup pending (M210) that no hook
58// beneath blocks, or at a prompt the operator types while the session is
59// idle, unless a cairn skill's prompt was expanded since the last prompt,
60// Stop, or turn end, as a typed cairn slash command's is. A typed prompt
61// that a hook beneath drops leaves the step (M210). So the step holds while the skill waits on background work and
62// through the turns that the work's notices start (M201). The row sits
63// above whatever the hooks beneath draw in the same slot. It ends in a
64// close button, which hides the band until the active rows' ids, statuses,
65// or order, the row /milestone-review moves the band to, or the idle row's
66// id change, or the session ends (M200, M206). A found ROADMAP that cannot
67// be read, or is empty, keeps the rows when they came from the same repo
68// root (M210), and the close state is compared against them and the
69// current step.
70//
71// The cairn pane (M205) opens from the `/cairn-pane` command, which also
72// closes it, or from the band's open button, which a row drawn from a found
73// ROADMAP carries beside the close button. It shows the active milestones
74// in full and the queue that scripts/cairn_next.py prints (pane.ts), from
75// the same refreshes as the band. A head line whose file reads ends with
76// the band's percent for its row, so the pane reads the `band` value too
77// (M208). While no cairn skill's step is set, the Next line carries a
78// Button with the band's next-step label after its command, and a press runs
79// `pressNext`, as the band's does (M218). At the same times, the line
80// carries Status after that Button, and a press runs `pressStatus` (M219).
81// At the same times, the first line carries ⌂ before ↻, and a press runs
82// `pressHome`: `/clear`, and an open of the pane at the clear's session end
83// (M241). Until M241
84// the Next line carried Clear while `ended` was true.
85// Each open of the pane, by the command, the band's open button, or the
86// session-start reopen, reads the blocked rows' pull request states once
87// with `gh`, and so does a press of the pane's ↻ Refresh Button
88// (`readPrs`, M236). The reopen skips the read when its start already read
89// (M238). An open does not wait for that read, and a `/clear` or a
90// `/resume` reads again while the pane is placed, shown or behind another
91// tab (M230, M237). A pane listed but not placed then reads at its first
92// draw, unless an open or the start's reopen read first, or the start's
93// `$.ui.panes()` threw. One start reads once, though both its start hooks
94// fire (M238). A blocked line then shows its state word, and a merged,
95// changes-requested, or closed line carries a Button for its next step
96// (M224). The same read counts each open pull request's unresolved review
97// threads, which draw on a line under it (M225, M236). A github.com pull
98// request's word and count come from one `gh api graphql` call (M237). The same read lists the operator's open pull requests on the
99// base remote with one `gh pr list` call and keeps the ones from
100// `hotfix-*` branches, which the pane draws, each with its word and counts
101// (M226).
102
103// Each shape tag names a value's layout; a reload whose value was written
104// under another tag reads it as absent. Bump a tag when its type changes.
105// The band's value keeps the repo root of the last read, null when no
106// ROADMAP was found or the working directory could not be read; the tag
107// moved to 4 with the root (M210).
108type StoredBand = BandState & { root: string | null }
109const BAND_REF = { plugin: 'cairn', key: 'band' } as const
110const BAND_SHAPE = 'band-4'
111const band = atom(BAND_REF, { rows: [], workable: [], root: null } as StoredBand, { shape: BAND_SHAPE })
112
113// The active ids and statuses, in ROADMAP order, `milestone-review` while
114// it moves the band to another row, and the idle row's id while no row is
115// active, at the last press of the close button; null while the band shows.
116// The tag moved to 4 when the skill's meaning changed (M206 review). The
117// press writes through `$.state.set`, which takes the tag with the value and
118// a reference written as literals in this file.
119const DISMISSED_REF = { plugin: 'cairn', key: 'dismissed' } as const
120const DISMISSED_SHAPE = 'dismissed-4'
121const dismissed = atom(DISMISSED_REF, null as CairnBandHidden | null, { shape: DISMISSED_SHAPE })
122
123// The running cairn skill, until a main-loop Stop with nothing in flight or
124// an idle typed prompt ends it (the `classic.Stop` and `prompt.submit`
125// hooks). A typed prompt that finds `expanded` set keeps it; null while no
126// cairn skill runs. The chapter it once held went in M206.
127const step = atom({ plugin: 'cairn', key: 'step' } as const, null as CairnStep | null, { shape: 'step-2' })
128
129// True from a cairn skill's prompt until the next prompt, Stop, turn end, or
130// session end.
131// The engine expands a typed slash command before it raises the command's
132// prompt, so that prompt finds this set and keeps the step the command just
133// started (M201).
134const expanded = atom({ plugin: 'cairn', key: 'expanded' } as const, false, { shape: 'expanded-1' })
135
136// True from a main-loop Stop that ends a cairn skill's step until the next
137// idle typed prompt that enters, the next cairn skill's prompt, or the
138// session's end (M216). While it is true, a row that draws the action
139// Buttons carries the Clear Button too, when it has room for it.
140const ended = atom({ plugin: 'cairn', key: 'ended' } as const, false, { shape: 'ended-1' })
141
142// What the cairn pane shows, written at each refresh (M205). The tag moved
143// to 2 when the state gained the candidate rows (M207), to 3 when it
144// gained the blocked rows (M223), to 4 when each blocked row gained its
145// pull request's URL (M224), to 5 when each blocked row gained
146// `archived` (M246), to 6 when the state gained the candidate rows'
147// started tokens (M258), to 7 when the next step gained `title` (M272),
148// and to 8 when each candidate row gained its `text` (M293).
149const pane = atom({ plugin: 'cairn', key: 'pane' } as const, NO_PANE as PaneState, { shape: 'pane-8' })
150
151// Each blocked row's pull request state word by its URL, written by the
152// read at a pane open or a Refresh press (M224). A URL with no entry has
153// not been read, and its line shows no word. Each entry also holds the
154// open pull request's counts, or null; the tag moved to 2 with them (M225)
155// and to 3 when the second count left them (M236), and to 4 with the merge
156// state (M301).
157const prs = atom({ plugin: 'cairn', key: 'prs' } as const, {} as Record<string, PrRead>, { shape: 'prs-4' })
158
159// The hotfix list that the last read wrote, and the repo root it is for
160// (M226, `readHotfixes` says when it is kept or empty). The pane draws
161// them only while the band's root is that root, so a failed read after a
162// `cd` shows no other repo's. The same value holds the candidate rows that
163// the listed bodies name, so one write keeps both from one read; the tag
164// moved to 2 with them (M252).
165const hotfixes = atom({ plugin: 'cairn', key: 'hotfixes' } as const, { root: null, prs: [], started: [] } as CairnHotfixRead, {
166  shape: 'hotfixes-2',
167})
168
169// The summary card's numbers, the project name (M291), and the repo root
170// they are for (M286), written by the same read as the hotfix list
171// (`readRepo` says when they are kept). The pane draws them only while the
172// band's root is that root, and otherwise names the root's last segment.
173const repo = atom({ plugin: 'cairn', key: 'repo' } as const, { root: null, counts: null, done: null, name: null, web: null } as CairnRepoRead, {
174  // `repo-2`: `repo-1`, without the release days, never shipped (M286).
175  // `repo-3` adds the project name (M291), and `repo-4` the repo page (M311).
176  shape: 'repo-4',
177})
178
179// True from the start of a read of the pull request states until the newest
180// read started has settled (M236). The pane's ↻ Button reads ⋯ while it is
181// true and a read that this module started is in flight (`inFlight`, M237).
182// A reload keeps it, so neither the label nor a press relies on it alone
183// (`pressing`).
184const reading = atom({ plugin: 'cairn', key: 'reading' } as const, false, { shape: 'reading-1' })
185
186// The pane's id, its title, and the command that opens and closes it.
187const PANE = 'cairn'
188const PANE_TITLE = 'cairn'
189const PANE_COMMAND = 'cairn-pane'
190// The key of the Next line's Button (M218).
191const PANE_NEXT = 'cairn-pane-next'
192// The store key that holds the project roots whose session ended with reason
193// `other` while the pane was open and shown (M222). A typed `/clear` in the
194// desktop app ends the process that way, and the next process starts with no
195// pane at the first message after the clear, so its `session.start` opens
196// the pane again. The key is `$.session.root()`, which a shell `cd` does not
197// move, so it matches the folder the next session starts in (M222 review). An app quit or a signal that ends the session with reason
198// `other` also brings the pane back at the next session in that folder. The
199// API does not say which ends those are, and none was checked live.
200const REOPEN_KEY = 'reopen'
201// The theme's text color, which a linked span without a color of its own
202// takes in place of the link's (M311 live look).
203const LINK_TEXT_KEY = 'text'
204
205// The close button's label. The desktop app draws a dismiss Button in the
206// band as its label text, so a long label reads as text there. On the
207// desktop the label is `✕`, dim at rest, which the operator picked at a
208// live look as closest to the app's own close icon (M197).
209const CLOSE_GLYPH = '×'
210const DESKTOP_CLOSE_GLYPH = '✕'
211// The columns the row's close gap and one-glyph label take on either
212// surface, which the row leaves free when it picks its form.
213const CLOSE_COLUMNS = GAP + width(CLOSE_GLYPH)
214// The open button's one-glyph label and the space after it, which a row
215// drawn from a found ROADMAP also leaves free (M205).
216const OPEN_GLYPH = '≡'
217const OPEN_COLUMNS = width(OPEN_GLYPH) + 1
218
219// The action Buttons (M212): the next step's label, from pane.ts's
220// `nextLabel`, which the pane's Next Button reads too (M218), and the status
221// Button's command. A plugin skill runs as `cairn:<name>` (M195).
222const STATUS_COMMAND = 'cairn:milestone'
223// The built-in command the Clear Button runs (M216). The Status and Clear
224// labels sit in pane.ts, which the pane's Next line reads too (M219).
225const CLEAR_COMMAND = 'clear'
226// The hover card's ground, the theme key the band's braille track sits on
227// (M286).
228const HOVER_GROUND = 'userMessageBackground'
229// The hover group of a candidate line's info glyph and card, one per line
230// key (M290).
231const infoScope = (lineKey: string) => `cairn-info-${lineKey}`
232// The columns a candidate line keeps for ✎ while the pointer is over it,
233// and the `right` offset that parks ✎ past the row's edge at rest (M290).
234// The park hides ✎ only while its Button is narrower than 8 columns, since
235// the pane clips what lies past its edge; a wider label needs both changed.
236const PLAN_SLOT = 4
237const PLAN_PARK = -8
238// The command a candidate line's ✎ holds for its `/clear` (M242).
239const PLAN_COMMAND = 'cairn:milestone-plan'
240// `CLEARS_FIRST`, the next steps whose Button runs `/clear` first (M221),
241// sits in pane.ts beside the label map.
242// The key and label of each Button after the Next line's action (M219),
243// of the pane's ⌂ Home (M241) and ↻ Refresh (M236), and of a blocked
244// line's Button, whose key ends in its milestone id (M224).
245const PANE_BUTTONS: Record<PaneButton, { key: string; label: string }> = {
246  home: { key: 'cairn-pane-home', label: HOME_LABEL },
247  status: { key: 'cairn-pane-status', label: STATUS_LABEL },
248  refresh: { key: 'cairn-pane-refresh', label: REFRESH_LABEL },
249  finish: { key: 'cairn-pane-finish', label: FINISH_LABEL },
250  revise: { key: 'cairn-pane-revise', label: REVISE_LABEL },
251  check: { key: 'cairn-pane-check', label: CHECK_LABEL },
252  plan: { key: 'cairn-pane-plan', label: PLAN_CANDIDATE_LABEL },
253}
254
255// The command each blocked line's Button runs, and whether the milestone's
256// id is its argument (M224). None runs `/clear` first, as the Review and
257// Resume Buttons keep the conversation.
258const BLOCKED_COMMANDS: Partial<Record<PaneButton, { command: string; withId: boolean }>> = {
259  finish: { command: 'cairn:milestone-review', withId: true },
260  revise: { command: 'cairn:milestone-implement', withId: true },
261  check: { command: STATUS_COMMAND, withId: false },
262}
263
264// How long one `gh api graphql` or `gh pr view` call may run, well under
265// the ten minutes `$.process.run` allows. The URLs' calls run side by side,
266// and a call still running then rejects and reads as `unknown` with no
267// counts (M224, M237). Each URL takes one call (M237).
268const GH_TIMEOUT_MS = 15_000
269
270export const register: Register = on => {
271  on('session.start', async ($, e, next) => {
272    const result = await next(e)
273    await refresh($)
274    // The band does not depend on the command: a refused registration
275    // leaves the band as the refresh drew it.
276    try {
277      await $.command.register({ name: PANE_COMMAND, description: 'Open or close the cairn pane' })
278    } catch {
279      // No `/cairn-pane` in this session. The band's open button still opens the pane.
280    }
281    // After the registration, so a slow open does not hold `/cairn-pane`
282    // back (M222 review).
283    await reopen($)
284    return result
285  })
286
287  // A `/clear` that stays in the same process raises no `session.start`, and
288  // the host's state starts empty under the new session id, so the band and
289  // an open pane read the files again here (M222). A `/resume` does the same
290  // (M237). The hook cannot tell a resume in the process from a resumed
291  // start, so a resumed start reads the files twice. A placed pane, shown or
292  // behind another tab, also reads the pull request states and the hotfix
293  // list again, and the hook does not wait for that read (M230, M237). A
294  // pane listed but not placed owes that read, and its first draw starts it
295  // (`owed`, M238), unless the hook's second listing finds it placed and
296  // reads first (M256). A start whose reopen already read starts no second read
297  // and owes none (`startRead`, M238).
298  on('classic.SessionStart', async ($, e, next) => {
299    const result = await next(e)
300    if (e.source === 'clear' || e.source === 'resume') {
301      // A session end during any await below makes the hook read and owe
302      // nothing, as a later start may owe the read and it is that start's
303      // (M260).
304      const at = ends
305      await refresh($)
306      if (startRead) return result
307      const mine = await listedPane($)
308      // A reopen that read during the await is this start's read (M238
309      // review).
310      if (mine == null || startRead || ends !== at) return result
311      if (mine.isPlaced) {
312        startRead = true
313        owed = false
314        void readPrs($)
315        return result
316      }
317      owed = true
318      // A pane placed and drawn during the list above drew before the read
319      // was owed, so the hook lists it again and reads if it is now placed,
320      // unless something cleared `owed` meanwhile: a draw, an open, a
321      // session end, or another start's hook (M256), or reads nothing after
322      // a session end, as above (M260).
323      const again = await listedPane($)
324      if (again != null && again.isPlaced && owed && ends === at) {
325        owed = false
326        startRead = true
327        void readPrs($)
328      }
329    }
330    return result
331  })
332
333  // `/cairn-pane` closes an open pane, and otherwise reads the files and
334  // opens it, or says why it did not (M205 AC1). After the open, it starts
335  // the read of the pull request states (M224), and its line does not wait
336  // for that read, whose calls each have a 15 s timeout (M230).
337  // Only a pane the person can see is closed: one that waits undrawn, or
338  // sits behind another pane's tab, is opened again instead (M205 review).
339  // A hook that refuses the open or the close gives a line, not an error.
340  // The first `/cairn-pane` after the session-start reopen, before any turn
341  // ends, keeps the reopened pane open: a typed `/clear` took the pane off
342  // the screen, and that command is the message whose start reopened it.
343  on('command.run', { command: PANE_COMMAND }, async $ => {
344    const afterReopen = reopened
345    reopened = false
346    try {
347      const mine = await paneOf($)
348      if (placedAndShown(mine)) {
349        if (afterReopen) return { text: 'cairn pane opened' }
350        await $.ui.close({ id: PANE })
351        return { text: 'cairn pane closed' }
352      }
353      await refresh($)
354      if (!(await read($, pane)).found) return { text: NO_ROADMAP }
355      const opened = await $.ui.open({ id: PANE, title: PANE_TITLE })
356      owed = false
357      void readPrs($)
358      return { text: opened.isPlaced ? 'cairn pane opened' : notPlaced(opened.reason) }
359    } catch (error) {
360      return { text: `cairn pane: ${error instanceof Error ? error.message : String(error)}` }
361    }
362  })
363
364  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
365    // A pane that a clear or resume start found listed but not placed reads
366    // the pull request states at its first draw (M238), unless that start's
367    // second listing read first (M256). The flag clears
368    // before any await, so two draws at once start one read. The read is
369    // the start's read, so a reopen after it reads nothing (M238 review).
370    if (owed) {
371      owed = false
372      startRead = true
373      void readPrs($)
374    }
375    const { Box, Button, Text } = $.ui.resolve(e)
376    // The Next line's Button shows while no cairn skill's step is set
377    // (M218). A pane gets no `isWorking` prop, so it also shows during a
378    // turn outside a cairn skill, and a press then waits for the session to
379    // be idle, as `$.command.run` queues.
380    // After that Button, the Next line shows Status at the same times
381    // (M219), and the first line shows ⌂ (M241).
382    const acts = knownStep(await read($, step)) === null
383    const shown = await read($, band)
384    const held = await read($, hotfixes)
385    const ours = held.root !== null && held.root === shown.root
386    const counts = await read($, repo)
387    const lines = paneLines(
388      await read($, pane),
389      shown.rows,
390      acts,
391      await read($, prs),
392      ours ? held.prs : [],
393      ours ? held.started : [],
394      counts.root !== null && counts.root === shown.root ? counts : null,
395      shown.root,
396    )
397    // ⋯ also needs a read in flight in this module, so a stored true that a
398    // reload or a failed write left draws ↻ (M237).
399    const busy_ = (await read($, reading)) && inFlight > 0
400    // A line's lead and tail keep their width, and its text takes the room
401    // left between them: cut to one line with an ellipsis, or wrapped for
402    // the goal's lines. The line Box may shrink below its content's width,
403    // so a long text is cut rather than pushing the tail past the edge
404    // (M208). The action Button sits after them in a Box that
405    // does not shrink, so the Next command is cut first (M218), and so does Status
406    // after it, and the first line's ⌂ and ↻, each in its own such Box
407    // (M219, M236, M241). Off the terminal, a candidate line's ✎ Box has no
408    // key and sits past the row's edge until the pointer is over the line,
409    // and the info glyph before it stays hidden until then (M290). A Text drops its
410    // `key`, so each line's key sits on a Box.
411    // The card's lines draw in one Box with a round border in `subtle`,
412    // before the rest (M286). On the desktop a line with a `full` holds a
413    // hidden Box with its whole text (on a candidate line, its row's text
414    // after the priority token, M293), placed out of the flow, which the
415    // pointer over the line reveals, or on a line with `info` the pointer
416    // over its info glyph, which names the card's hover group (M290). An
417    // absolute Box is painted over the siblings before it, so a card drawn
418    // in its line opens upward (M286). A candidate card opens upward when it
419    // fits above its row, else downward when it fits below. When it fits
420    // neither side, it opens on the larger side (above on a tie) with its
421    // text cut, and is not drawn when that side has fewer than 3 rows. A
422    // card that opens downward, whole or cut, is drawn after every line in
423    // the pane's root Box (M294). A lead span that names an icon draws it as an
424    // `Svg` on a surface whose table has the element, and its glyph in the
425    // terminal, and a line with one centers its row (M286). A tail span
426    // that names an icon, the merge mark, draws the same way (M301).
427    const Svg = e.surface === 'terminal' ? undefined : $.ui.resolve(e).Svg
428    // Spans with an `href` draw in a `Link` to that page, but in the
429    // terminal (M311): a terminal without OSC 8 draws the URL after the
430    // text, which would push the first line's Buttons off the row. A run of
431    // spans with one `href`, a count and its word, is one Link, so it lights
432    // as one. Inside it each span is a `Text` in its own style, the theme's
433    // text color where it names none, with no underline, so the link takes
434    // the card's look rather than a link's blue and underline (M311 live
435    // look). The Link sits in a `Text` that cuts with an ellipsis, as every
436    // span's `Text` does, and so does each `Text` inside it (M311 review).
437    const Link = e.surface === 'terminal' ? undefined : $.ui.resolve(e).Link
438    const linkStyle = (span: Span) => ({ color: LINK_TEXT_KEY, ...style(span), underline: false })
439    const linked = (group: Span[]) =>
440      Link === undefined ? null : (
441        <Link href={group[0].href as string}>
442          {group.map(span => (
443            <Text wrap="truncate-end" {...linkStyle(span)}>
444              {span.text}
445            </Text>
446          ))}
447        </Link>
448      )
449    // A span that holds a badge draws as its `Svg` pill on such a surface,
450    // and as its padded text on the theme's gray in the terminal (M289); a
451    // heading with one centers its row too. Since M302 the badge is in the
452    // heading's lead, after the label, where M289 put it in the tail.
453    const drawSpan = (span: Span) =>
454      span.badge !== undefined && Svg !== undefined ? (
455        <Svg
456          source={badgeSvg(span.badge.count)}
457          alt={`${span.badge.count}`}
458          width={badgeWidth(span.badge.count)}
459          height={BADGE_H}
460        />
461      ) : span.icon !== undefined && Svg !== undefined ? (
462        <Svg source={iconSvg(span.icon)} alt={span.text} width={ICON_PX} height={ICON_PX} />
463      ) : (
464        <Text wrap="truncate-end" {...style(span)}>
465          {span.text}
466        </Text>
467      )
468    // A part's spans, each run with one `href` drawn as one Link where the
469    // surface draws Links, and every other span as `drawSpan` draws it.
470    const drawSpans = (spans: Span[]) => {
471      if (Link === undefined) return spans.map(drawSpan)
472      const out: unknown[] = []
473      for (let i = 0; i < spans.length; ) {
474        const href = spans[i].href
475        let end = i + 1
476        if (href !== undefined) while (end < spans.length && spans[end].href === href) end += 1
477        out.push(href === undefined ? drawSpan(spans[i]) : <Text wrap="truncate-end">{linked(spans.slice(i, end))}</Text>)
478        i = end
479      }
480      return out
481    }
482    // A line that draws the info glyph, which then alone opens its card (M290).
483    const infos = (line: (typeof lines)[number]) => line.info === true && line.full !== undefined && e.surface !== 'terminal'
484    // Where each candidate card opens, from the Pane props (M294): above
485    // its row when it fits there, else below, else cut to the larger side,
486    // or not at all where that side has fewer than 3 rows. A card that
487    // opens below draws after every line in the pane's root Box: an
488    // absolute Box is painted over the siblings before it, so the lines
489    // after its own, painted later, would cover a card drawn in the line.
490    // The M294 live look saw a card drawn last paint over those lines.
491    const places = cardPlaces(lines, {
492      bodyColumns: e.props.bodyColumns,
493      offset: e.props.scroll.offset,
494      bodyRows: e.props.scroll.bodyRows,
495      placement: e.props.placement,
496    })
497    const placeOf = (line: (typeof lines)[number]): CardPlace =>
498      Object.prototype.hasOwnProperty.call(places, line.key) ? places[line.key] : { side: 'up', rows: null }
499    // A card's Box: no key of its own, since a keyed Box would scope its own
500    // hover and a hidden scope is never under the pointer (M290). `at` places
501    // it. A cut card holds its text cut by whole words to its rows, ending in
502    // `…`, and sets no height, since a fixed height left empty rows where the
503    // desktop wraps more per row than `cardRows` counts (M294 live look).
504    const cardBox = (line: (typeof lines)[number], at: { top: number } | { bottom: number }, rows: number | null) => (
505      <Box
506        position="absolute"
507        {...at}
508        left={0}
509        right={0}
510        display="none"
511        hover={infos(line) ? { display: 'flex', scope: infoScope(line.key) } : { display: 'flex' }}
512        borderStyle="round"
513        borderColor={METER_EMPTY_KEY}
514        backgroundColor={HOVER_GROUND}
515        paddingX={1}
516      >
517        <Text wrap="wrap">{rows === null ? line.full : cardCut(line.full ?? '', rows, e.props.bodyColumns)}</Text>
518      </Box>
519    )
520    // A tail icon, the merge state mark, centers its row too (M301), and so
521    // does a badge in the lead (M302).
522    const drawsSvg = (span: Span) => span.badge !== undefined || span.icon !== undefined
523    const centers = (line: (typeof lines)[number]) =>
524      Svg !== undefined && (line.lead.some(drawsSvg) || (line.tail ?? []).some(drawsSvg))
525        ? { alignItems: 'center' as const }
526        : {}
527    const drawLine = (line: (typeof lines)[number]) => (
528          <Box key={line.key} paddingLeft={line.indent} minWidth={0} {...centers(line)}>
529            {line.lead.length === 0 ? null : (
530              <Box key={`${line.key}-lead`} flexShrink={0} {...centers(line)}>
531                {line.lead.map(drawSpan)}
532              </Box>
533            )}
534            {line.text === null ? null : (
535              <Box key={`${line.key}-text`} flexShrink={1} minWidth={0} {...(line.grow ? { flexGrow: 1 } : {})}>
536                <Text wrap={line.wraps ? 'wrap' : 'truncate-end'} {...style(line.text)}>
537                  {line.text.href !== undefined && Link !== undefined ? linked([line.text]) : line.text.text}
538                </Text>
539              </Box>
540            )}
541            {line.tail === undefined ? null : (
542              // A tail that grows takes the free room, so the Buttons after
543              // it sit at the right end (the card's first line, M291).
544              <Box key={`${line.key}-tail`} flexShrink={0} {...(line.tailGrows ? { flexGrow: 1 } : {})} {...centers(line)}>
545                {drawSpans(line.tail)}
546              </Box>
547            )}
548            {line.action === undefined ? null : (
549              <Box key={`${line.key}-action`} flexShrink={0} marginLeft={1}>
550                <Button
551                  key={PANE_NEXT}
552                  variant="secondary"
553                  label={line.action}
554                  onPress={() => pressNext($, line.action)}
555                />
556              </Box>
557            )}
558            {!infos(line) ? null : (
559              // The info glyph, hidden until the pointer is over the line,
560              // when ✎ also moves in. It names the hover group that alone opens the line's
561              // card, so the card no longer opens with ✎ (M290). In the
562              // desktop app a Text in a group heats it and a Box that only
563              // names the group does not (M290 live look). Its right margin
564              // keeps the room that ✎ moves into.
565              <Box
566                display="none"
567                hover={{ display: 'flex' }}
568                flexShrink={0}
569                marginLeft={1}
570                marginRight={(line.buttons ?? []).includes('plan') ? PLAN_SLOT : 0}
571              >
572                <Text color={GRAY} hover={{ scope: infoScope(line.key), bold: true }}>
573                  {INFO_LABEL}
574                </Text>
575              </Box>
576            )}
577            {(line.buttons ?? []).map(kind => {
578              const button = PANE_BUTTONS[kind]
579              const target = line.target
580              const title = line.title
581              // Off the terminal a candidate line's ✎ sits in an unkeyed Box
582              // placed past the row's right edge, where the pane clips it, and
583              // the pointer over the line moves it into the room the info
584              // glyph keeps (M290). In the desktop app a Button drawn under
585              // `display: 'none'` takes no click once revealed, and one moved
586              // by an offset does. A keyed Box would scope its own hover. The
587              // Box spans the row's height and centers ✎ in it, as the row
588              // centers ⓘ.
589              const parks = kind === 'plan' && e.surface !== 'terminal'
590              return (
591                <Box
592                  {...(parks
593                    ? {
594                        position: 'absolute' as const,
595                        top: 0,
596                        bottom: 0,
597                        alignItems: 'center' as const,
598                        right: PLAN_PARK,
599                        hover: { right: 0 },
600                      }
601                    : { key: `${line.key}-${kind}` })}
602                  flexShrink={0}
603                  marginLeft={1}
604                >
605                  <Button
606                    key={target === undefined ? button.key : `${button.key}-${target}`}
607                    variant="secondary"
608                    label={kind === 'refresh' && busy_ ? READING_LABEL : button.label}
609                    onPress={() => pressPane($, kind, target, title)}
610                  />
611                </Box>
612              )
613            })}
614            {line.full === undefined || e.surface === 'terminal' || placeOf(line)?.side !== 'up'
615              ? null
616              : // An upward card, in its line above the row. The keyed line Box
617                // opens it, or on a line with the info glyph its group (M290).
618                cardBox(line, { bottom: 1 }, placeOf(line)?.rows ?? null)}
619          </Box>
620    )
621    const card = lines.filter(line => line.card)
622    // The cards that open below their rows, each at its line's row plus 1
623    // in the pane's tree, drawn after every line (M294).
624    // Only a line with the info glyph: its card names the glyph's hover
625    // group, where a card at the root with no group would light from
626    // anywhere in the pane.
627    const below = lines.filter(line => infos(line) && placeOf(line)?.side === 'down')
628    return (
629      <Box key="cairn-pane" flexDirection="column">
630        {card.length === 0 ? null : (
631          <Box key="cairn-card" flexDirection="column" borderStyle="round" borderColor={METER_EMPTY_KEY} paddingX={1}>
632            {card.map(drawLine)}
633          </Box>
634        )}
635        {lines.filter(line => !line.card).map(drawLine)}
636        {below.map(line => cardBox(line, { top: (line.rowsAbove ?? 0) + 1 }, placeOf(line)?.rows ?? null))}
637      </Box>
638    )
639  })
640
641  // A turn end reads the tracking files again and ends no step (M201). A
642  // skill that waits on background work ends its turn, and the work's notice
643  // starts the next one, so a turn end is not the skill's end.
644  on('turn.complete', async ($, e, next) => {
645    reopened = false
646    const result = await next(e)
647    await update($, expanded, () => false)
648    await refresh($)
649    return result
650  })
651
652  // The main loop's Stop ends the running cairn skill's step when nothing is
653  // in flight: `background_tasks` is empty or absent, and no hook beneath
654  // blocked the stop (M201). A Stop with work in flight keeps the step
655  // through the wait, and so does a blocked Stop, after which the turn goes
656  // on. A Stop inside a subagent carries an `agent_id` and keeps the step.
657  // A one-shot entry in `session_crons`, as ScheduleWakeup makes, also keeps
658  // the step, so a skill that waits on a wakeup keeps it (M210). A recurring
659  // cron, as `/loop` makes, does not, since it would keep the step for good.
660  on('classic.Stop', async ($, e, next) => {
661    const result = await next(e)
662    await update($, expanded, () => false)
663    if (e.agent_id !== undefined || result?.block !== undefined) return result
664    const waking = (e.session_crons ?? []).some(cron => cron.recurring === false)
665    if ((e.background_tasks ?? []).length === 0 && !waking) {
666      if (knownStep(await read($, step)) !== null) await update($, ended, () => true)
667      await update($, step, () => null)
668      await refresh($)
669    }
670    return result
671  })
672
673  // A prompt the operator typed, at the terminal or the desktop (`composer`)
674  // or through Remote Control (`bridge`), while the session was idle (no
675  // `turnId`) ends a step that a Stop kept (M201). A background task's
676  // notice, a peer's message, or a prompt typed over a running turn keeps
677  // it. A typed cairn slash command keeps the step its own skill prompt set:
678  // the engine expands the command first, so the prompt finds `expanded`
679  // set. Were the skill prompt to run beneath instead, the step would end
680  // before `next` and the skill prompt would set the new one. So the step
681  // ends before `next`, and a prompt that a hook beneath drops puts it back,
682  // unless something set a new step meanwhile (M210).
683  on('prompt.submit', async ($, e, next) => {
684    const typed = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
685    const fresh = await read($, expanded)
686    await update($, expanded, () => false)
687    if (!typed || e.turnId !== undefined || fresh) return next(e)
688    const before = await read($, step)
689    const hiddenBefore = await read($, dismissed)
690    const endedBefore = await read($, ended)
691    await update($, step, () => null)
692    await update($, ended, () => false)
693    await refresh($)
694    const result = await next(e)
695    // The refresh above can clear a hide made against the old step, so a
696    // drop puts back the close state as well (M210 review).
697    if (result?.drop !== undefined && before !== null) {
698      await update($, step, current => current ?? before)
699      if (hiddenBefore !== null) await update($, dismissed, current => current ?? hiddenBefore)
700      await reconcile($)
701    }
702    // A drop also puts back the Clear Button that a skill's end left, unless
703    // a skill started meanwhile (M216).
704    if (result?.drop !== undefined && endedBefore && (await read($, step)) === null) {
705      await update($, ended, () => true)
706    }
707    return result
708  })
709
710  // A cairn skill's prompt starts its step, the same skill run again
711  // included. The event carries no agent id, so a subagent that loads a
712  // cairn skill starts a step too. The text passes through as is.
713  on('skill.prompt', async ($, e, next) => {
714    const result = await next(e)
715    const skill = cairnSkill(e.skill)
716    if (skill !== null) {
717      await update($, step, () => ({ skill }))
718      await update($, ended, () => false)
719      await update($, expanded, () => true)
720      await refresh($)
721    }
722    return result
723  })
724
725  // A file the session writes under a `cairn/` directory, such as a
726  // milestone file whose box was just checked, reads the files again, so the
727  // track moves inside a long turn (M206 review: the chapter hook, which
728  // M206 removed, had done this at each chapter). The tool's own call goes
729  // through first, and a refused or failed call reads nothing.
730  on('tool.call', { tool: 'Edit' }, afterWrite)
731  on('tool.call', { tool: 'Write' }, afterWrite)
732  on('tool.call', { tool: 'MultiEdit' }, afterWrite)
733
734  // Every session end, a `/clear` or a resume among them, ends the step and
735  // shows a band that a press hid, whatever its reason (M200).
736  on('session.end', async ($, e, next) => {
737    // A `Plan`, `Implement`, or ✎ press's held command is taken first, so a
738    // rejecting `next(e)` below cannot leave it set (M221 review).
739    const queued = heldRun
740    heldRun = null
741    // So is a ⌂ press's mark (M241).
742    const home = homeRun
743    homeRun = null
744    reopened = false
745    // The end ends the start, so the next start reads again (M238).
746    owed = false
747    startRead = false
748    // A press whose checks have not settled is cut off: its checks run
749    // nothing when they settle (M255).
750    ends += 1
751    // The run and the press mark current now are the ones this end frees.
752    // A press made while `next(e)` is pending keeps its own (M260 review).
753    const runAt = runs
754    const checkAt = pressCheck
755    const free = () => {
756      if (runs === runAt) running = false
757      if (pressCheck === checkAt) pressCheck = null
758    }
759    // An `other` end marks this folder for a reopen at the next start
760    // (M222). A `clear` end needs nothing, as no pane closes when the clear
761    // stays in the same process.
762    if (e.reason === 'other') await markReopen($)
763    let result: unknown
764    let failed: { error: unknown } | null = null
765    try {
766      result = await next(e)
767    } catch (error) {
768      failed = { error }
769    }
770    // An end beneath that rejects resets the band as a resolved end does
771    // (M278). A write that rejects stops the resets but none of what
772    // follows, and its error goes on after them unless `next(e)` rejected
773    // first (M278 review).
774    let wrote: { error: unknown } | null = null
775    try {
776      await update($, step, () => null)
777      await update($, expanded, () => false)
778      await update($, dismissed, () => null)
779      await update($, ended, () => false)
780    } catch (error) {
781      wrote = { error }
782    }
783    // A `/clear` from the Clear Button ends the session, and its run may
784    // never settle, so the end frees the action Buttons (M216). So does a
785    // press whose checks have not settled, once the end's own updates are
786    // done, so no press reads the state of the session that ended (M255).
787    // An end beneath that rejects frees them too, so a press whose `/clear`
788    // run never settles leaves none dead (M260).
789    free()
790    // The held command runs now when this end is its `/clear` (M221). The
791    // run is not awaited, so the session end does not wait on the command.
792    // It takes the next run number, so the `/clear` run that settles after
793    // this end does not free a press made while the command runs. Any other
794    // end drops the command, and the prompt box and a toast say so, as for
795    // a refused run (M221 review). An end beneath that rejects drops it
796    // whatever its reason (M260).
797    if (queued !== null) {
798      if (failed !== null) void fallBack($, lineOf(queued.command, queued.args), 'the session end failed')
799      else if (e.reason === 'clear') void run($, queued.command, queued.args)
800      else void fallBack($, lineOf(queued.command, queued.args), 'the session ended before /clear')
801    }
802    // A ⌂ press's `/clear` opens the pane at its end, unawaited as the held
803    // command's run is, and also when the end beneath rejects (M255). Any
804    // other end drops the mark with no open (M241).
805    if (home !== null && e.reason === 'clear') void openHome($)
806    if (failed !== null) throw failed.error
807    if (wrote !== null) throw wrote.error
808    return result
809  })
810
811  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
812    if (e.props.hasSurvey) return next(e)
813    const state = await read($, band)
814    const { rows, workable } = state
815    const current = knownStep(await read($, step))
816    // A row drawn from a found ROADMAP carries the pane's open button
817    // (M205), and with no active or workable row it is the empty row (M213).
818    const { found: canOpen, next: nextStep } = await read($, pane)
819    if (rows.length === 0 && workable.length === 0 && !canOpen) return next(e)
820    const hidden = await read($, dismissed)
821    if (hidden !== null && same(hidden, mark(state, current))) return next(e)
822    const beneath = await next(e)
823    const { Box, Button, Text } = $.ui.resolve(e)
824    // The track draws as the `Svg` element on every surface whose table has
825    // one, the desktop app's among them (M204), and as braille cells in the
826    // terminal (M206). With the image, the row centers its parts, since the
827    // track is taller than text.
828    const Svg = e.surface === 'terminal' ? undefined : $.ui.resolve(e).Svg
829    const center = Svg === undefined ? {} : { alignItems: 'center' as const }
830    const close = CLOSE_COLUMNS + (canOpen ? OPEN_COLUMNS : 0)
831    // The next-step and status Buttons (M212) show while no cairn skill's
832    // step is set and no turn is working, on a row that has room for them
833    // (band.ts `actionsFit`). The track gives up columns to them; without
834    // them the row draws its track or label alone, and the idle row draws
835    // no command in their place (M220). The next step is the
836    // pane's: a milestone's step on a milestone or idle row, and planning
837    // on the empty row (M213).
838    const nextLabel = nextStep == null ? undefined : labelOf(nextStep.action)
839    const canAct = canOpen && nextLabel !== undefined && current === null && e.props.isWorking !== true
840    // Each action Button draws with its chrome, so the terminal draws it as
841    // `[ label ]`: its label and 4 columns. One space follows each. Both take
842    // the `secondary` look: an accent color beside the track's phase colors
843    // clashed at a live look.
844    // The Clear Button (M216) shows with them after a cairn skill ends, and
845    // the row drops it first when the three do not fit.
846    const actionColumns = nextLabel === undefined ? 0 : width(nextLabel) + 4 + 1 + width(STATUS_LABEL) + 4 + 1
847    const clearColumns = width(CLEAR_LABEL) + 4 + 1
848    const tries = !canAct ? [] : (await read($, ended)) ? [actionColumns + clearColumns, actionColumns] : [actionColumns]
849    let acts = false
850    let clears = false
851    let lines: BandLine[] = []
852    for (const taken of tries) {
853      const reserved = close + taken
854      const withActs = stepLines(rows, current, e.props.bodyColumns, reserved, workable, canOpen)
855      if (withActs.length > 0 && actionsFit(withActs[0], e.props.bodyColumns, reserved)) {
856        acts = true
857        clears = taken > actionColumns
858        lines = withActs
859        break
860      }
861    }
862    if (!acts) lines = stepLines(rows, current, e.props.bodyColumns, close, workable, canOpen)
863    const spans = (list: Span[]) =>
864      list.map(span => (
865        <Text wrap="truncate-end" {...style(span)}>
866          {span.text}
867        </Text>
868      ))
869    const track = (line: BandLine) => {
870      if (line.track === undefined) return null
871      if (Svg === undefined) return spans(brailleSpans(line.track.flow, line.track.columns))
872      const px = Math.min(TRACK_PX, line.track.columns * PX_PER_COLUMN)
873      return <Svg source={trackSvg(line.track.flow, px)} alt={line.track.flow.alt} width={px} height={TRACK_H} />
874    }
875
876    // Two groups: the bold id and the title on the left, where the title
877    // gives way first, and the track and the tail on the right, which keep
878    // their width. The engine cuts the title to the room that is left.
879    // A shrinking Box also takes `minWidth: 0`, and the id sits in a Box
880    // that never shrinks. Without both, the desktop app drew a long text at
881    // full width past the edge with no `…`, and the short parts beside it
882    // shrank to nothing (M194). The empty row has no id, so no head (M213).
883    const row = (line: BandLine, isFirst: boolean) => (
884      <Box key={line.key} justifyContent="space-between" {...center}>
885        <Box key={`${line.key}-left`} flexShrink={1} minWidth={0}>
886          {line.id === '' ? null : (
887            <Box key={`${line.key}-head`} flexShrink={0}>
888              <Text wrap="truncate-end" color={GRAY} bold>
889                {line.id}
890              </Text>
891              <Text wrap="truncate-end">{' '}</Text>
892            </Box>
893          )}
894          <Box key={`${line.key}-text`} flexShrink={1} minWidth={0}>
895            <Text wrap="truncate-end" color={GRAY}>
896              {line.title}
897            </Text>
898          </Box>
899        </Box>
900        <Box key={`${line.key}-right`} flexShrink={0} marginLeft={GAP} {...center}>
901          {track(line)}
902          {spans(line.tail)}
903          {isFirst ? (
904            <Text wrap="truncate-end">{' '.repeat(GAP)}</Text>
905          ) : null}
906          {isFirst && clears ? (
907            <Button key="cairn-clear" variant="secondary" label={CLEAR_LABEL} onPress={() => pressClear($)} />
908          ) : null}
909          {isFirst && clears ? <Text wrap="truncate-end">{' '}</Text> : null}
910          {isFirst && acts ? (
911            <Button
912              key="cairn-next"
913              variant="secondary"
914              label={nextLabel}
915              onPress={() => pressNext($, nextLabel)}
916            />
917          ) : null}
918          {isFirst && acts ? <Text wrap="truncate-end">{' '}</Text> : null}
919          {isFirst && acts ? (
920            <Button key="cairn-status" variant="secondary" label={STATUS_LABEL} onPress={() => pressStatus($)} />
921          ) : null}
922          {isFirst && acts ? <Text wrap="truncate-end">{' '}</Text> : null}
923          {isFirst && canOpen ? (
924            <Button
925              key="cairn-open"
926              plain
927              {...(e.surface === 'terminal' ? {} : { dimColor: true })}
928              label={OPEN_GLYPH}
929              onPress={() => openPane($)}
930            />
931          ) : null}
932          {isFirst && canOpen ? <Text wrap="truncate-end">{' '.repeat(OPEN_COLUMNS - width(OPEN_GLYPH))}</Text> : null}
933          {isFirst ? (
934            <Button
935              key="cairn-close"
936              role="dismiss"
937              plain
938              {...(e.surface === 'terminal' ? {} : { dimColor: true })}
939              label={e.surface === 'terminal' ? CLOSE_GLYPH : DESKTOP_CLOSE_GLYPH}
940              onPress={() => dismiss($)}
941            />
942          ) : null}
943        </Box>
944      </Box>
945    )
946
947    return (
948      <Box key="cairn-stack" flexDirection="column">
949        <Box key="cairn-band" flexDirection="column">
950          {/* A Text drops its `key`, so each row's key sits on a Box. */}
951          {lines.map((line, i) => row(line, i === 0))}
952        </Box>
953        {beneath ?? null}
954      </Box>
955    )
956  })
957}
958
959// After an Edit, Write, or MultiEdit call that went through, a path under a
960// `cairn/` directory reads the files again.
961async function afterWrite($, e, next) {
962  const result = await next(e)
963  if (result?.deny !== undefined || result?.isError === true) return result
964  if (typeof e.file_path === 'string' && /(^|[\\/])cairn[\\/]/.test(e.file_path)) await refresh($)
965  return result
966}
967
968// The press reads the rows and the step as they are now, not as they were
969// drawn. It writes only while the close state stands at the version it had
970// before those reads, so a session end that lands between them wins and the
971// band stays shown (M210). Any other write in between drops the press too,
972// and a second press hides the band.
973async function dismiss($) {
974  const held = await $.state.get(DISMISSED_REF)
975  const state = await read($, band)
976  const current = await read($, step)
977  await $.state.set(DISMISSED_REF, { shape: DISMISSED_SHAPE, value: mark(state, current) }, { ifVersion: held.version })
978}
979
980// A press of the band's open button opens the pane. The press is the
981// person's own act, so the surface places the pane at any width.
982// A press has no output line, so an open the surface does not place, or one
983// a hook refuses, says why in a toast. An open that does not throw starts
984// the read of the pull request states (M224), and the press does not wait
985// for it (M230).
986async function openPane($) {
987  try {
988    const opened = await $.ui.open({ id: PANE, title: PANE_TITLE })
989    if (!opened.isPlaced) $.ui.toast(notPlaced(opened.reason))
990  } catch (error) {
991    $.ui.toast(`cairn pane: ${error instanceof Error ? error.message : String(error)}`)
992    return
993  }
994  owed = false
995  void readPrs($)
996}
997
998// The pane as `$.ui.panes()` lists it, or undefined when it is not listed.
999// It throws when that call throws. Every other place that needs the pane's
1000// listing reads it here (M238).
1001async function paneOf($) {
1002  return (await $.ui.panes()).find(open => open.id === PANE)
1003}
1004
1005// The pane as `paneOf` lists it, or null when the call throws (M238).
1006async function listedPane($) {
1007  try {
1008    return await paneOf($)
1009  } catch {
1010    return null
1011  }
1012}
1013
1014// True when `$.ui.panes()` lists the pane placed and shown, false when it
1015// does not or the call throws.
1016async function isShown($): Promise<boolean> {
1017  return placedAndShown(await listedPane($))
1018}
1019
1020// True when a listing of the pane, as `paneOf` or `listedPane` gives it,
1021// is placed and shown. The command's close, `isShown`, and `markReopen`
1022// test the listing here (M256).
1023function placedAndShown(mine: { isPlaced: boolean; isShown: boolean } | null | undefined): boolean {
1024  return mine != null && mine.isPlaced && mine.isShown
1025}
1026
1027// Each read of the pull request states takes the next number, and only the
1028// newest read started writes its words, so an older read that settles
1029// later does not put back older words (M224 review). A reload starts it
1030// over at 0.
1031let prReads = 0
1032
1033// True from a clear or resume start that finds the pane listed but not
1034// placed until the pane's next draw starts the read it owes, the start's
1035// second listing finds the pane placed and reads (M256), an open reads, or
1036// the session ends (M238). A reload starts it over as false.
1037let owed = false
1038
1039// True from the read that a start's reopen, its clear or resume hook, or
1040// the first draw that hook owed starts until the next session end, so the
1041// other hook of the same start starts no second read and owes none (M238).
1042// A reload starts it over as false.
1043let startRead = false
1044
1045// The reads of the pull request states that this module started and that
1046// have not settled (M237). A reload starts it over at 0, as the reload ends
1047// the old module's reads.
1048let inFlight = 0
1049
1050// Reads each blocked row's pull request with one call per URL, side by
1051// side, and writes each state word and its counts by its URL (M224, M225).
1052// A github.com URL takes one `gh api graphql` call for both (`readPr`,
1053// M237), and the URL names the repo, so the call needs no `--repo`. A call
1054// that rejects, as when `gh` cannot start or outruns its timeout, reads as
1055// `unknown` with no counts, as a bad result does (counts.ts `prRead`), and
1056// the read never throws. Threads that fail the shape check leave the word
1057// and draw no counts. It runs only at a pane open, a Refresh press, a
1058// `/clear` or `/resume` while the pane is placed (M230, M237), and the
1059// first draw of a pane that such a start found not placed (M238). A start
1060// reads once: its reopen and its clear or resume hook skip the read when
1061// the other, or the owed draw, already read (M238). No timer and no turn
1062// end starts one, since the operator does not want repeating tasks.
1063// A read that starts while another runs still runs, with the newest URLs.
1064// Words and counts are written together when every call has settled, so a
1065// Refresh keeps the earlier counts drawn until then.
1066// Beside the blocked rows' reads, `readHotfixes` lists the open hotfix pull
1067// requests (M226), and the blocked reads do not wait for it (M230). Once the
1068// list settles, the hotfix URLs that no blocked row names are read. The list
1069// is written with the words.
1070async function readPrs($) {
1071  prReads += 1
1072  const mine = prReads
1073  inFlight += 1
1074  // Each write checks again inside `update`, which retries on a version
1075  // conflict, that no newer read started, so a retried write never undoes a
1076  // newer read's write (M236 review).
1077  try {
1078    await update($, reading, current => (mine === prReads ? true : current))
1079  } catch {
1080    // The ↻ stays, and the read still runs.
1081  }
1082  try {
1083    const urls: string[] = []
1084    for (const row of (await read($, pane)).blocked) {
1085      if (row.url !== null && !urls.includes(row.url)) urls.push(row.url)
1086    }
1087    // One lookup of the root and its base remote's URL serves the hotfix
1088    // list and the card's read (M286). Neither the blocked reads nor the
1089    // words and list they write wait for the card's read, which is written
1090    // last (M286 review, as M230 keeps the blocked reads apart). A lookup
1091    // that rejects rejects both, so nothing is written; the card's
1092    // rejection is held so it is never unhandled.
1093    const where = baseOf($)
1094    const listing = readHotfixes($, where)
1095    const card = readRepo($, where).catch(() => null)
1096    const blocked = urls.map(url => readPr($, url))
1097    const listed = await listing
1098    const more: string[] = []
1099    for (const pr of listed.prs) {
1100      if (!urls.includes(pr.url) && !more.includes(pr.url)) more.push(pr.url)
1101    }
1102    urls.push(...more)
1103    // Each write checks inside `update`, which retries on a version
1104    // conflict, that no newer read started, so a retried write never
1105    // replaces a newer read's value (M236 review, M286 review).
1106    const newest = <T,>(value: T) => (current: T) => (mine === prReads ? value : current)
1107    if (urls.length > 0) {
1108      const reads = await Promise.all([...blocked, ...more.map(url => readPr($, url))])
1109      const out: Record<string, PrRead> = {}
1110      urls.forEach((url, i) => {
1111        out[url] = reads[i]
1112      })
1113      // A newer read that settles between the two writes keeps its list
1114      // (M226 review).
1115      if (mine === prReads) await update($, prs, newest(out))
1116    }
1117    if (mine === prReads) await update($, hotfixes, newest(listed))
1118    const counted = await card
1119    if (counted !== null && mine === prReads) await update($, repo, newest(counted))
1120  } catch {
1121    // No write: the lines keep the words they had.
1122  } finally {
1123    inFlight -= 1
1124    // Only the newest read puts back the ↻, so an older read that settles
1125    // first leaves ⋯ while the newer one runs (M236).
1126    if (mine === prReads) {
1127      try {
1128        await update($, reading, current => (mine === prReads ? false : current))
1129      } catch {
1130        // The stored value stays true, and once no read of this module is
1131        // in flight, the next draw shows ↻ (M237). A change to `inFlight`
1132        // draws nothing, so this asks for the pane to be drawn again (M237
1133        // review). No test covers that redraw.
1134        try {
1135          $.ui.invalidate('ui.render')
1136        } catch {
1137          // The ⋯ stays until something else draws the pane.
1138        }
1139      }
1140    }
1141  }
1142}
1143
1144// One pull request's state word, and its counts when the word says it is
1145// open, as `readPrs` describes. It never rejects. A github.com URL takes one
1146// `gh api graphql` call for both (counts.ts `prRead`, M237). A URL of
1147// another form, as a hotfix's on another host, takes one `gh pr view` call
1148// for its word and merge state (M301) and gets no counts.
1149async function readPr($, url: string): Promise<PrRead> {
1150  const graph = countsArgv(url)
1151  if (graph !== null) {
1152    try {
1153      return prRead(await $.process.run(graph, { timeoutMs: GH_TIMEOUT_MS }))
1154    } catch {
1155      return prRead(null)
1156    }
1157  }
1158  try {
1159    const argv = ['gh', 'pr', 'view', url, '--json', PR_VIEW_FIELDS]
1160    return prViewRead(await $.process.run(argv, { timeoutMs: GH_TIMEOUT_MS }))
1161  } catch {
1162    return prViewRead(null)
1163  }
1164}
1165
1166// The hotfix list to write, read with one `gh pr list` call on the base
1167// remote of the band's repo root (M226). The base remote is the one
1168// `base_remote` in hooks/cairn_common.py picks: `upstream` in guest mode
1169// when `git remote` lists it, else `origin`. The call names the remote's
1170// URL, which `gh` takes as `--repo` (M226 T1), and runs in the root. With
1171// no root or no URL for the base remote, it runs no call, and the list is
1172// empty. A call that fails keeps the last good list when it was read for
1173// the same root, and is empty otherwise. A good read replaces it, an empty
1174// one included. The same result gives the candidate rows that the listed
1175// bodies name (`startedRows`, M252), kept and emptied with the list.
1176async function readHotfixes($, where: Promise<Where>): Promise<CairnHotfixRead> {
1177  const { root, url } = await where
1178  if (root === null) return { root: null, prs: [], started: [] }
1179  if (url === null) return { root, prs: [], started: [] }
1180  let got: HotfixPr[] | null
1181  let started: StartedRow[] | null
1182  try {
1183    const result = await $.process.run(listArgv(url), { cwd: root, timeoutMs: GH_TIMEOUT_MS })
1184    got = hotfixPrs(result)
1185    started = startedRows(result)
1186  } catch {
1187    got = null
1188    started = null
1189  }
1190  if (got !== null && started !== null) return { root, prs: got, started }
1191  const held = await read($, hotfixes)
1192  return held.root === root ? held : { root, prs: [], started: [] }
1193}
1194
1195// The band's repo root, whether it is in guest mode, and its base remote's
1196// URL, read once per `readPrs` (M286). With no root, the URL is null and no
1197// call runs.
1198type Where = { root: string | null; guest: boolean; url: string | null }
1199async function baseOf($): Promise<Where> {
1200  const root = (await read($, band)).root
hooks/status/band.ts 348 lines
1import type { CairnBandHidden, CairnBandMark, CairnStep } from '../../types'
2import type { IconName } from './icons'
3import type { BandRow, BandState, WorkableRow } from './reader'
4
5// The band's one row, as a plain description that register.tsx draws
6// (M206). It shows one active milestone: the first `review` row while
7// /milestone-review runs and one exists, else the first `in-progress` row,
8// else the first `review` row. With no active row, it shows the idle row
9// for the first workable planned milestone, whether or not a cairn skill
10// runs, and with none workable, the empty row where a ROADMAP is found
11// (M213). A milestone or idle row's left side is the bold id and the
12// title, and the empty row's is its text alone. Its right side is the
13// flow track and its percent, the idle row's track alone (M220), or a
14// warning label for a row whose counts cannot be read, and on the empty
15// row nothing but the Buttons register.tsx adds. The track draws as
16// an image on the desktop and as braille cells in the terminal (track.ts),
17// at the width the row leaves it.
18
19// One run of text and its style. The row draws in `inactive`, the theme's
20// gray, but for the warning labels and the terminal track's cells.
21// `icon` names an SVG icon the cairn pane draws in place of the text on a
22// surface with the `Svg` element (M286, icons.ts); the band draws none.
23// `badge` holds a heading's count badge, which the cairn pane draws as an
24// `Svg` pill in place of the text on such a surface (M289, badge.ts).
25// `href` is a web page the cairn pane links the text to off the terminal
26// (M311); the band links none.
27export type Span = {
28  text: string
29  color?: string
30  backgroundColor?: string
31  bold?: boolean
32  icon?: IconName
33  badge?: { count: number }
34  href?: string
35}
36
37export const GRAY = 'inactive'
38
39// The track and the columns it takes: an image of about PX_PER_COLUMN
40// pixels a column on the desktop, one braille cell a column in the
41// terminal.
42export type TrackPart = { flow: Flow; columns: number }
43
44// `track`, when set, draws before the tail.
45export type BandLine = { key: string; id: string; title: string; tail: Span[]; track?: TrackPart }
46
47type Phase = { noun: string }
48
49const PHASES: Record<string, Phase> = {
50  'in-progress': { noun: 'tasks' },
51  review: { noun: 'criteria' },
52}
53
54// The columns between the left and the right group.
55export const GAP = 2
56// The most columns a row keeps for its title when it picks a form: a
57// shorter title needs only its own width.
58export const TEXT_ROOM = 10
59// The most and least columns the track takes. The desktop counts the full
60// TRACK_PX (360) image as TRACK_COLUMNS, at about PX_PER_COLUMN pixels a
61// column (M204). On a milestone row, below MIN_TRACK_COLUMNS the track
62// keeps that width and the title takes less room. The idle row drops its
63// track instead.
64export const TRACK_COLUMNS = 52
65export const MIN_TRACK_COLUMNS = 12
66export const PX_PER_COLUMN = 7
67
68// The cairn skills, by their directories under `skills/`. fixtures.gen.ts
69// lists those directories, and a test holds this list to that one. A
70// running skill shows nothing of its own (M206): /milestone-review picks the
71// row, and a skill's start or end can show a band hidden over a milestone
72// row.
73export const CAIRN_SKILLS: readonly string[] = [
74  'milestone-plan',
75  'milestone-implement',
76  'milestone-review',
77  'hotfix',
78  'cairn-triage',
79  'cairn-release',
80  'milestone',
81  'milestone-brief',
82  'design-interview',
83  'cairn-init',
84  'copilot-review',
85]
86
87// A skill's bare name when it is a cairn skill, from its bare name or its
88// `cairn:` name; null for any other skill.
89export function cairnSkill(name: string): string | null {
90  const bare = name.startsWith('cairn:') ? name.slice('cairn:'.length) : name
91  return CAIRN_SKILLS.includes(bare) ? bare : null
92}
93
94// The step, or null when its skill is not a cairn skill, as a step stored
95// before a reload can name a skill the list has since dropped.
96export function knownStep(step: CairnStep | null): CairnStep | null {
97  return step !== null && CAIRN_SKILLS.includes(step.skill) ? step : null
98}
99
100// What the close button stores at a press, and what a refresh and the
101// drawing compare it with: the ids and statuses of the active rows, in
102// ROADMAP order, `milestone-review` while that skill runs and moves the band
103// off the row it shows with no skill, and the idle row's id while no row is
104// active (M206). The step is read through knownStep, as the drawing reads it
105// (M200). The workable list is left out while a row is active, so a planned
106// row added then keeps the band hidden too. Any other skill draws nothing,
107// so its start or end keeps a hidden band hidden (M206 review).
108export function mark(state: BandState, step: CairnStep | null): CairnBandHidden {
109  const current = knownStep(step)
110  const marks: CairnBandMark[] = state.rows.map(row => ({ id: row.id, status: row.status }))
111  const active = state.rows.length > 0
112  const first = (status: string) => state.rows.find(row => row.status === status)
113  const plain = first('in-progress') ?? first('review')
114  const reviewed = current?.skill === 'milestone-review' ? first('review') : undefined
115  return {
116    marks,
117    skill: reviewed !== undefined && reviewed !== plain ? 'milestone-review' : null,
118    idle: active ? null : (state.workable[0]?.id ?? null),
119  }
120}
121
122export function same(a: CairnBandHidden, b: CairnBandHidden): boolean {
123  return (
124    a.skill === b.skill &&
125    a.idle === b.idle &&
126    a.marks.length === b.marks.length &&
127    a.marks.every((m, i) => m.id === b.marks[i].id && m.status === b.marks[i].status)
128  )
129}
130
131export function phaseOf(row: BandRow): Phase {
132  return PHASES[row.status]
133}
134
135// The flow track (M204): one flow of three equal segments, plan, then
136// implement, then review. track.ts draws it; the model is here.
137export type FlowPhase = 'plan' | 'implement' | 'review'
138export const FLOW_PHASES: readonly FlowPhase[] = ['plan', 'implement', 'review']
139// Each phase's color as a Claude Code theme key (M217), so it changes with
140// the theme: `planMode` for plan, `claude` for implement, and `success` for
141// review. The light theme changes plan and review, and the colorblind and
142// ANSI themes change all three. The desktop track is an image and
143// cannot read theme keys, so it draws from its own palette (track.ts).
144export const FLOW_COLORS: Record<FlowPhase, string> = { plan: 'planMode', implement: 'claude', review: 'success' }
145
146// A segment's fill as a whole-number fraction, so the percent needs no
147// floating point.
148export type Fill = { num: number; den: number }
149
150export type Flow = {
151  // The phase the pill sits on and takes its color from.
152  phase: FlowPhase
153  // Plan, implement, review.
154  fills: [Fill, Fill, Fill]
155  // The items in the implement and review segments. The active segment's
156  // count sets its ticks; 0 draws none.
157  items: [number, number]
158  pill: string
159  // The pill's text on a track too short for `pill`: the count alone,
160  // `none` for a section with no items, or `Planned` on the idle flow
161  // (M206).
162  short: string
163  // The flow's percent, or null on a row that shows none.
164  percent: number | null
165  // What the drawing says, for a reader that cannot see it.
166  alt: string
167}
168
169const FULL: Fill = { num: 1, den: 1 }
170const NONE: Fill = { num: 0, den: 1 }
171
172// A section of zero items is empty.
173function share(checked: number, total: number): Fill {
174  return total === 0 ? NONE : { num: checked, den: total }
175}
176
177// floor(100 × (sum of the fills) / 3), in whole numbers.
178export function percentOf(fills: readonly Fill[]): number {
179  const den = fills.reduce((d, f) => d * f.den, 1)
180  const num = fills.reduce((n, f) => n + f.num * (den / f.den), 0)
181  const top = 100 * num
182  return (top - (top % (3 * den))) / (3 * den)
183}
184
185// A milestone row's flow, or null when its counts cannot be read. Plan is
186// full. An `in-progress` row fills implement by its tasks and leaves review
187// empty; a `review` row fills implement and fills review by its criteria.
188export function flowOf(row: BandRow): Flow | null {
189  const { tasksChecked, tasksTotal, criteriaChecked, criteriaTotal } = row
190  if (tasksChecked === null || tasksTotal === null || criteriaChecked === null || criteriaTotal === null) return null
191  const isTasks = phaseOf(row).noun === 'tasks'
192  const fills: [Fill, Fill, Fill] = isTasks
193    ? [FULL, share(tasksChecked, tasksTotal), NONE]
194    : [FULL, FULL, share(criteriaChecked, criteriaTotal)]
195  const [checked, total, noun] = isTasks ? [tasksChecked, tasksTotal, 'tasks'] : [criteriaChecked, criteriaTotal, 'criteria']
196  const phase: FlowPhase = isTasks ? 'implement' : 'review'
197  const name = isTasks ? 'Implement' : 'Review'
198  const percent = percentOf(fills)
199  const counts = total === 0 ? `no ${noun}` : `${checked}/${total} ${noun}`
200  return {
201    phase,
202    fills,
203    items: [tasksTotal, criteriaTotal],
204    pill: total === 0 ? `no ${noun}` : `${name} ${checked}/${total}`,
205    short: total === 0 ? 'none' : `${checked}/${total}`,
206    percent,
207    alt: `${phase} ${counts}, ${percent}% through plan, implement, review`,
208  }
209}
210
211// The idle row's flow: plan full, the rest empty, no percent.
212export function idleFlow(): Flow {
213  return {
214    phase: 'plan',
215    fills: [FULL, NONE, NONE],
216    items: [0, 0],
217    pill: 'Planned',
218    short: 'Planned',
219    percent: null,
220    alt: 'plan done, implement next',
221  }
222}
223
224// Columns at one per code point: true for ASCII and the band's own glyphs.
225// A wide character in a title, such as a CJK character or an emoji, is
226// undercounted.
227export function width(text: string): number {
228  return [...text].length
229}
230
231const spansWidth = (spans: Span[]) => spans.reduce((n, span) => n + width(span.text), 0)
232
233// The columns of the left group's part that does not shrink: the id and
234// the space after it, or none on the empty row, which has no id.
235function headWidth(id: string): number {
236  return id === '' ? 0 : width(id) + 1
237}
238
239// The columns the title needs to pick a form: its full width, or TEXT_ROOM
240// when that is less.
241function textNeed(title: string): number {
242  return Math.min(width(title), TEXT_ROOM)
243}
244
245// The columns a row leaves the right group, less `tail` and the title's
246// need. `close` is the columns the row's close gap and buttons take.
247function room(columns: number, close: number, line: { id: string; title: string }, tail: Span[]): number {
248  return columns - headWidth(line.id) - textNeed(line.title) - GAP - spansWidth(tail) - close
249}
250
251// The track's columns in that room: at most TRACK_COLUMNS, and at least
252// MIN_TRACK_COLUMNS.
253function trackColumns(left: number): number {
254  return Math.max(MIN_TRACK_COLUMNS, Math.min(TRACK_COLUMNS, left))
255}
256
257// The space between the track and what follows it.
258const SPACE: Span = { text: ' ' }
259
260// The idle row: the bold id and the title, and on the right the track
261// (plan full). Where the row leaves the track too little room, the track
262// goes. The row draws no command: the `Implement` Button register.tsx adds
263// starts the milestone (M220).
264export function idleLines(next: WorkableRow, columns: number, close = 0): BandLine[] {
265  const line = { key: 'idle-row', id: next.id, title: next.title }
266  const left = room(columns, close, line, [])
267  if (left >= MIN_TRACK_COLUMNS) {
268    return [{ ...line, tail: [], track: { flow: idleFlow(), columns: trackColumns(left) } }]
269  }
270  return [{ ...line, tail: [] }]
271}
272
273// The empty row's key and text (M213).
274export const EMPTY_KEY = 'plan-row'
275export const EMPTY_TEXT = 'No milestone ready'
276
277// The empty row (M213), for a found ROADMAP with no active and no workable
278// row: no id, the text, and no track or tail. Its right side is the
279// Buttons register.tsx adds.
280export function emptyLines(): BandLine[] {
281  return [{ key: EMPTY_KEY, id: '', title: EMPTY_TEXT, tail: [] }]
282}
283
284// The band's one row, or none: the first `review` row under
285// /milestone-review, else the first `in-progress` row, else the first
286// `review` row; with no active row, an idle row for the first workable
287// planned row, else the empty row where `found` says a ROADMAP was found,
288// else nothing. `rows` are the active rows in ROADMAP order, and `workable`
289// the workable planned rows in their order. `close` is the columns the
290// close gap and buttons take.
291export function stepLines(
292  rows: BandRow[],
293  step: CairnStep | null,
294  columns: number,
295  close = 0,
296  workable: WorkableRow[] = [],
297  found = false,
298): BandLine[] {
299  const first = (status: string) => rows.find(row => row.status === status)
300  const reviewed = step?.skill === 'milestone-review' ? first('review') : undefined
301  const row = reviewed ?? first('in-progress') ?? first('review')
302  if (row !== undefined) return bandLines(row, columns, close)
303  if (workable.length > 0) return idleLines(workable[0], columns, close)
304  return found ? emptyLines() : []
305}
306
307// One milestone's row: the track and its percent, or a warning label when
308// its counts cannot be read. The track keeps its least width even where
309// that leaves the title less than its room.
310export function bandLines(row: BandRow, columns: number, close = 0): BandLine[] {
311  const line = { key: `${row.id}-row`, id: row.id, title: row.title }
312  const flow = flowOf(row)
313  if (flow === null) {
314    const long: Span[] = [{ text: LONG_WARNING, color: 'warning' }]
315    const short: Span[] = [{ text: 'no file', color: 'warning' }]
316    return [{ ...line, tail: room(columns, close, line, long) >= 0 ? long : short }]
317  }
318  const tail: Span[] = [SPACE, { text: `${flow.percent}%`, color: GRAY }]
319  return [{ ...line, tail, track: { flow, columns: trackColumns(room(columns, close, line, tail)) } }]
320}
321
322// The warning label of a row whose counts cannot be read, at its full width.
323const LONG_WARNING = 'no milestone file'
324
325// Whether a line drawn with `reserved` columns taken for the close gap and
326// all the Buttons has room for the action Buttons (M212): the line has its
327// track, or its long warning label, or is the empty row (M213), and the
328// title keeps its room. The track gives up its columns to the Buttons down
329// to MIN_TRACK_COLUMNS. A line that has its track or its long label keeps it
330// at every wider band, and the title's room then stays at its need or grows,
331// so the widths that show the Buttons are one run up to any wider band.
332export function actionsFit(line: BandLine, columns: number, reserved: number): boolean {
333  const full = line.track !== undefined || line.tail[0]?.text === LONG_WARNING || line.key === EMPTY_KEY
334  if (!full) return false
335  const taken = headWidth(line.id) + GAP + spansWidth(line.tail) + (line.track?.columns ?? 0) + reserved
336  return columns - taken >= textNeed(line.title)
337}
338
339// A line's text with the two groups GAP spaces apart (the least gap a row
340// draws; a wide row spreads them further), for the tests. The track draws
341// as `[track N]`, N its columns.
342export function lineText(line: BandLine): string {
343  const text = (spans: Span[]) => spans.map(s => s.text).join('')
344  const track = line.track === undefined ? '' : `[track ${line.track.columns}]`
345  const head = line.id === '' ? '' : `${line.id} `
346  return `${head}${line.title}${' '.repeat(GAP)}${track}${text(line.tail)}`.trimEnd()
347}
348
hooks/status/counts.ts 118 lines
1// The read of one github.com pull request: its state word (M224), the
2// count under an open pull request's line (M225), and an open pull
3// request's merge state (M301), from one `gh api graphql`
4// call (M237). The count is the review threads not marked resolved. A thread
5// opened by a bot, such as Copilot, counts too. Until M236 a second count
6// showed the reviews and conversation comments that came after the author's
7// last comment, review, or commit. It was dropped because GitHub links no
8// reply to a review, so it counted items that had nothing to answer, such as
9// a Copilot summary review with no threads. The threads are read
10// `last: 100`, so the count covers the newest 100. Until M237 the word came
11// from a `gh pr view` call before this one.
12
13import type { CairnPrRead } from '../../types'
14import { mergeOf, OPEN_WORDS, wordOf } from './pane'
15
16// The counts as the state contract holds them.
17export type PrCounts = NonNullable<CairnPrRead['counts']>
18
19// The threads as the query returns them.
20export type PrNodes = { threads: { isResolved: boolean }[] }
21
22// The query `gh api graphql` runs for one pull request.
23export const COUNTS_QUERY =
24  'query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ' +
25  'state reviewDecision mergeable reviewThreads(last: 100) { nodes { isResolved } } } } }'
26
27// The URL `prUrl` in reader.ts keeps: owner, repo, and number.
28const URL = /^https:\/\/github\.com\/([^/ \t]+)\/([^/ \t]+)\/pull\/([0-9]{1,15})$/
29
30// The `gh api graphql` argv for a pull request URL, null for a URL of
31// another form. The owner and repo go as strings (`-f`) and the number as
32// an Int (`-F`), so an owner named like a number stays a string. The call
33// names `--hostname github.com`, the URL's host, so a `GH_HOST` set to
34// another host does not move it (M237 review).
35export function countsArgv(url: string): string[] | null {
36  const match = URL.exec(url)
37  if (match === null) return null
38  const [, owner, repo, number] = match
39  return [
40    'gh',
41    'api',
42    'graphql',
43    '--hostname',
44    'github.com',
45    '-f',
46    `query=${COUNTS_QUERY}`,
47    '-f',
48    `owner=${owner}`,
49    '-f',
50    `repo=${repo}`,
51    '-F',
52    `number=${number}`,
53  ]
54}
55
56// The count from the returned nodes.
57export function countPr(pr: PrNodes): PrCounts {
58  return { unresolved: pr.threads.filter(t => !t.isResolved).length }
59}
60
61const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)
62
63// A connection's `nodes` list, or undefined when it is not a list of objects.
64function nodesOf(value: unknown): Record<string, unknown>[] | undefined {
65  if (!isObject(value) || !Array.isArray(value.nodes) || !value.nodes.every(isObject)) return undefined
66  return value.nodes as Record<string, unknown>[]
67}
68
69// The `pullRequest` object of a `gh api graphql` reply, or null when the
70// reply has none.
71function pullRequestOf(reply: unknown): Record<string, unknown> | null {
72  if (!isObject(reply) || !isObject(reply.data) || !isObject(reply.data.repository)) return null
73  const pr = reply.data.repository.pullRequest
74  return isObject(pr) ? pr : null
75}
76
77// The nodes of a `gh api graphql` reply, or null when the reply fails the
78// shape check: a null `pullRequest`, threads that are not a list, or a
79// thread whose `isResolved` is not a boolean.
80export function prNodes(reply: unknown): PrNodes | null {
81  const pr = pullRequestOf(reply)
82  if (pr === null) return null
83  const threads = nodesOf(pr.reviewThreads)
84  if (threads === undefined) return null
85  const out: PrNodes = { threads: [] }
86  for (const t of threads) {
87    if (typeof t.isResolved !== 'boolean') return null
88    out.threads.push({ isResolved: t.isResolved })
89  }
90  return out
91}
92
93// The word and count of one `gh api graphql` call, whose result is null
94// when the call rejected. A rejected call, a non-zero exit, text that is not JSON, or a
95// reply with no `pullRequest` reads `unknown` with no count. Otherwise the
96// word comes from `state` and `reviewDecision` (pane.ts `wordOf`). An open
97// word carries the count, which is null when the threads fail the shape
98// check, and the word stands. Any other word carries no count. The merge
99// state comes from `mergeable` (pane.ts `mergeOf`, M301), and threads that
100// fail the shape check leave it standing.
101export function prRead(result: { exitCode: number; stdout: string } | null): CairnPrRead {
102  const none: CairnPrRead = { word: 'unknown', counts: null, mergeable: null }
103  if (result === null || result.exitCode !== 0) return none
104  let reply: unknown
105  try {
106    reply = JSON.parse(result.stdout)
107  } catch {
108    return none
109  }
110  const pr = pullRequestOf(reply)
111  if (pr === null) return none
112  const word = wordOf(pr.state, pr.reviewDecision)
113  const mergeable = mergeOf(word, pr.mergeable)
114  if (!OPEN_WORDS.includes(word)) return { word, counts: null, mergeable }
115  const nodes = prNodes(reply)
116  return { word, counts: nodes === null ? null : countPr(nodes), mergeable }
117}
118
hooks/status/badge.ts 57 lines
1import type { Span } from './band'
2import { GRAY } from './band'
3
4// The count badge on the Blocked, Hotfixes, and Candidates headings
5// (M289), in place of the bare gray count that M286 drew. On the desktop
6// it draws as an `Svg` pill, a rounded rectangle in one gray fill with
7// the number in white. In the terminal it draws as the number with a
8// space on each side, in `inverseText` on `inactive`, the theme's gray:
9// the band terminal pill's text key (track.ts `PILL_TEXT`), but not bold,
10// where that pill is bold. Since M302 the three headings share the one gray, where
11// M289 gave each its own color.
12// An image has no theme signal (ROADMAP "Gaps only the app or mod API can
13// close"), so the fill is a fixed mid gray, dark enough that white reads
14// on it at about 5:1, and light enough to show on a dark ground.
15
16// The terminal badge's ground: the theme's gray, the band's `GRAY`.
17export const BADGE_KEY = GRAY
18
19// The desktop pill's fill and the number's color.
20export const BADGE_FILL = { fill: 'rgb(110,110,110)', text: 'rgb(255,255,255)' }
21
22// The terminal badge's text color.
23export const BADGE_TEXT_KEY = 'inverseText'
24
25// The pill's height in CSS pixels, the estimated width of one digit, and
26// the room left and right of the number together. A system-font digit at
27// 10.5 px is about 6 px wide, so `textLength` stretches it little.
28export const BADGE_H = 16
29export const BADGE_DIGIT = 6
30export const BADGE_PAD = 12
31
32// The pill's width: the number's estimated width and the padding, 18 for
33// one digit, so even a one-digit count draws as a short pill.
34export function badgeWidth(count: number): number {
35  return `${count}`.length * BADGE_DIGIT + BADGE_PAD
36}
37
38// The pill's SVG document. As in the band's pill (track.ts), `textLength`
39// holds the number to the width less the padding, so a wider fallback font
40// squeezes the digits rather than running past the pill's ends.
41export function badgeSvg(count: number): string {
42  const width = badgeWidth(count)
43  const { fill, text } = BADGE_FILL
44  return (
45    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${BADGE_H}" viewBox="0 0 ${width} ${BADGE_H}">` +
46    `<rect class="badge" width="${width}" height="${BADGE_H}" rx="${BADGE_H / 2}" fill="${fill}"/>` +
47    `<text class="badge-text" x="${width / 2}" y="${BADGE_H / 2}" textLength="${width - BADGE_PAD}" lengthAdjust="spacingAndGlyphs" text-anchor="middle" dominant-baseline="central" font-family="-apple-system,system-ui,sans-serif" font-size="10.5" font-weight="650" fill="${text}">${count}</text>` +
48    `</svg>`
49  )
50}
51
52// The badge as a span: the terminal's text and colors, and the badge's
53// count, which the desktop draws as `badgeSvg`.
54export function badgeSpan(count: number): Span {
55  return { text: ` ${count} `, color: BADGE_TEXT_KEY, backgroundColor: BADGE_KEY, badge: { count } }
56}
57
hooks/status/icons.ts 82 lines
1// The cairn pane's marks as small SVG icons on the desktop (M286), drawn
2// like the desktop app's own task list: a filled circle with a check, a
3// circle with three dots, and a dashed circle, all one size. A span that
4// names an icon draws it on a surface with the `Svg` element and its text
5// glyph in the terminal. An image has no theme signal (ROADMAP "Gaps only
6// the app or mod API can close"), so each icon takes a fixed color chosen
7// to read on both the dark and the light theme.
8
9export type IconName =
10  | 'done'
11  | 'current'
12  | 'open'
13  | 'ring'
14  | 'merged'
15  | 'review'
16  | 'attention'
17  | 'closed'
18  | 'high'
19  | 'low'
20  | 'parked'
21  | 'mergeable'
22  | 'conflicts'
23
24// The icon's drawn size in CSS pixels.
25export const ICON_PX = 14
26
27// The fixed colors: a neutral gray, and the implement, review, warning, and
28// error colors near the theme's own (red since M301), and a muted blue for
29// a parked row, so it differs from a gray low row (M305).
30export const ICON_COLORS = {
31  gray: '#8f8f8f',
32  ink: '#1f1f1e',
33  orange: '#d77757',
34  green: '#4eba65',
35  amber: '#d9a21b',
36  red: '#e5534b',
37  blue: '#7f93c4',
38} as const
39
40const RING = (color: string, dash = '') =>
41  `<circle cx="8" cy="8" r="6.5" fill="none" stroke="${color}" stroke-width="1.4"${dash === '' ? '' : ` stroke-dasharray="${dash}"`}/>`
42const DISC = (color: string) => `<circle cx="8" cy="8" r="7" fill="${color}"/>`
43const CHECK = (color: string) =>
44  `<path d="M4.9 8.2 7.1 10.3 11.1 5.9" fill="none" stroke="${color}" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>`
45const DOTS = (color: string) => [5, 8, 11].map(x => `<circle cx="${x}" cy="8" r="0.95" fill="${color}"/>`).join('')
46const LINE = (d: string, color: string) =>
47  `<path d="${d}" fill="none" stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>`
48
49// A merge symbol (M301): a branch from the top node runs down to the bottom
50// node and curves out to the right node.
51const MERGE = (color: string) =>
52  LINE('M5 5V11M5 5.2C5 8 7.6 8 10.1 8', color) +
53  [
54    [5, 3.4],
55    [5, 12.6],
56    [11.7, 8],
57  ]
58    .map(([x, y]) => `<circle cx="${x}" cy="${y}" r="1.6" fill="none" stroke="${color}" stroke-width="1.4"/>`)
59    .join('')
60
61const { gray, ink, orange, green, amber, red, blue } = ICON_COLORS
62const BODIES: Record<IconName, string> = {
63  done: DISC(gray) + CHECK(ink),
64  current: RING(gray) + DOTS(gray),
65  open: RING(gray, '2.2 1.9'),
66  ring: RING(gray),
67  merged: DISC(green) + CHECK(ink),
68  review: RING(gray) + DOTS(gray),
69  attention: DISC(amber) + LINE('M8 4.6V8.7', ink) + `<circle cx="8" cy="11.1" r="0.9" fill="${ink}"/>`,
70  closed: RING(gray) + LINE('M5.8 5.8 10.2 10.2M10.2 5.8 5.8 10.2', gray),
71  high: RING(orange) + LINE('M8 11V5M5.6 7.4 8 5 10.4 7.4', orange),
72  low: RING(gray) + LINE('M8 5V11M5.6 8.6 8 11 10.4 8.6', gray),
73  parked: RING(blue, '2.2 1.9') + LINE('M8 5.2V8.2L9.9 9.4', blue),
74  mergeable: MERGE(green),
75  conflicts: DISC(red) + LINE('M5.8 5.8 10.2 10.2M10.2 5.8 5.8 10.2', ink),
76}
77
78// The icon's SVG document.
79export function iconSvg(name: IconName): string {
80  return `<svg xmlns="http://www.w3.org/2000/svg" width="${ICON_PX}" height="${ICON_PX}" viewBox="0 0 16 16">${BODIES[name]}</svg>`
81}
82
hooks/status/repo.ts 181 lines
1// The summary card's reads (M286): the open pull requests and open issues
2// of the base remote's repo, from one `gh api graphql` call, and the latest
3// release tag, its age, and the milestones done since it, from three git
4// calls, and the project name (M291), from the URL or from one more git
5// call when the URL is not a github.com one, and the repo page (M311), from
6// the URL alone. `readPrs` in register.tsx
7// makes them all, through `readRepo`, at the times it reads the pull
8// request states, and at no other time.
9
10import type { CairnRepoCounts, CairnRepoDone } from '../../types'
11
12// The query `gh api graphql` runs for the repo. `totalCount` counts every
13// open item, with no page limit.
14export const REPO_QUERY =
15  'query($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { ' +
16  'pullRequests(states: OPEN) { totalCount } issues(states: OPEN) { totalCount } } }'
17
18// The github.com remote URL forms, each giving the owner and the repo: the
19// scp-like `[user@]github.com:o/r`, `ssh://[user@]github.com[:port]/o/r`,
20// and `http(s)://[userinfo@]github.com[:port]/o/r`, each with an optional
21// `.git` and trailing `/`. The host matches in any case. An ssh host alias
22// names no host, so it runs no call.
23const REMOTE_FORMS = [
24  /^(?:[^@\s/]+@)?github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i,
25  /^ssh:\/\/(?:[^@/\s]+@)?github\.com(?::[0-9]+)?\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i,
26  /^https?:\/\/(?:[^@/\s]+@)?github\.com(?::[0-9]+)?\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i,
27]
28
29// The owner and repo of a github.com remote URL, or null for any other URL.
30export function remoteRepo(url: string): { owner: string; repo: string } | null {
31  for (const form of REMOTE_FORMS) {
32    const match = form.exec(url)
33    if (match !== null) return { owner: match[1], repo: match[2] }
34  }
35  return null
36}
37
38// The `gh api graphql` argv for a base remote URL, or null for a URL that
39// is not a github.com one, which runs no call. The argv holds only the
40// owner and the repo from the URL, so no userinfo reaches it. It names
41// `--hostname github.com`, as `countsArgv` in counts.ts does.
42export function repoArgv(url: string): string[] | null {
43  const named = remoteRepo(url)
44  if (named === null) return null
45  return [
46    'gh',
47    'api',
48    'graphql',
49    '--hostname',
50    'github.com',
51    '-f',
52    `query=${REPO_QUERY}`,
53    '-f',
54    `owner=${named.owner}`,
55    '-f',
56    `repo=${named.repo}`,
57  ]
58}
59
60const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)
61
62// A connection's `totalCount`, or null when it is not an integer.
63function totalOf(value: unknown): number | null {
64  if (!isObject(value)) return null
65  const total = value.totalCount
66  return typeof total === 'number' && Number.isInteger(total) ? total : null
67}
68
69// The two numbers of one call, whose result is null when the call rejected.
70// A rejected call, a non-zero exit, text that is not JSON, a reply without
71// one or both counts, or a count that is not an integer gives null.
72export function repoCounts(result: { exitCode: number; stdout: string } | null): CairnRepoCounts | null {
73  if (result === null || result.exitCode !== 0) return null
74  let reply: unknown
75  try {
76    reply = JSON.parse(result.stdout)
77  } catch {
78    return null
79  }
80  if (!isObject(reply) || !isObject(reply.data) || !isObject(reply.data.repository)) return null
81  const prs = totalOf(reply.data.repository.pullRequests)
82  const issues = totalOf(reply.data.repository.issues)
83  return prs === null || issues === null ? null : { prs, issues }
84}
85
86// The git argv that names the latest release tag: the newest `v*` tag that
87// `git describe` reaches from HEAD.
88export const DESCRIBE_ARGS = ['describe', '--tags', '--abbrev=0', '--match', 'v*']
89
90// The git argv that lists the milestone files archived since a tag.
91// `--no-renames` lists a file moved into the archive as added, so a file
92// planned before the tag counts, and the pathspec keeps the root archive
93// only, not a fixture tree that holds one.
94export function archivedArgs(tag: string): string[] {
95  return ['diff', '--no-renames', '--diff-filter=A', '--name-only', tag, 'HEAD', '--', 'cairn/milestones/archive/']
96}
97
98// The git argv that prints the tagged commit's time in Unix seconds. The
99// release walk tags the release commit, so its time is the release's. The
100// `--` keeps a path named like the tag from being read as one.
101export function tagTimeArgs(tag: string): string[] {
102  return ['log', '-1', '--format=%ct', tag, '--']
103}
104
105// The git argv that prints the absolute path of the repo's common git dir,
106// which a linked worktree shares with its main working tree (M291).
107export const COMMON_DIR_ARGS = ['rev-parse', '--path-format=absolute', '--git-common-dir']
108
109// The last path segment of a path, split on `/` and `\`, with trailing
110// separators dropped. A path with no segment, such as `/`, gives ''.
111export function lastSegment(path: string): string {
112  const parts = path.split(/[\\/]/).filter(part => part !== '')
113  return parts.length === 0 ? '' : parts[parts.length - 1]
114}
115
116// The project name the card shows (M291) from the base remote's URL, the
117// common git dir call's stdout, and the repo root. The repo part of a
118// github.com URL comes first. Otherwise, when the trimmed common dir's own
119// name is `.git`, the name of the folder that holds it, which is the main
120// working tree's, so a linked worktree shows the repo's name. Otherwise,
121// or when the call failed (null), the root's last segment. Only the last
122// output line counts: a git before 2.31 echoes the unknown
123// `--path-format=absolute` on a line of its own before the dir.
124export function projectName(url: string | null, common: string | null, root: string): string {
125  const named = url === null ? null : remoteRepo(url)
126  if (named !== null) return named.repo
127  const dir = (common ?? '').trim().split(/\r?\n/).pop()?.trim() ?? ''
128  if (lastSegment(dir) === '.git') {
129    const holder = lastSegment(dir.replace(/[\\/]*\.git[\\/]*$/, ''))
130    if (holder !== '') return holder
131  }
132  return lastSegment(root)
133}
134
135// The characters a GitHub owner or repo name holds. `.` and `..` match too,
136// and `webOf` refuses them, since `new URL` would resolve them away.
137const WEB_PART = /^[A-Za-z0-9._-]+$/
138// GitHub's longest owner and repo names, which keep every page `webOf`
139// gives under the 2048 characters a Link's `href` may hold (M311 review).
140const OWNER_MAX = 39
141const REPO_MAX = 100
142
143// The repo page of a github.com base remote URL (M311), which the card's
144// name and counts link to, or null for any other URL, for no URL, and for
145// an owner or repo that `WEB_PART` refuses, that is `.` or `..`, or that is
146// longer than GitHub allows. A Link
147// whose `href` is not spelled as `new URL(href).href` refuses the whole
148// pane, so only such a URL comes back.
149export function webOf(url: string | null): string | null {
150  const named = url === null ? null : remoteRepo(url)
151  if (named === null) return null
152  const fits = (part: string, max: number) => WEB_PART.test(part) && part !== '.' && part !== '..' && part.length <= max
153  if (!fits(named.owner, OWNER_MAX) || !fits(named.repo, REPO_MAX)) return null
154  const web = `https://github.com/${named.owner}/${named.repo}`
155  return new URL(web).href === web ? web : null
156}
157
158const DAY_MS = 86_400_000
159
160// The release read from the guest flag, the three git calls' stdout, each
161// null when its call failed, and the read's start in milliseconds. Null in
162// guest mode, where `cairn/` is never committed, when `git describe` failed
163// or printed nothing, when the `git log` call failed or its trimmed output
164// is not a whole number, and when the `git diff` call failed. The days are
165// whole days from the commit's time to the read's start, rounded down, and
166// 0 for a commit time after it. The count is the diff's non-blank lines.
167export function doneSince(
168  guest: boolean,
169  describe: string | null,
170  log: string | null,
171  diff: string | null,
172  now: number,
173): CairnRepoDone | null {
174  if (guest || describe === null) return null
175  const tag = describe.trim()
176  const seconds = log?.trim() ?? ''
177  if (tag === '' || !/^\d+$/.test(seconds) || diff === null) return null
178  const days = Math.max(0, Math.floor((now - Number(seconds) * 1000) / DAY_MS))
179  return { tag, days, count: diff.split('\n').filter(line => line.trim() !== '').length }
180}
181
hooks/status/pane.ts 980 lines
1import type { CairnHotfixPr, CairnPrMerge, CairnPrRead, CairnPrWord, CairnRepoRead, CairnStartedRow } from '../../types'
2import type { PrCounts } from './counts'
3import type { Span } from './band'
4import type { FlowPhase } from './band'
5import { badgeSpan } from './badge'
6import type { IconName } from './icons'
7import { FLOW_COLORS, flowOf, GRAY, width } from './band'
8import { lastSegment } from './repo'
9import type { BandRow, CandidateRow, NextStep, PaneItem, PaneMilestone, PaneState, TakenRow } from './reader'
10
11// The cairn pane's lines (M205), as a plain description that register.tsx
12// draws. First, the summary card (M286): the project name (M291), the base
13// remote repo's open pull requests and issues, the drawn candidate rows at each level, and the
14// planned, blocked, and done milestones. For each active milestone: its id
15// in its phase's color (no phase word since M236), and its title, with the
16// band's percent for the row at the end of the line when its file reads
17// (M208), its goal, and its tasks and criteria with their boxes. Its
18// newest work-log lines drew too until the M286 live look.
19// Below them: the command that scripts/cairn_next.py recommends, the
20// workable planned milestones, and the planned ones that wait on
21// dependencies. Then the blocked milestones, each with the number of the
22// pull request its header names (M223), and after a read, that pull
23// request's state word and a Button for three of the words (M224), and for
24// an open one with unresolved review threads, a line under it with their
25// number (M225, M236). After a read, the
26// open pull requests that the operator opened from `hotfix-*` branches,
27// each with the same word, counts, and merge mark (M301) and no Button
28// (M226). With no
29// active milestone, the ROADMAP's candidate rows follow, each a priority
30// mark and its short title (M207).
31// A line's `lead` and `tail` keep their width. Its `text` is cut to one
32// line with an ellipsis, but for the goal's lines, which wrap: the operator
33// picked one line per item at the M205 live look, so a long task list fits
34// on one screen.
35// The operator picked the look at the M286 prototypes (look B), in place
36// of the M208 look: the card in a round border, each section heading a bold
37// label, with any count at the right end, a six-cell meter beside the Tasks
38// and Criteria counts, the head line's title bold, the Next command after
39// an arrow with no pill, and one layout for blocked and hotfix lines. At the
40// live look the operator asked for the app's task-list marks, which the
41// desktop draws as icons of one size (icons.ts), and dropped look B's rule
42// after each heading. A milestone's meters take its phase's color, and the
43// Next line takes the color of the phase its command runs. The colors are
44// theme keys (M217). The `card` lines draw in the card's Box. Since M289
45// the Blocked, Hotfixes, and Candidates headings draw their count as a
46// badge (badge.ts), and since M302 the badge is gray and comes right after
47// the label, so only the Tasks and Criteria counts sit at the right end.
48// While no cairn skill runs, the Next line also carries the band's
49// next-step label after the command, which register.tsx draws as a Button
50// (M218). After that Button the line carries Status, which register.tsx
51// draws as a Button (M219). Until M241 it also carried Clear after a cairn
52// skill's end, and the first line's ⌂ took its place. Since M305 no line
53// says that no milestone is active, a planning Next line draws only while
54// the Candidates list draws no row, and a parked row draws in its own blue.
55
56// The Next line's `action`, when set, is the label of the next-step Button
57// drawn after its tail. No other line carries one: register.tsx draws it
58// with the one key `cairn-pane-next` and the next-step press.
59// A line's `buttons` name the Buttons that register.tsx draws after its
60// tail and any action Button, in order: Status on the Next line (M219),
61// and one of Finish, Revise, or Check on a blocked line (M224). A
62// blocked line's `target` is its milestone id, which its Button's key and
63// press carry. Since M236 the pane's first line, the card's first since
64// M286, carries the one Refresh
65// Button, labeled ↻, which reads everything again. Its `tailGrows` makes
66// its tail, the counts after the project name, take the free room, so the
67// Button sits at the right end of the row (M291). Until M236 the Blocked and Hotfixes headings each carried a
68// Refresh. While no cairn skill runs, the Home Button, labeled ⌂, comes
69// before ↻: it clears the conversation and opens the pane again (M241).
70// While no cairn skill runs, each candidate line whose short title is not
71// empty carries the Plan Button, labeled ✎, which plans that row (M242).
72// Its `target` is the line's index among the candidate rows, which the
73// Button's key carries, so two rows with one title draw two keys, and its
74// `title` is the row's short title, which the press carries. A candidate
75// line's `grow` puts ✎ at the right end of the row, and a blocked or
76// hotfix line with a tail grows so its tail sits there too. Off the
77// terminal, register.tsx draws ✎ hidden until the pointer is over its
78// line (M290).
79// A line's `full`, set on each head, task, criterion, workable, waiting,
80// blocked, hotfix, and candidate line, is its whole text, which the desktop
81// shows in a card while the pointer is over the line (M286). On a candidate
82// line the whole text is its row's text after the priority token, not the
83// short title the line draws (M293). A candidate line with a `full` sets
84// `info`, and there the desktop shows the card only
85// while the pointer is over its info glyph `ⓘ`, which shows on line hover,
86// beside ✎ when the line has one (M290).
87export type PaneButton = 'home' | 'status' | 'refresh' | 'finish' | 'revise' | 'check' | 'plan'
88export type PaneLine = {
89  key: string
90  indent: number
91  lead: Span[]
92  text: Span | null
93  tail?: Span[]
94  wraps?: true
95  card?: true
96  full?: string
97  info?: true
98  rowsAbove?: number
99  action?: string
100  buttons?: PaneButton[]
101  target?: string
102  title?: string
103  grow?: true
104  tailGrows?: true
105}
106
107// A blocked milestone's pull request state, as `wordOf` maps it from a
108// `gh api graphql` reply (counts.ts `prRead`, M237) or, for a URL on
109// another host, from a `gh pr view <url> --json` call with
110// `PR_VIEW_FIELDS` (`prViewRead`, M224, M301). The state contract holds the
111// one list of words.
112export type PrWord = CairnPrWord
113
114// One read of a pull request: its word, and its counts while it is open
115// and its threads passed the shape check (M225, M237), and its merge state
116// while it is open and GitHub knows it (M301).
117export type PrRead = CairnPrRead
118
119// An open pull request's merge state (M301).
120export type PrMerge = CairnPrMerge
121
122// The words `wordOf` gives an OPEN pull request, the ones that carry
123// counts (M225, M237) and a merge state (M301).
124export const OPEN_WORDS: readonly PrWord[] = ['changes requested', 'approved', 'in review']
125
126// The fields a `gh pr view` call reads for a URL that is not a github.com
127// pull URL (M224, `mergeable` since M301).
128export const PR_VIEW_FIELDS = 'state,reviewDecision,mergeable'
129
130// The merge state of a pull request with this word and this `mergeable`
131// value (M301). Only a word in `OPEN_WORDS` carries one. MERGEABLE reads
132// `mergeable` and CONFLICTING reads `conflicts`. UNKNOWN, which GitHub
133// answers while it computes the value, and any other value read null.
134export function mergeOf(word: PrWord, mergeable: unknown): PrMerge | null {
135  if (!OPEN_WORDS.includes(word)) return null
136  if (mergeable === 'MERGEABLE') return 'mergeable'
137  if (mergeable === 'CONFLICTING') return 'conflicts'
138  return null
139}
140
141// The count line's text, or null when the count is zero. One thread reads
142// in the singular (M225, M236).
143export function countsText(counts: PrCounts): string | null {
144  if (counts.unresolved === 0) return null
145  return `${counts.unresolved} unresolved ${counts.unresolved === 1 ? 'thread' : 'threads'}`
146}
147
148// The read of one `gh pr view --json` call with `PR_VIEW_FIELDS`, null
149// for a call that rejected: its word, no counts, and the merge state as
150// `mergeOf` gives it (M301; the word alone was `prWord`'s until then). A
151// non-zero exit, text that is not a JSON object, or a `state` other than
152// MERGED, CLOSED, or OPEN reads as `unknown`. An OPEN pull request reads
153// by its `reviewDecision`, and any decision but CHANGES_REQUESTED or
154// APPROVED, an empty or absent one included, reads as `in review`.
155export function prViewRead(result: { exitCode: number; stdout: string } | null): PrRead {
156  const none: PrRead = { word: 'unknown', counts: null, mergeable: null }
157  if (result === null || result.exitCode !== 0) return none
158  let view: unknown
159  try {
160    view = JSON.parse(result.stdout)
161  } catch {
162    return none
163  }
164  if (view === null || typeof view !== 'object') return none
165  const { state, reviewDecision, mergeable } = view as { state?: unknown; reviewDecision?: unknown; mergeable?: unknown }
166  const word = wordOf(state, reviewDecision)
167  return { word, counts: null, mergeable: mergeOf(word, mergeable) }
168}
169
170// The state word of a pull request's `state` and `reviewDecision`, as
171// `prViewRead` reads them from `gh pr view` and `prRead` in counts.ts from
172// `gh api graphql` (M237), which give the same values.
173export function wordOf(state: unknown, reviewDecision: unknown): PrWord {
174  if (state === 'MERGED') return 'merged'
175  if (state === 'CLOSED') return 'closed'
176  if (state !== 'OPEN') return 'unknown'
177  if (reviewDecision === 'CHANGES_REQUESTED') return 'changes requested'
178  if (reviewDecision === 'APPROVED') return 'approved'
179  return 'in review'
180}
181
182// An open pull request from a `hotfix-*` branch (M226).
183export type HotfixPr = CairnHotfixPr
184
185// The head branch prefix of a hotfix (tracking-rules git model).
186export const HOTFIX_PREFIX = 'hotfix-'
187
188// The hotfix pull requests of one `gh pr list --json
189// number,title,url,headRefName` result, in the order it lists them, or
190// null for a call that rejected, exited non-zero, or printed something
191// other than a JSON array (M226). An entry that is not an object, or has no
192// string `headRefName`, no string `url`, or no integer `number`, is
193// skipped, and so is one whose branch does not start with `hotfix-`, and a
194// second entry with a URL or number already kept, so no two lines share a
195// key (M226 review). A title that is not a string reads as empty.
196export function hotfixPrs(result: { exitCode: number; stdout: string } | null): HotfixPr[] | null {
197  if (result === null || result.exitCode !== 0) return null
198  let list: unknown
199  try {
200    list = JSON.parse(result.stdout)
201  } catch {
202    return null
203  }
204  if (!Array.isArray(list)) return null
205  const out: HotfixPr[] = []
206  for (const entry of list) {
207    if (entry === null || typeof entry !== 'object') continue
208    const { number, title, url, headRefName } = entry as Record<string, unknown>
209    if (typeof headRefName !== 'string' || !headRefName.startsWith(HOTFIX_PREFIX)) continue
210    if (typeof url !== 'string' || typeof number !== 'number' || !Number.isInteger(number)) continue
211    if (out.some(pr => pr.url === url || pr.number === number)) continue
212    out.push({ number, title: typeof title === 'string' ? title : '', url })
213  }
214  return out
215}
216
217// One `Candidate row: <short title>` line of an open pull request's body,
218// with that pull request's number (M252). `/hotfix` and `/milestone-review`
219// write one such line per candidate row their merge removes or narrows.
220export type StartedRow = CairnStartedRow
221
222// The prefix a body line opens with to name a candidate row (M252).
223export const STARTED_PREFIX = 'Candidate row: '
224
225// A body line that opens or closes a fenced code block: three backticks
226// or three tildes after optional spaces (M257).
227const FENCE_LINE = /^ *(```|~~~)/
228
229// The started items of one `gh pr list --json
230// number,title,url,headRefName,body` result, in the order it lists them,
231// or null for a call that rejected, exited non-zero, or printed something
232// other than a JSON array, as `hotfixPrs` reads it (M252). Every entry with
233// an integer `number` and a string `body` counts, whatever its head
234// branch. Each body line, split on `\n` with a trailing `\r` removed, that
235// opens with exactly `Candidate row: ` gives one item, its title the rest
236// trimmed as `candidateRows` trims a title. A blank rest gives none. A
237// line between a fence line and the next fence line gives none (M257):
238// any fence line closes an open fence, and each body starts with no fence
239// open.
240export function startedRows(result: { exitCode: number; stdout: string } | null): StartedRow[] | null {
241  if (result === null || result.exitCode !== 0) return null
242  let list: unknown
243  try {
244    list = JSON.parse(result.stdout)
245  } catch {
246    return null
247  }
248  if (!Array.isArray(list)) return null
249  const out: StartedRow[] = []
250  for (const entry of list) {
251    if (entry === null || typeof entry !== 'object') continue
252    const { number, body } = entry as Record<string, unknown>
253    if (typeof body !== 'string' || typeof number !== 'number' || !Number.isInteger(number)) continue
254    let fenced = false
255    for (const raw of body.split('\n')) {
256      const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
257      if (FENCE_LINE.test(line)) {
258        fenced = !fenced
259        continue
260      }
261      if (fenced || !line.startsWith(STARTED_PREFIX)) continue
262      const title = line.slice(STARTED_PREFIX.length).trim()
263      if (title !== '') out.push({ title, number })
264    }
265  }
266  return out
267}
268
269// What marks the candidate row with this short title as started (M258):
270// `numbers` the pull requests whose bodies name it and the `#<n>` tokens
271// whose n the open hotfix list holds, in no order, and `ids` its
272// `M<NNN>` tokens (the reader keeps only those whose milestone is
273// `planned` or `blocked`), lowest first. A row with an empty short title
274// has none.
275export function startedRefs(
276  title: string,
277  taken: TakenRow[],
278  hotfixes: HotfixPr[],
279  started: StartedRow[],
280): { numbers: number[]; ids: string[] } {
281  if (title === '') return { numbers: [], ids: [] }
282  const mine = taken.filter(item => item.title === title)
283  const numbers = [
284    ...started.filter(item => item.title === title).map(item => item.number),
285    ...mine
286      .filter(item => item.ref.startsWith('#'))
287      .map(item => Number(item.ref.slice(1)))
288      .filter(number => hotfixes.some(pr => pr.number === number)),
289  ]
290  const ids = mine
291    .filter(item => item.ref.startsWith('M'))
292    .map(item => item.ref)
293    .sort((a, b) => Number(a.slice(1)) - Number(b.slice(1)))
294  return { numbers, ids }
295}
296
297// The candidate row's short title that the next step names while planning
298// (M272, M273): the first `[high]` row with a short title that the
299// Candidates list draws, under the list's own test (`startedRefs` over the
300// counted tokens, the open hotfix list, and the PR bodies that name a row),
301// so the Plan press never names a hidden row or passes over a drawn one.
302// Since M305 the pane's Next line, and with it its Plan press, draws only
303// while the list draws no row, so the pick reaches the band's Plan press
304// alone. Null outside planning, or
305// when the list draws no such row. The reader's `next.title` counts every
306// `#` token and reads no PR body, as scripts/cairn_next.py does.
307export function nextTitle(
308  next: NextStep,
309  candidates: CandidateRow[],
310  taken: TakenRow[],
311  hotfixes: HotfixPr[],
312  started: StartedRow[],
313): string | null {
314  if (next.id !== null || next.command !== '/milestone-plan') return null
315  const row = candidates.find(row => {
316    if (row.priority !== 'high' || row.title === '') return false
317    const { numbers, ids } = startedRefs(row.title, taken, hotfixes, started)
318    return numbers.length === 0 && ids.length === 0
319  })
320  return row?.title ?? null
321}
322
323// The Button a blocked line carries for its state word (M224), from three
324// of the routes that /milestone gives a handed-off PR: a merged one goes to
325// review's hygiene, one with changes requested back to implement, and a
326// closed one to /milestone. The other words carry none. An archived row
327// keeps only Finish (M246), since its milestone file is gone.
328export const PR_BUTTON: Partial<Record<PrWord, PaneButton>> = {
329  merged: 'finish',
330  'changes requested': 'revise',
331  closed: 'check',
332}
333
334// A state word's color: the review phase's for a merged or approved pull
335// request, the warning key for one with changes requested, gray otherwise.
336function prColor(word: PrWord): string {
337  if (word === 'merged' || word === 'approved') return FLOW_COLORS.review
338  if (word === 'changes requested') return WARNING
339  return GRAY
340}
341
342// The next-step Button's label by the action that scripts/cairn_next.py
343// names (M212), planning among them (M213). The band and the pane read
344// this one map (M218).
345export const PLAN_LABEL = 'Plan'
346export const NEXT_LABELS: Record<string, string> = {
347  review: 'Review',
348  resume: 'Resume',
349  implement: 'Implement',
350  'plan the next milestone': PLAN_LABEL,
351}
352
353// The actions whose next-step Button runs `/clear` first and its command in
354// the cleared conversation (M221): `Implement` and `Plan`. A resumed run
355// and a review keep their conversation. Each is a key of `NEXT_LABELS`.
356export const CLEARS_FIRST: readonly string[] = ['implement', 'plan the next milestone']
357
358// An action's label, read from the map's own keys only, so an action named
359// like an object property, such as `toString`, has none (M218 review).
360export function nextLabel(action: string): string | undefined {
361  return Object.prototype.hasOwnProperty.call(NEXT_LABELS, action) ? NEXT_LABELS[action] : undefined
362}
363
364// The Status and Clear Buttons' labels (M212, M216). The band reads both,
365// and the pane's Next line reads Status (M219, M241).
366export const STATUS_LABEL = 'Status'
367export const CLEAR_LABEL = 'Clear'
368// The pane's Refresh Button (M224, one ↻ on the first line since M236),
369// its label while a read of the pull request states runs (M236), and a
370// blocked line's Buttons (M224).
371export const REFRESH_LABEL = '↻'
372// The pane's Home Button, before ↻ on the first line (M241).
373export const HOME_LABEL = '⌂'
374// A candidate line's Plan Button (M242).
375export const PLAN_CANDIDATE_LABEL = '✎'
376// A candidate line's info glyph, which opens its card on the desktop (M290).
377export const INFO_LABEL = 'ⓘ'
378
379// Where a candidate line's card opens (M294): `up` above its row, as every
380// other card does, or `down` below it, with `rows` the rows a cut card's
381// text is fitted to (`cardCut`), else null. A null place draws no card.
382export type CardPlace = { side: 'up' | 'down'; rows: number | null } | null
383
384// The fewest rows a cut card keeps: its two border rows and one of text.
385export const CARD_MIN_ROWS = 3
386
387// A card of `need` rows opens above its row when the `above` rows there
388// hold it, else below when the `below` rows hold it. Otherwise it opens on
389// the side with more rows, above on a tie, cut to that side's rows, and a
390// side of fewer than CARD_MIN_ROWS rows draws no card (M294).
391export function cardPlace(need: number, above: number, below: number): CardPlace {
392  if (need <= above) return { side: 'up', rows: null }
393  if (need <= below) return { side: 'down', rows: null }
394  const side = above >= below ? 'up' : 'down'
395  const rows = side === 'up' ? above : below
396  return rows < CARD_MIN_ROWS ? null : { side, rows }
397}
398
399// What the Pane render's props say about its body (M294): its width, the
400// first row its window shows, the rows the window may show, and where the
401// surface seated it.
402export type PaneView = { bodyColumns: number; offset: number; bodyRows: number; placement: 'dock' | 'inline' }
403
404// Where each candidate line's card opens, by line key (M294). The line's
405// row in the window is its `rowsAbove` less the window's offset. In a dock
406// the room is the body's rows. Inline, the frame fits the tree, so the room
407// is the fewer of the body's rows and the tree's rows (its lines and the
408// summary card's two border rows).
409export function cardPlaces(lines: PaneLine[], view: PaneView): Record<string, CardPlace> {
410  const room = view.placement === 'dock' ? view.bodyRows : Math.min(view.bodyRows, lines.length + 2)
411  const out: Record<string, CardPlace> = {}
412  for (const line of lines) {
413    if (line.info !== true || line.full === undefined || line.rowsAbove === undefined) continue
414    const row = line.rowsAbove - view.offset
415    out[line.key] = cardPlace(cardRows(line.full, view.bodyColumns), row, room - row - 1)
416  }
417  return out
418}
419
420// The card's border and padding take 4 of the pane's columns.
421export const CARD_FRAME_COLUMNS = 4
422
423// An estimate of the rows a card's text takes in a pane `columns` wide
424// (M294): a greedy wrap at runs of spaces, a word longer than a row split
425// across rows, plus the card's two border rows. Columns are code points, as
426// `width` counts them, and the desktop's own wrap can differ.
427export function cardRows(text: string, columns: number): number {
428  const room = Math.max(1, columns - CARD_FRAME_COLUMNS)
429  let rows = 0
430  let used = 0
431  for (const word of text.split(/ +/).filter(each => each !== '')) {
432    const wide = width(word)
433    if (wide > room) {
434      if (used > 0) rows += 1
435      rows += Math.floor(wide / room)
436      used = wide % room
437    } else if (used === 0) {
438      used = wide
439    } else if (used + 1 + wide <= room) {
440      used += 1 + wide
441    } else {
442      rows += 1
443      used = wide
444    }
445  }
446  if (used > 0) rows += 1
447  return rows + 2
448}
449
450// A cut card's text (M294, amended after the live look): `text` as it is
451// when `cardRows` fits it in `rows`, else its longest run of words from the
452// start that fits with ` …` after it, then ` …`, or `…` alone. Adding a
453// word never lowers `cardRows`, so the scan stops at the first word that
454// does not fit. The card sets no height, so the desktop's own wrap, which
455// can differ, leaves no empty rows.
456export function cardCut(text: string, rows: number, columns: number): string {
457  if (cardRows(text, columns) <= rows) return text
458  const words = text.split(/ +/).filter(each => each !== '')
459  let kept = 0
460  while (kept < words.length && cardRows(`${words.slice(0, kept + 1).join(' ')} …`, columns) <= rows) kept += 1
461  return kept === 0 ? '…' : `${words.slice(0, kept).join(' ')} …`
462}
463export const READING_LABEL = '⋯'
464export const FINISH_LABEL = 'Finish'
465export const REVISE_LABEL = 'Revise'
466export const CHECK_LABEL = 'Check'
467
468export const NO_ROADMAP = 'no cairn ROADMAP found'
469export const NO_FILE = 'no milestone file'
470// A task or criterion's marks (M286), as the desktop app's own task list
471// draws them, at the operator's direction after the pick: a checked box is
472// a filled circle with a check, an open one a dashed circle, and the first
473// open task of an `in-progress` milestone, the one being worked, a circle
474// with three dots. Each names its icon (icons.ts), which the desktop draws
475// in place of the glyph, so every mark is one size there; the terminal
476// draws the glyph.
477export const CHECKED_MARK = '●'
478export const ITEM_OPEN_MARK = '◌'
479export const CURRENT_MARK = '⊙'
480// The empty circle a normal candidate row draws (M253), which a blocked or
481// hotfix line also draws before a read (M286).
482export const OPEN_MARK = '○'
483// A parked row's color (M305): the theme's `permission` blue, so a parked
484// row differs from a gray low row. Its desktop icon draws in the icons'
485// fixed blue (icons.ts).
486export const PARKED_KEY = 'permission'
487// A candidate row's mark for each priority (M207). A normal row's mark is
488// the empty circle `OPEN_MARK` (M253). Each names its icon (M286).
489export const PRIORITY_MARK: Record<CandidateRow['priority'], Span> = {
490  high: { text: '↑', color: FLOW_COLORS.implement, bold: true, icon: 'high' },
491  normal: { text: OPEN_MARK, icon: 'ring' },
492  low: { text: '↓', color: GRAY, icon: 'low' },
493  // A parked row waits on a promotion condition that has not held (M284).
494  // Its mark and title draw in `PARKED_KEY`, where M284 drew them gray like
495  // a low row's (M305).
496  parked: { text: '⧗', color: PARKED_KEY, icon: 'parked' },
497}
498// The order the Candidates list draws each priority in (M280), the parked
499// rows last (M284).
500const LEVEL_RANK: Record<CandidateRow['priority'], number> = { high: 0, normal: 1, low: 2, parked: 3 }
501// The meter's cells, filled and empty, and how many it draws (M208, look B
502// in M286).
503export const METER_FULL = '━'
504export const METER_EMPTY = '─'
505export const METER_CELLS = 6
506// The empty cells' theme key, as the band's terminal track marks use (M208 review).
507export const METER_EMPTY_KEY = 'subtle'
508// The room after an item's mark: two spaces, for the operator's ask for
509// more space after the pick (M286).
510export const ITEM_GAP = '  '
511// The warning text's theme key, as the band's warning labels use.
512const WARNING = 'warning'
513// The Next line's mark before its command (M286).
514export const NEXT_MARK = '→ '
515// The identifier a hotfix line draws where a blocked line draws its
516// milestone id (M286).
517export const HOTFIX_ID = 'fix'
518// A pull request line's state mark for each word, in the word's color, and
519// for a line with no read yet, each with its icon (M286).
520export const PR_MARK: Record<PrWord, { text: string; icon: IconName }> = {
521  merged: { text: '●', icon: 'merged' },
522  approved: { text: '●', icon: 'merged' },
523  'changes requested': { text: '▲', icon: 'attention' },
524  'in review': { text: '◐', icon: 'review' },
525  closed: { text: '✕', icon: 'closed' },
526  unknown: { text: '◌', icon: 'open' },
527}
528export const UNREAD_MARK = { text: OPEN_MARK, icon: 'ring' as IconName }
529// An open pull request's merge state mark, last in its line's tail (M301):
530// a green merge symbol when it can merge, a red disc with a cross when it
531// has conflicts, each with the glyph the terminal draws in its place.
532export const MERGE_MARK: Record<PrMerge, Span> = {
533  mergeable: { text: '✓', color: FLOW_COLORS.review, icon: 'mergeable' },
534  conflicts: { text: '✗', color: 'error', icon: 'conflicts' },
535}
536// The card's line keys (M286), and the text a number draws as before a read
537// gives it.
538export const CARD_KEYS = {
539  repo: 'card-repo',
540  candidates: 'card-candidates',
541  milestones: 'card-milestones',
542  release: 'card-release',
543} as const
544export const UNKNOWN_NUMBER = '?'
545
546// A milestone's id draws in its phase's color, with no phase word, which
547// the operator dropped at the M236 live look.
548const PHASE_COLOR: Record<string, string> = {
549  'in-progress': FLOW_COLORS.implement,
550  review: FLOW_COLORS.review,
551}
552// The phase each recommended command runs, for the Next line's color.
553export const COMMAND_PHASE: Record<string, FlowPhase> = {
554  '/milestone-plan': 'plan',
555  '/milestone-implement': 'implement',
556  '/milestone-review': 'review',
557}
558
559const line = (key: string, indent: number, lead: Span[], text: Span | null = null): PaneLine => ({
560  key,
561  indent,
562  lead,
563  text,
564})
565
566// One blank row, before each section heading, each milestone after the
567// first, and Next.
568const gap = (key: string) => line(key, 0, [], { text: ' ' })
569
570// The filled share of the meter: none only with no box checked, and all
571// only with every box checked.
572export function meterFill(checked: number, total: number): number {
573  if (total === 0 || checked === 0) return 0
574  if (checked >= total) return METER_CELLS
575  return Math.min(METER_CELLS - 1, Math.max(1, Math.round((METER_CELLS * checked) / total)))
576}
577
578export function meter(checked: number, total: number, color: string): Span[] {
579  const fill = meterFill(checked, total)
580  return [
581    { text: METER_FULL.repeat(fill), color },
582    { text: METER_EMPTY.repeat(METER_CELLS - fill), color: METER_EMPTY_KEY },
583  ].filter(span => span.text !== '')
584}
585
586// A section heading and the blank row before it (M286): the label in bold,
587// and an empty text that grows, so the heading's tail, where it has one,
588// sits at the right end after a space. Look B's rule after the label was
589// dropped at the live look, where the desktop drew it as two lines.
590function heading(key: string, label: string, tail: Span[] = []): PaneLine[] {
591  const head: PaneLine = { ...line(key, 0, [{ text: label, bold: true }], { text: '' }), grow: true }
592  if (tail.length > 0) head.tail = [{ text: ' ' }, ...tail]
593  return [gap(`${key}-gap`), head]
594}
595
596// A heading with its count as a badge (M289, badge.ts) right after the
597// label and a space, in its lead, with no tail (M302, where M289 put the
598// badge at the right end). The badge is on the theme's gray in the
599// terminal and in a fixed gray fill on the desktop, where M286 drew a gray
600// number.
601function countHeading(key: string, label: string, count: number): PaneLine[] {
602  const [blank, head] = heading(key, label)
603  return [blank, { ...head, lead: [...head.lead, { text: ' ' }, badgeSpan(count)] }]
604}
605
606// A heading whose tail is the checked and total counts and the meter in
607// the phase's color.
608function counted(key: string, label: string, list: PaneItem[], color: string): PaneLine[] {
609  const checked = list.filter(item => item.checked).length
610  return heading(key, label, [{ text: `${checked}/${list.length} `, color: GRAY }, ...meter(checked, list.length, color)])
611}
612
613// The item lines. `current` is the index of the item that draws
614// `CURRENT_MARK`, or -1 for none.
615function items(prefix: string, list: PaneItem[], current = -1): PaneLine[] {
616  return list.map((item, i) => {
617    const mark: Span = item.checked
618      ? { text: CHECKED_MARK, color: GRAY, icon: 'done' }
619      : i === current
620        ? { text: CURRENT_MARK, icon: 'current' }
621        : { text: ITEM_OPEN_MARK, color: GRAY, icon: 'open' }
622    return {
623      ...line(`${prefix}-${i}`, 2, [mark, { text: ITEM_GAP }], item.checked ? { text: item.text, color: GRAY } : { text: item.text }),
624      full: item.text,
625    }
626  })
627}
628
629// A list item's opening marker: `- `, `* `, or digits and `. ` (M286).
630const LIST_MARK = /^([-*] |\d+\. )/
631
632// The goal's paragraphs and list items, each one string, so the pane wraps
633// them at its own width and not at the file's line breaks (M286). Each line
634// is trimmed. A line joins the one above it with one space, unless a blank
635// line comes between them or its trimmed text opens with a list marker. One
636// or more blank lines give one empty string between blocks.
637export function goalBlocks(goal: string): string[] {
638  const out: string[] = []
639  let open = false
640  let blank = false
641  for (const raw of goal.split('\n')) {
642    const text = raw.trim()
643    if (text === '') {
644      if (out.length > 0) blank = true
645      open = false
646      continue
647    }
648    if (blank) {
649      out.push('')
650      blank = false
651    }
652    if (open && !LIST_MARK.test(text)) {
653      out[out.length - 1] = `${out[out.length - 1]} ${text}`
654    } else {
655      out.push(text)
656      open = true
657    }
658  }
659  return out
660}
661
662function milestoneLines(row: PaneMilestone, band: BandRow | undefined): PaneLine[] {
663  const phase = { color: PHASE_COLOR[row.status] ?? GRAY }
664  // The id bold in the phase's color and the title bold (M286, look B).
665  const head = line(`${row.id}-head`, 0, [{ text: row.id, color: phase.color, bold: true }, { text: '  ' }], {
666    text: row.title,
667    bold: true,
668  })
669  head.full = row.title
670  const file = row.file
671  // The band's percent for the row, from its own counts, which count a box
672  // inside an HTML comment where the pane's items do not.
673  const flow = file === null || band === undefined ? null : flowOf(band)
674  if (flow !== null && flow.percent !== null) head.tail = [{ text: '  ' }, { text: `${flow.percent}%`, color: GRAY }]
675  const out: PaneLine[] = [head]
676  if (file === null) return [...out, line(`${row.id}-nofile`, 2, [], { text: NO_FILE, color: WARNING })]
677  if (file.goal !== '') {
678    out.push(...heading(`${row.id}-goal-head`, 'Goal'))
679    // One wrapping line per paragraph or list item (M286). The blank row
680    // between paragraphs draws as one space, so it keeps its row.
681    goalBlocks(file.goal).forEach((text, i) =>
682      out.push({ ...line(`${row.id}-goal-${i}`, 2, [], { text: text === '' ? ' ' : text }), wraps: true }),
683    )
684  }
685  if (file.tasks.length > 0) {
686    out.push(...counted(`${row.id}-tasks-head`, 'Tasks', file.tasks, phase.color))
687    // While the milestone is `in-progress`, its first open task is the one
688    // being worked (M286).
689    const current = row.status === 'in-progress' ? file.tasks.findIndex(item => !item.checked) : -1
690    out.push(...items(`${row.id}-task`, file.tasks, current))
691  }
692  if (file.criteria.length > 0) {
693    out.push(...counted(`${row.id}-criteria-head`, 'Criteria', file.criteria, phase.color))
694    out.push(...items(`${row.id}-criterion`, file.criteria))
695  }
696  // The work log draws no section since the M286 live look, where the
697  // operator found its one-row lines added little; the file holds it.
698  return out
699}
700
701// The candidate rows that the Candidates list draws, each with its index in
702// `state.candidates`, high rows first, then normal, low, and parked (M280,
703// M284), each level in ROADMAP order. A row that `startedRefs` marks is left
704// out (M261). The card counts the same rows, so the list and the card share
705// this one filter (M286).
706export function drawnCandidates(
707  state: PaneState,
708  hotfixes: HotfixPr[],
709  started: StartedRow[],
710): { row: CandidateRow; i: number }[] {
711  return state.candidates
712    .map((row, i) => ({ row, i }))
713    .filter(({ row }) => {
714      const { numbers, ids } = startedRefs(row.title, state.taken, hotfixes, started)
715      return numbers.length === 0 && ids.length === 0
716    })
717    .sort((a, b) => LEVEL_RANK[a.row.priority] - LEVEL_RANK[b.row.priority] || a.i - b.i)
718}
719
720// The summary card's lines (M286, look B), which register.tsx draws in one
721// Box with a round border. The first holds the project name, bold (M291),
722// then the base remote repo's open pull requests and open issues, each `?`
723// while the store holds no numbers for this root. The second holds the drawn candidate rows at each level, each
724// after its level's mark. The third holds the planned and blocked
725// milestones. A fourth, the release line, holds the latest release tag, the
726// days since its commit, and the milestones done since it, when the last
727// read could read them. When the read holds the repo page of a github.com
728// base remote, the name links to it, and each count and its word to the
729// page's pull requests or issues list (M311).
730export function cardLines(
731  state: PaneState,
732  drawn: { row: CandidateRow }[],
733  repo: CairnRepoRead | null,
734  name: string | null = null,
735): PaneLine[] {
736  const counts = repo?.counts ?? null
737  const web = repo?.web ?? null
738  const linked = (span: Span, path: string): Span => (web === null ? span : { ...span, href: `${web}${path}` })
739  const number = (n: number | undefined, path: string) =>
740    linked({ text: n === undefined ? UNKNOWN_NUMBER : `${n}`, bold: true }, path)
741  // The project name, bold, in the text, which is cut first when the line
742  // is too narrow, and the counts in the tail after it (M291). The tail
743  // takes the free room, so the Buttons sit at the right end.
744  const named = name !== null && name !== ''
745  const first: PaneLine = {
746    ...line(CARD_KEYS.repo, 0, [], named ? linked({ text: name, bold: true }, '') : null),
747    tail: [
748      ...(named ? [{ text: '  ' }] : []),
749      number(counts?.prs, '/pulls'),
750      linked({ text: ' PRs', color: GRAY }, '/pulls'),
751      { text: '   ' },
752      number(counts?.issues, '/issues'),
753      linked({ text: ' issues', color: GRAY }, '/issues'),
754    ],
755    tailGrows: true,
756  }
757  const levels: CandidateRow['priority'][] = ['high', 'normal', 'low', 'parked']
758  const second = line(CARD_KEYS.candidates, 0, [
759    { text: 'candidates', color: GRAY },
760    ...levels.flatMap((level, i) => [
761      { text: i === 0 ? ' ' : '   ' },
762      PRIORITY_MARK[level],
763      { text: ` ${drawn.filter(({ row }) => row.priority === level).length}` },
764    ]),
765  ])
766  const planned = state.workable.length + state.waiting.length
767  const third = line(CARD_KEYS.milestones, 0, [], { text: `${planned} planned · ${state.blocked.length} blocked`, color: GRAY })
768  // The release line, while the last read written for this root could read
769  // the latest release tag, the days since its commit, and the milestones
770  // archived since it (M286).
771  const done = repo?.done ?? null
772  const release =
773    done === null
774      ? []
775      : [
776          line(CARD_KEYS.release, 0, [], {
777            text: `${done.tag} · ${done.days === 1 ? '1 day' : `${done.days} days`} ago · ${done.count} done since`,
778            color: GRAY,
779          }),
780        ]
781  return [first, second, third, ...release].map(card => ({ ...card, card: true }))
782}
783
784// A blocked milestone's line or a hotfix pull request's line, in one layout
785// (M286): the state mark in its word's color, the identifier bold, the
786// title, and a tail that holds the pull request's number in gray, the
787// archived mark for a blocked row whose file was archived (M246), and the
788// state word in its color. An open pull request whose read has a merge
789// state ends the tail with that state's mark (M301). Before a read the mark
790// is `○` in gray and the tail holds no word. A blocked row with no pull
791// request has no number. A line with a tail grows, so the tail sits at the
792// right end whether or not the title is cut.
793function prLine(key: string, id: string, title: string, number: number | null, archived: boolean, got: PrRead | undefined): PaneLine {
794  const word = got?.word
795  const mark: Span = word === undefined ? { ...UNREAD_MARK, color: GRAY } : { ...PR_MARK[word], color: prColor(word) }
796  const held: PaneLine = { ...line(key, 2, [mark, { text: ' ' }, { text: id, bold: true }, { text: '  ' }], { text: title }), full: title }
797  const tail: Span[] = []
798  if (number !== null) tail.push({ text: ' ' }, { text: `#${number}`, color: GRAY })
799  if (archived) tail.push({ text: ' ' }, { text: 'archived', color: GRAY })
800  if (word !== undefined) tail.push({ text: ' ' }, { text: word, color: prColor(word) })
801  // Only an open word draws the mark, whatever the read holds.
802  const merge = word !== undefined && OPEN_WORDS.includes(word) ? (got?.mergeable ?? null) : null
803  if (merge !== null) tail.push({ text: ' ' }, { ...MERGE_MARK[merge] })
804  if (tail.length > 0) {
805    held.tail = [{ text: ' ' }, ...tail]
806    held.grow = true
807  }
808  return held
809}
810
811// The line under a pull request's line with its unresolved threads, or null
812// when it has no count. The counts sit in the line's text, which is cut at
813// the pane's edge, since a 44-column dock leaves no room for them in the
814// tail (M225).
815function countsLine(key: string, got: PrRead | undefined): PaneLine | null {
816  const counts = got?.counts == null ? null : countsText(got.counts)
817  return counts === null ? null : line(key, 4, [], { text: counts, color: GRAY })
818}
819
820// The pane's lines from its state and the band's rows, whose counts give
821// each head line its percent. `acts` is true while no cairn skill's step is
822// set, and then the Next line carries its action label (M218) and the
823// Status Button after it (M219), the first line carries ⌂ (M241), and each
824// candidate line with a short title carries ✎ (M242).
825// `prs` holds each pull request's state word by its
826// URL, from the last read (M224), with its counts (M225). `hotfixes` holds
827// the open hotfix pull requests of the last read for this root (M226), and
828// `started` the candidate rows that open pull requests' bodies name (M252).
829export function paneLines(
830  state: PaneState,
831  band: BandRow[] = [],
832  acts = false,
833  prs: Record<string, PrRead> = {},
834  hotfixes: HotfixPr[] = [],
835  started: StartedRow[] = [],
836  repo: CairnRepoRead | null = null,
837  root: string | null = null,
838): PaneLine[] {
839  if (!state.found) return [line('no-roadmap', 0, [], { text: NO_ROADMAP, color: GRAY })]
840  // The candidate rows the Candidates list draws, whether or not a
841  // milestone is active, which the card counts too (M286).
842  const drawable = drawnCandidates(state, hotfixes, started)
843  // The project name of the read for this root, or before one is stored
844  // the root's last segment (M291). `repo` is for this root or null.
845  const name = repo?.name ?? (root === null ? null : lastSegment(root))
846  const out: PaneLine[] = cardLines(state, drawable, repo, name)
847  // The card's first line carries the ↻ Button at its right end (M236, on
848  // the card since M286), and ⌂ before it while no cairn skill's step is
849  // set (M241).
850  out[0].buttons = acts ? ['home', 'refresh'] : ['refresh']
851  // A blank row under the card, for the operator's ask for more space,
852  // before the first milestone. Every later section opens with its own
853  // blank row, so with no milestone active the card needs none (M305).
854  state.milestones.forEach((row, i) => {
855    out.push(gap(i === 0 ? 'card-gap' : `${row.id}-gap`))
856    out.push(...milestoneLines(row, band.find(b => b.id === row.id && b.status === row.status)))
857  })
858  // With no milestone active, a planning Next line beside a drawn
859  // Candidates list repeats the ✎ that each candidate line with a short
860  // title carries, so it draws only while the list draws no row (M305). A
861  // list whose drawn rows all have empty titles has no ✎, and the band's
862  // Plan is then the way to plan.
863  const drawn = state.milestones.length === 0 ? drawable : []
864  const repeats = state.next?.command === '/milestone-plan' && drawn.length > 0
865  if (state.next !== null && !repeats) {
866    // Until M305 planning named its `[high]` row's short title after the
867    // command (M272). A drawn `[high]` row now hides the line, so a shown
868    // planning line names none. The band's Plan press still names it.
869    const target = state.next.id === null ? state.next.command : `${state.next.command} ${state.next.id}`
870    out.push(gap('next-gap'))
871    // The arrow and the command, bold in the color of the phase the command
872    // runs, with no pill (M286, look B).
873    const color = FLOW_COLORS[COMMAND_PHASE[state.next.command] ?? 'implement']
874    const next = line('next', 0, [{ text: NEXT_MARK, color, bold: true }], { text: target, color, bold: true })
875    const label = nextLabel(state.next.action)
876    // Status follows the next-step Button and shows only with it, as the
877    // band's shows only with a next-step label (M219 review).
878    if (acts && label !== undefined) {
879      next.action = label
880      next.buttons = ['status']
881    }
882    out.push(next)
883  }
884  if (state.workable.length > 0) {
885    out.push(...heading('workable-head', 'Workable'))
886    for (const row of state.workable) {
887      out.push({ ...line(`workable-${row.id}`, 2, [{ text: row.id, bold: true }, { text: '  ' }], { text: row.title }), full: row.title })
888    }
889  }
890  if (state.waiting.length > 0) {
891    out.push(...heading('waiting-head', 'Waiting'))
892    for (const row of state.waiting) {
893      const text = `${row.title} · on ${row.unmet.join(', ')}`
894      out.push({ ...line(`waiting-${row.id}`, 2, [{ text: row.id, bold: true }, { text: '  ' }], { text }), full: text })
895    }
896  }
897  // The blocked rows, each with its pull request's number when its
898  // milestone file's header names one, whether or not a milestone is
899  // active (M223). After the number, the state word that the last read
900  // found, and the Button that word carries (M224).
901  if (state.blocked.length > 0) {
902    out.push(...countHeading('blocked-head', 'Blocked', state.blocked.length))
903    for (const row of state.blocked) {
904      const got = row.url !== null && Object.prototype.hasOwnProperty.call(prs, row.url) ? prs[row.url] : undefined
905      const held = prLine(`blocked-${row.id}`, row.id, row.title, row.pr, row.archived, got)
906      const word = got?.word
907      if (word !== undefined) {
908        // An archived row carries only Finish (M246 review): its milestone
909        // file is gone, so Revise and Check have nothing to work on.
910        const mapped = PR_BUTTON[word]
911        const button = row.archived && mapped !== 'finish' ? undefined : mapped
912        if (button !== undefined) {
913          held.buttons = [button]
914          held.target = row.id
915        }
916      }
917      out.push(held)
918      const counts = countsLine(`blocked-${row.id}-counts`, got)
919      if (counts !== null) out.push(counts)
920    }
921  }
922  // The open hotfix pull requests, after the Blocked rows and before the
923  // candidates, each its number and title, and after a read its state word
924  // and counts as a blocked line shows them, with no Button (M226).
925  // A hotfix pull request whose URL is a blocked row's draws on that blocked
926  // line only, which carries any Button its word calls for, and the count
927  // leaves it out (M230).
928  const shown = hotfixes.filter(pr => !state.blocked.some(row => row.url === pr.url))
929  if (shown.length > 0) {
930    out.push(...countHeading('hotfixes-head', 'Hotfixes', shown.length))
931    for (const pr of shown) {
932      const got = Object.prototype.hasOwnProperty.call(prs, pr.url) ? prs[pr.url] : undefined
933      out.push(prLine(`hotfix-${pr.number}`, HOTFIX_ID, pr.title, pr.number, false, got))
934      const counts = countsLine(`hotfix-${pr.number}-counts`, got)
935      if (counts !== null) out.push(counts)
936    }
937  }
938  // With no active milestone, the ROADMAP's candidate rows (M207), each
939  // with ✎ while no cairn skill runs, but for a row with an empty short
940  // title, whose press would plan with no args (M242). A row that work has
941  // started draws no line (M261): one whose short title an open pull
942  // request's body names exactly (M252), or that a counted started token
943  // marks (M258). The heading counts the drawn rows, and with none it is
944  // not drawn. The lines draw high rows first, then normal, then low, then
945  // parked (M284), each level in ROADMAP order, whatever order the file
946  // holds them in (M280).
947  // `state.candidates` stays in ROADMAP order. A drawn line keeps its row's
948  // index there as its key and its ✎ target, and `pressCandidate` looks the
949  // row up by that index. `drawn` is set before the Next line, which reads it.
950  if (drawn.length > 0) {
951    out.push(...countHeading('candidates-head', 'Candidates', drawn.length))
952    for (const { row, i } of drawn) {
953      const candidate = line(
954        `candidate-${i}`,
955        2,
956        [PRIORITY_MARK[row.priority], { text: ' ' }],
957        row.priority === 'low' ? { text: row.title, color: GRAY } : row.priority === 'parked' ? { text: row.title, color: PARKED_KEY } : { text: row.title },
958      )
959      candidate.grow = true
960      // The card holds the row's whole text after its priority token, and
961      // the line its short title (M293).
962      candidate.full = row.text
963      if (row.text !== '') candidate.info = true
964      // The rows the pane draws before this line (M294): one per line before
965      // it, since only goal lines wrap and they draw only while a milestone
966      // is active, plus the summary card's two border rows.
967      candidate.rowsAbove = out.length + 2
968      if (acts && row.title !== '') {
969        candidate.buttons = ['plan']
970        candidate.target = `${i}`
971        candidate.title = row.title
972      }
973      out.push(candidate)
974    }
975  }
976  // A line whose text is empty has no hover card (M286).
977  for (const each of out) if (each.full === '') delete each.full
978  return out
979}
980
hooks/status/reader.ts 752 lines
1// The status band's reader: which milestones are active, how many of their
2// tasks and criteria are checked, and the first open one of each, and which
3// planned milestones are workable. It mirrors the Python helpers the
4// validator uses (`parse_roadmap_rows_full` in hooks/cairn_common.py, `_section_body` and
5// `_AC_ITEM` in scripts/cairn_validate.py, `find_cairn_root` for the walk),
6// and `workable` in scripts/cairn_next.py over the rows `cairn_scripts.rows`
7// parses (its Depends-on cells through `parse_depends`), with what
8// `workable` reaches through `done_ids` and `_workable` (`canon_id`,
9// `archive_files`, and `sort_by_priority` with its `id_num`). For the cairn
10// pane it also mirrors `recommend` and `waiting` in scripts/cairn_next.py
11// (M205), and reads the candidate rows in the sections that
12// `candidate_count` in scripts/cairn_scripts.py walks (M207), and mirrors
13// `blocked` and `pr_number` in scripts/cairn_next.py (M223), and `pr_url`
14// (M224), and `archived_text` and `status_paragraph` (M246), and
15// `stack_bases` and `_met`, with `push_remote` in hooks/cairn_common.py
16// (M268), and `high_title`, which `recommend` reads for planning (M272).
17// The mirror
18// reads ASCII digits only, where Python's `isdigit`, `isdecimal`, and `\d`
19// also take other Unicode digits, so an id such as `M0057` reads
20// differently in the two.
21// hooks/status/reader.test.ts holds this reader, and
22// scripts/tests/test_status_fixtures.py the Python helpers, to the same
23// fixtures.
24
25// Where the reader gets files. The shipped mod reads through `$.fs` and
26// `$.session`; the tests read an in-memory copy of a fixture.
27export type FileSource = {
28  cwd: () => Promise<string>
29  isFile: (path: string) => Promise<boolean>
30  // The file's text, or null when it cannot be read.
31  read: (path: string) => Promise<string | null>
32  // The names of a directory's entries, or null when it cannot be listed.
33  list: (path: string) => Promise<string[] | null>
34}
35
36// A planned milestone whose dependencies are all done; in guest mode at
37// most one may instead be a stack base (M268, `workableRows`).
38export type WorkableRow = { id: string; title: string }
39
40// What the band reads: the active rows in ROADMAP order, and the workable
41// planned rows by priority and then id, whether or not a row is active.
42export type BandState = { rows: BandRow[]; workable: WorkableRow[] }
43
44// The counts and next items are all null when the row's milestone path is
45// not a readable regular file. A next item is also null when its section
46// holds no open box.
47export type BandRow = {
48  id: string
49  title: string
50  status: string
51  tasksChecked: number | null
52  tasksTotal: number | null
53  criteriaChecked: number | null
54  criteriaTotal: number | null
55  // The first open task or criterion line, less its `- [ ]` prefix.
56  nextTask: string | null
57  nextCriterion: string | null
58}
59
60export type Fixture = {
61  cwd: string
62  files: Record<string, string>
63  rows: BandRow[]
64  // The ordered ids of the workable planned rows, as cairn_next.py lists them.
65  workable: string[]
66  // The pane's milestones, and `recommend` with `waiting` beside it, as
67  // scripts/tests/test_status_fixtures.py computes them; `next` is null
68  // with no ROADMAP (M205).
69  pane: PaneMilestone[]
70  next: (NextStep & { waiting: WaitingRow[] }) | null
71  // The pane's candidate rows, as test_status_fixtures.py reads them (M207).
72  candidates: CandidateRow[]
73  // The pane's blocked rows, as `blocked` in scripts/cairn_next.py reads
74  // them (M223).
75  blocked: BlockedRow[]
76  // Paths that stat as files but whose read fails in the tests.
77  unreadable: string[]
78}
79
80export const ACTIVE: readonly string[] = ['in-progress', 'review']
81
82const AC_ITEM = /^\s*-\s*\[[ xX]\]/
83const CHECKED = /^\s*-\s*\[[xX]\]/
84const OPEN_BOX = /^\s*-\s*\[ \]\s*/
85
86// The line breaks Python's str.splitlines() splits on.
87const LINE_BREAK = new RegExp(
88  '\\r\\n|[\\n\\r\\v\\f\\x1c\\x1d\\x1e\\x85' + String.fromCharCode(0x2028, 0x2029) + ']',
89)
90
91export function splitLines(text: string): string[] {
92  return text.split(LINE_BREAK)
93}
94
95export type RoadmapRow = {
96  id: string
97  title: string
98  status: string
99  depends: string
100  priority: string
101  relpath: string
102}
103
104export function parseRoadmapRows(text: string): RoadmapRow[] {
105  const rows: RoadmapRow[] = []
106  for (const line of splitLines(text)) {
107    if (!line.trimStart().startsWith('|')) continue
108    const cells = line.split('|').slice(1, -1).map(c => c.trim())
109    if (cells.length < 6 || !cells[0].startsWith('M')) continue
110    rows.push({
111      id: cells[0],
112      title: cells[1],
113      status: cells[2].toLowerCase(),
114      depends: cells[3],
115      priority: cells[4],
116      relpath: cells[5],
117    })
118  }
119  return rows
120}
121
122const DIGITS = /^\d+$/
123
124// The milestone ids in a Depends-on cell, as `parse_depends` for ASCII
125// digits: a token is an `M` and digits, and every other token, `—`
126// included, is dropped.
127export function parseDepends(cell: string): string[] {
128  return cell
129    .trim()
130    .split(/[,\s]+/)
131    .filter(token => token.startsWith('M') && DIGITS.test(token.slice(1)))
132}
133
134// An id at three-digit padding, as `canon_id` for ASCII digits: `M57`,
135// `M057`, and `M0057` are `M057`, and a non-numeric id stays as it is.
136export function canonId(id: string): string {
137  const rest = id.slice(1)
138  return DIGITS.test(rest) ? `M${BigInt(rest).toString().padStart(3, '0')}` : id
139}
140
141// The sort key of an id: its number, or after every numeric id.
142function idNumber(id: string): number {
143  const rest = id.slice(1)
144  return DIGITS.test(rest) ? Number(rest) : 1e9
145}
146
147// A Map, so a priority word such as `constructor` reads as normal.
148const PRIORITY_RANK = new Map([
149  ['high', 0],
150  ['normal', 1],
151  ['low', 2],
152])
153
154function priorityRank(priority: string): number {
155  return PRIORITY_RANK.get(priority.toLowerCase()) ?? 1
156}
157
158// The planned rows whose Depends-on ids are each a done row, in
159// `archived`, or in `bases`, with at most one in `bases` (M268), by
160// priority and then id; the sort keeps ROADMAP order on a tie. `archived`
161// and `bases` hold ids at three-digit padding. `bases` holds the stack
162// bases, as `stack_bases` in scripts/cairn_next.py reads them.
163export function workableRows(rows: RoadmapRow[], archived: string[], bases: string[] = []): WorkableRow[] {
164  const done = doneIds(rows, archived)
165  const stacked = new Set(bases)
166  return rows
167    .filter(row => row.status === 'planned' && unmetDeps(row, done, stacked).length === 0)
168    .sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority) || idNumber(a.id) - idNumber(b.id))
169    .map(row => ({ id: row.id, title: row.title }))
170}
171
172function doneIds(rows: RoadmapRow[], archived: string[]): Set<string> {
173  return new Set([...rows.filter(row => row.status === 'done').map(row => canonId(row.id)), ...archived])
174}
175
176// The Depends-on ids, as written, that `_met` in scripts/cairn_next.py
177// leaves out: met are the done ids, and the row's stack-base dependency
178// when it has exactly one (M268).
179function unmetDeps(row: RoadmapRow, done: Set<string>, bases: Set<string>): string[] {
180  const deps = parseDepends(row.depends)
181  const onBases = new Set(deps.map(canonId).filter(id => bases.has(id) && !done.has(id)))
182  const met = onBases.size <= 1 ? new Set([...done, ...onBases]) : done
183  return deps.filter(dep => !met.has(canonId(dep)))
184}
185
186// The glob `M*.md` and the id at the start of each name, as `archive_files`.
187const ARCHIVE_NAME = /^M[\s\S]*\.md$/
188const ARCHIVE_ID = /^M\d+/
189
190// The ids, at three-digit padding, of the archive files directly under
191// cairn/milestones/archive/.
192async function archivedIds(source: FileSource, root: string): Promise<string[]> {
193  const names = (await source.list(join(root, 'cairn/milestones/archive'))) ?? []
194  const ids: string[] = []
195  for (const name of names) {
196    const id = ARCHIVE_NAME.test(name) ? ARCHIVE_ID.exec(name)?.[0] : undefined
197    if (id !== undefined) ids.push(canonId(id))
198  }
199  return ids
200}
201
202// `status_paragraph` in scripts/cairn_next.py (M246): the first line that
203// starts with `**Status:**`, through the line before the next line of only
204// spaces and tabs, or the end of the text. Null when no line starts so.
205const BLANK = /^[ \t]*$/
206const STATUS_DONE = /^\*\*Status:\*\*[ \t]*done/
207export function statusParagraph(text: string): string | null {
208  const lines = splitLines(text)
209  const start = lines.findIndex(line => line.startsWith('**Status:**'))
210  if (start < 0) return null
211  const out = [lines[start]]
212  for (const rest of lines.slice(start + 1)) {
213    if (BLANK.test(rest)) break
214    out.push(rest)
215  }
216  return out.join('\n')
217}
218
219// `archived_text` in scripts/cairn_next.py (M246): the text of the one
220// archive file whose canonical id is the row's, when its read succeeds and
221// its Status paragraph starts with `done`. Null otherwise.
222async function archivedText(source: FileSource, root: string, id: string): Promise<string | null> {
223  const dir = join(root, 'cairn/milestones/archive')
224  const want = canonId(id)
225  const found = ((await source.list(dir)) ?? []).filter(name => {
226    const got = ARCHIVE_NAME.test(name) ? ARCHIVE_ID.exec(name)?.[0] : undefined
227    return got !== undefined && canonId(got) === want
228  })
229  if (found.length !== 1) return null
230  const path = join(dir, found[0])
231  const text = (await source.isFile(path)) ? await source.read(path) : null
232  const para = text === null ? null : statusParagraph(text)
233  return para !== null && STATUS_DONE.test(para) ? text : null
234}
235
236// Lines under the first `## <heading>` H2, up to the next H2 or the end.
237export function sectionBody(text: string, heading: string): string[] {
238  const out: string[] = []
239  let inSection = false
240  for (const line of splitLines(text)) {
241    if (line.startsWith('## ')) {
242      if (inSection) break
243      inSection = line.slice(3).trim().toLowerCase().startsWith(heading.toLowerCase())
244      continue
245    }
246    if (inSection) out.push(line)
247  }
248  return out
249}
250
251export type SectionFields = { checked: number; total: number; next: string | null }
252
253// The checkbox counts of one section and its first open line, less the box.
254export function sectionFields(text: string, heading: string): SectionFields {
255  const items = sectionBody(text, heading).filter(line => AC_ITEM.test(line))
256  const open = items.find(line => OPEN_BOX.test(line))
257  return {
258    checked: items.filter(line => CHECKED.test(line)).length,
259    total: items.length,
260    next: open === undefined ? null : open.replace(OPEN_BOX, ''),
261  }
262}
263
264const NO_FILE = {
265  tasksChecked: null,
266  tasksTotal: null,
267  criteriaChecked: null,
268  criteriaTotal: null,
269  nextTask: null,
270  nextCriterion: null,
271}
272
273function fileFields(text: string) {
274  const tasks = sectionFields(text, 'Tasks')
275  const criteria = sectionFields(text, 'Acceptance criteria')
276  return {
277    tasksChecked: tasks.checked,
278    tasksTotal: tasks.total,
279    criteriaChecked: criteria.checked,
280    criteriaTotal: criteria.total,
281    nextTask: tasks.next,
282    nextCriterion: criteria.next,
283  }
284}
285
286export function dirname(path: string): string {
287  const trimmed = path.length > 1 ? path.replace(/[\\/]+$/, '') : path
288  // A UNC share root (`\\host\share`) is a root, as a drive is (M210).
289  if (/^[\\/]{2}[^\\/]+[\\/][^\\/]+$/.test(trimmed)) return trimmed
290  const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
291  if (cut < 0) return trimmed
292  if (cut === 0) return trimmed[0]
293  const head = trimmed.slice(0, cut)
294  return /^[A-Za-z]:$/.test(head) ? head + trimmed[cut] : head
295}
296
297export function join(dir: string, rel: string): string {
298  return `${dir.replace(/[\\/]+$/, '')}/${rel}`
299}
300
301// The nearest directory at or above `cwd` that holds cairn/ROADMAP.md.
302export async function findRoot(source: FileSource, cwd: string): Promise<string | null> {
303  let path = cwd
304  for (;;) {
305    if (await source.isFile(join(path, 'cairn/ROADMAP.md'))) return path
306    const parent = dirname(path)
307    if (parent === path) return null
308    path = parent
309  }
310}
311
312// One row per `in-progress` or `review` milestone, in ROADMAP order, and
313// the workable list. Empty when no ROADMAP is found, and null when one is
314// found but cannot be read (M200) or is empty (M210). `read_roadmap` in
315// scripts/cairn_scripts.py reads an unreadable ROADMAP as empty instead.
316export async function loadBand(source: FileSource): Promise<BandState | null> {
317  const loaded = await loadCairn(source)
318  return loaded === null ? null : loaded.band
319}
320
321// The band's state and the pane's from one read of the files (M205). Null
322// when a ROADMAP is found but cannot be read, or its text is empty or only
323// whitespace, as a write half done can leave it (M210).
324export async function loadCairn(source: FileSource): Promise<{ band: BandState; pane: PaneState } | null> {
325  const root = await findRoot(source, await source.cwd())
326  return root === null ? emptyCairn() : loadAt(source, root)
327}
328
329// The same read with the root it found (M210): `root` is null when no
330// ROADMAP is found, and `state` is null when a found one cannot be read,
331// its text is empty or only whitespace, or a throw ends the read. A throw
332// from `source.cwd()` is not caught, since it leaves the root unknown.
333export async function readCairn(
334  source: FileSource,
335): Promise<{ root: string | null; state: { band: BandState; pane: PaneState } | null }> {
336  const root = await findRoot(source, await source.cwd())
337  if (root === null) return { root, state: emptyCairn() }
338  try {
339    return { root, state: await loadAt(source, root) }
340  } catch {
341    return { root, state: null }
342  }
343}
344
345function emptyCairn(): { band: BandState; pane: PaneState } {
346  return { band: { rows: [], workable: [] }, pane: NO_PANE }
347}
348
349async function loadAt(source: FileSource, root: string): Promise<{ band: BandState; pane: PaneState } | null> {
350  const roadmap = await source.read(join(root, 'cairn/ROADMAP.md'))
351  if (roadmap === null || roadmap.trim() === '') return null
352  const parsed = parseRoadmapRows(roadmap)
353  const out: BandRow[] = []
354  const milestones: PaneMilestone[] = []
355  const blocked: BlockedRow[] = []
356  for (const row of parsed) {
357    const active = ACTIVE.includes(row.status)
358    if (!active && row.status !== 'blocked') continue
359    // A regular file only, as Python's os.path.isfile: a path to a pipe or
360    // a device would otherwise stall the read at every turn end.
361    const path = join(root, `cairn/${row.relpath}`)
362    const live = await source.isFile(path)
363    const text = live ? await source.read(path) : null
364    if (!active) {
365      const archive = live ? null : await archivedText(source, root, row.id)
366      if (archive !== null) {
367        const url = PR_URL.exec(statusParagraph(archive) ?? '')
368        blocked.push({
369          id: row.id,
370          title: row.title,
371          pr: url === null ? null : Number(url[1]),
372          url: url === null ? null : url[0],
373          archived: true,
374        })
375        continue
376      }
377      blocked.push({
378        id: row.id,
379        title: row.title,
380        pr: text === null ? null : prNumber(text),
381        url: text === null ? null : prUrl(text),
382        archived: false,
383      })
384      continue
385    }
386    const fields = text === null ? NO_FILE : fileFields(text)
387    out.push({ id: row.id, title: row.title, status: row.status, ...fields })
388    milestones.push({ id: row.id, title: row.title, status: row.status, file: text === null ? null : paneFile(text) })
389  }
390  const archived = await archivedIds(source, root)
391  // The stack bases, as `stack_bases` in scripts/cairn_next.py (M268).
392  const profilePath = join(root, 'cairn/PROFILE.md')
393  const profile = (await source.isFile(profilePath)) ? await source.read(profilePath) : null
394  const stacking = profile !== null && collaborationMode(profile) === 'guest' && pushRemote(profile) === 'base'
395  const bases = stacking ? blocked.filter(row => row.url !== null && !row.archived).map(row => canonId(row.id)) : []
396  const workable = workableRows(parsed, archived, bases)
397  const shipped = blocked.filter(row => row.archived).map(row => row.id)
398  return {
399    band: { rows: out, workable },
400    pane: {
401      found: true,
402      milestones,
403      next: recommend(parsed, workable, roadmap, shipped),
404      workable,
405      waiting: waitingRows(parsed, archived, bases),
406      candidates: candidateRows(roadmap),
407      blocked,
408      taken: takenRows(roadmap, parsed, shipped),
409    },
410  }
411}
412
413// A milestone header's `Branch/PR` line, and a pull request URL in it, as
414// `BRANCH_PR` and `PR_URL` in scripts/cairn_next.py (M223), with spaces and
415// tabs spelled out, since `\s` takes different characters in the two. A
416// number has at most 15 digits, so `Number` reads it exactly.
417const BRANCH_PR = /^[ \t]*-[ \t]*\*\*Branch\/PR:\*\*(.*)$/
418const PR_URL = /https:\/\/github\.com\/[^/ \t]+\/[^/ \t]+\/pull\/([0-9]{1,15})(?![0-9])/
419
420// `_pr_match` in scripts/cairn_next.py: the match of the pull request URL
421// that the first `Branch/PR` header line names, the first URL before any
422// `companion:` entry, or null. The header is the text before the first
423// `## ` heading.
424function prMatch(text: string): RegExpExecArray | null {
425  for (const line of splitLines(text)) {
426    if (line.startsWith('## ')) return null
427    const match = BRANCH_PR.exec(line)
428    if (match === null) continue
429    return PR_URL.exec(match[1].split('companion:')[0])
430  }
431  return null
432}
433
434// The collaboration mode that a `cairn/PROFILE.md` text declares, as
435// `collaboration_mode` in hooks/cairn_common.py reads it (M226): the value
436// of the first `# Collaboration mode:` line before the first `## ` slot
437// heading, lowercased, with the key matched in any case and a leading BOM
438// skipped. A text with no such line reads as `owner`.
439export function collaborationMode(text: string): string {
440  return profileHeader(text, /^#\s*Collaboration mode:\s*(\S+)/i) ?? 'owner'
441}
442
443// The value of the `# Push remote:` line that a `cairn/PROFILE.md` text
444// declares, as `push_remote` in hooks/cairn_common.py reads it (M268):
445// read as `collaborationMode` reads its line, and null with no such line.
446export function pushRemote(text: string): string | null {
447  return profileHeader(text, /^#\s*Push remote:\s*(\S+)/i)
448}
449
450// The first match of `pattern` before the first `## ` slot heading,
451// lowercased, with a leading BOM skipped, or null.
452function profileHeader(text: string, pattern: RegExp): string | null {
453  for (const each of splitLines(text.replace(/^/, ''))) {
454    if (each.startsWith('## ')) break
455    const found = pattern.exec(each)
456    if (found !== null) return found[1].toLowerCase()
457  }
458  return null
459}
460
461// `pr_number` in scripts/cairn_next.py: the number of that pull request, or
462// null.
463export function prNumber(text: string): number | null {
464  const url = prMatch(text)
465  return url === null ? null : Number(url[1])
466}
467
468// `pr_url` in scripts/cairn_next.py (M224): its URL up to the number, so
469// with no trailing path or anchor, or null.
470export function prUrl(text: string): string | null {
471  const url = prMatch(text)
472  return url === null ? null : url[0]
473}
474
475// The cairn pane's state (M205): the active milestones in full, the
476// queue that scripts/cairn_next.py prints, the candidate rows (M207), and
477// the blocked rows with their pull request numbers (M223), and the
478// started tokens of the candidate rows (M258). `found` is false when no
479// ROADMAP is found.
480export type PaneState = {
481  found: boolean
482  milestones: PaneMilestone[]
483  next: NextStep | null
484  workable: WorkableRow[]
485  waiting: WaitingRow[]
486  candidates: CandidateRow[]
487  blocked: BlockedRow[]
488  taken: TakenRow[]
489}
490
491// One candidate row of the ROADMAP: its priority token's level, `normal`
492// with no token, its short title, and its whole text after the token
493// (M293), which the desktop pane's ⓘ card shows.
494// A `parked` row waits on a promotion condition that has not held (M284).
495export type CandidateRow = { priority: 'high' | 'normal' | 'low' | 'parked'; title: string; text: string }
496
497// One ` — started <ref>` token of a candidate row (M258), with the row's
498// short title: `ref` is `M<NNN>` or `#<n>` as the token spells it.
499export type TakenRow = { title: string; ref: string }
500
501export type PaneItem = { text: string; checked: boolean }
502
503// `file` is null when the milestone file is missing or its read fails.
504export type PaneMilestone = {
505  id: string
506  title: string
507  status: string
508  file: { goal: string; tasks: PaneItem[]; criteria: PaneItem[]; log: string[] } | null
509}
510
511// `recommend` in scripts/cairn_next.py: `id` is null for planning, and
512// `title` is `highTitle`'s short title when planning, else null (M272,
513// M273).
514export type NextStep = { action: string; command: string; id: string | null; title: string | null }
515
516// `waiting` in scripts/cairn_next.py: `unmet` holds each undone dependency
517// as written, with its row's status or `unknown`.
518export type WaitingRow = { id: string; title: string; unmet: string[] }
519
520// `blocked` in scripts/cairn_next.py (M223): a `blocked` row, and the
521// number of the pull request its milestone file's `Branch/PR` header names,
522// or null, with that pull request's URL beside it (M224). `archived` is true
523// when the row's file is not a regular file and exactly one archive file
524// with its id is read and its Status paragraph starts with `done` (M246). The number and URL then come from
525// that file's Status paragraph, and either may be null.
526export type BlockedRow = { id: string; title: string; pr: number | null; url: string | null; archived: boolean }
527
528export const NO_PANE: PaneState = {
529  found: false,
530  milestones: [],
531  next: null,
532  workable: [],
533  waiting: [],
534  candidates: [],
535  blocked: [],
536  taken: [],
537}
538
539// How many work-log lines the pane state holds, newest last. The pane has
540// drawn none since M286; the state and its Python twin keep them.
541export const LOG_LINES = 5
542
543const COMMENT = /<!--[\s\S]*?-->/g
544const ITEM_BOX = /^\s*-\s*\[[ xX]\]\s*/
545const LOG_ITEM = /^- /
546
547// A section's lines with HTML comments removed, as the template's owner
548// notes are.
549function sectionText(text: string, heading: string): string[] {
550  return splitLines(sectionBody(text, heading).join('\n').replace(COMMENT, ''))
551}
552
553// A section's checkbox items. A non-blank indented line that is not itself
554// an item continues the item above it, so a wrapped task reads whole.
555export function sectionItems(text: string, heading: string): PaneItem[] {
556  const items: PaneItem[] = []
557  let current: PaneItem | null = null
558  for (const line of sectionText(text, heading)) {
559    if (AC_ITEM.test(line)) {
560      current = { text: line.replace(ITEM_BOX, ''), checked: CHECKED.test(line) }
561      items.push(current)
562    } else if (current !== null && /^\s/.test(line) && line.trim() !== '') {
563      current.text = `${current.text} ${line.trim()}`
564    } else {
565      current = null
566    }
567  }
568  return items
569}
570
571function paneFile(text: string) {
572  return {
573    goal: sectionText(text, 'Goal').join('\n').trim(),
574    tasks: sectionItems(text, 'Tasks'),
575    criteria: sectionItems(text, 'Acceptance criteria'),
576    log: sectionText(text, 'Work log')
577      .filter(line => LOG_ITEM.test(line))
578      .slice(-LOG_LINES)
579      .map(line => line.replace(LOG_ITEM, '')),
580  }
581}
582
583const PRIORITY_TOKENS: readonly [string, 'high' | 'low' | 'parked'][] = [
584  ['[high] ', 'high'],
585  ['[low] ', 'low'],
586  ['[parked] ', 'parked'],
587]
588
589// The candidate rows (M207): each flush-left line that opens with `- `
590// under a `## Candidates` heading. HTML comments are removed from each such
591// section's body before it is read, so the `/cairn-init` skeleton's
592// placeholder rows are not read, and a `<!--` in another section hides
593// nothing here. Every `## ` line starts or ends a section, as in
594// `candidate_count` in scripts/cairn_scripts.py, which also counts indented
595// lines and lines inside comments. A row's priority is `high`, `low`, or
596// `parked` when its text opens with exactly `[high] `, `[low] `, or
597// `[parked] ` (M284), else `normal`. Its
598// short title is the text after that token up to the first `: `, else up
599// to the first ` — `, else all of it (M251; tracking-rules "Candidate short
600// title"). Its text is all of it after the token, trimmed as the title is
601// (M293).
602export function candidateRows(roadmap: string): CandidateRow[] {
603  return candidateTexts(roadmap).map(({ priority, text }) => ({ priority, title: shortTitle(text), text: text.trim() }))
604}
605
606// Each candidate row's priority and its text after the priority token.
607function candidateTexts(roadmap: string): { priority: CandidateRow['priority']; text: string }[] {
608  const bodies: string[][] = []
609  let body: string[] | null = null
610  for (const line of splitLines(roadmap)) {
611    if (line.startsWith('## ')) {
612      body = line.trim().toLowerCase().startsWith('## candidates') ? [] : null
613      if (body !== null) bodies.push(body)
614      continue
615    }
616    if (body !== null) body.push(line)
617  }
618  const rows: { priority: CandidateRow['priority']; text: string }[] = []
619  for (const line of bodies.flatMap(lines => splitLines(lines.join('\n').replace(COMMENT, '')))) {
620    if (!line.startsWith('- ')) continue
621    let text = line.slice(2)
622    let priority: CandidateRow['priority'] = 'normal'
623    const match = PRIORITY_TOKENS.find(([token]) => text.startsWith(token))
624    if (match !== undefined) {
625      priority = match[1]
626      text = text.slice(match[0].length)
627    }
628    rows.push({ priority, text })
629  }
630  return rows
631}
632
633function shortTitle(text: string): string {
634  let cut = text.indexOf(': ')
635  if (cut < 0) cut = text.indexOf(' — ')
636  return (cut < 0 ? text : text.slice(0, cut)).trim()
637}
638
639// A started token (M258): ` — started ` and a milestone id or a pull
640// request number, followed by the row's end or by a character that is not
641// an ASCII letter or digit, so a note such as `; narrowed …` or a trailing space
642// after the token leaves it read (M258 review).
643const STARTED_TOKEN = / — started (M[0-9]+|#[0-9]{1,15})(?![0-9A-Za-z])/g
644
645// The started tokens of the candidate rows (M258), in ROADMAP order, each
646// with its row's short title. `/milestone-plan` writes ` — started M<NNN>`
647// on a row its plan absorbs, and `/hotfix`'s guest arm ` — started #<n>`
648// on a row its pull request fixes. Since each token opens with ` — `, a
649// token after the row's first `: ` or ` — ` leaves its short title the
650// same. A row with an empty
651// short title gives none, since no title names it.
652export function startedTokens(roadmap: string): TakenRow[] {
653  const out: TakenRow[] = []
654  for (const { text } of candidateTexts(roadmap)) {
655    const title = shortTitle(text)
656    if (title === '') continue
657    for (const match of text.matchAll(STARTED_TOKEN)) out.push({ title, ref: match[1] })
658  }
659  return out
660}
661
662// The tokens the pane counts (M258): an `M<NNN>` token while the ROADMAP
663// table holds that id as `planned` or `blocked`, the two statuses under
664// which that milestone is open and does not hide the candidate list (an
665// `in-progress` or `review` milestone hides it), and every `#<n>` token,
666// which the pane checks against its open hotfix list. A `blocked` id in
667// `archived`, whose file was archived before its row changed (M246), does
668// not count, since that work shipped. A counted id is given at three-digit
669// padding, as the table spells it (M258 review).
670export function takenRows(roadmap: string, rows: RoadmapRow[], archived: string[] = []): TakenRow[] {
671  const shipped = new Set(archived.map(canonId))
672  const live = new Set(
673    rows
674      .filter(row => row.status === 'planned' || row.status === 'blocked')
675      .map(row => canonId(row.id))
676      .filter(id => !shipped.has(id)),
677  )
678  return startedTokens(roadmap)
679    .filter(item => item.ref.startsWith('#') || live.has(canonId(item.ref)))
680    .map(item => (item.ref.startsWith('#') ? item : { title: item.title, ref: canonId(item.ref) }))
681}
682
683// `recommend` in scripts/cairn_next.py, over the rows, the workable list,
684// the ROADMAP text, and the archived `blocked` ids, from which planning
685// reads `highTitle` (M272, M273).
686export function recommend(rows: RoadmapRow[], workable: WorkableRow[], roadmap = '', archived: string[] = []): NextStep {
687  const review = rows.find(row => row.status === 'review')
688  if (review !== undefined) return { action: 'review', command: '/milestone-review', id: review.id, title: null }
689  const active = rows.find(row => row.status === 'in-progress')
690  if (active !== undefined) return { action: 'resume', command: '/milestone-implement', id: active.id, title: null }
691  if (workable.length > 0) return { action: 'implement', command: '/milestone-implement', id: workable[0].id, title: null }
692  return {
693    action: 'plan the next milestone',
694    command: '/milestone-plan',
695    id: null,
696    title: highTitle(roadmap, rows, archived),
697  }
698}
699
700// `high_title` in scripts/cairn_next.py (M272, M273): the short title of
701// the first candidate row, in ROADMAP order, that opens with `[high] `, has
702// a non-empty short title, and whose short title no token `takenRows`
703// counts names, or null. With no pull request read, every `#` token
704// counts here; the pane's own pick (`nextTitle` in pane.ts) checks them
705// against its open hotfix list.
706export function highTitle(roadmap: string, rows: RoadmapRow[] = [], archived: string[] = []): string | null {
707  const taken = new Set(takenRows(roadmap, rows, archived).map(item => item.title))
708  for (const { priority, text } of candidateTexts(roadmap)) {
709    const title = shortTitle(text)
710    if (priority === 'high' && title !== '' && !taken.has(title)) return title
711  }
712  return null
713}
714
715// `waiting` in scripts/cairn_next.py: the planned rows that are not
716// workable, in ROADMAP order. A later row with the same id wins the status
717// lookup, as the Python dict does.
718export function waitingRows(rows: RoadmapRow[], archived: string[], bases: string[] = []): WaitingRow[] {
719  const done = doneIds(rows, archived)
720  const stacked = new Set(bases)
721  const byId = new Map<string, RoadmapRow>()
722  for (const row of rows) byId.set(canonId(row.id), row)
723  const out: WaitingRow[] = []
724  for (const row of rows) {
725    if (row.status !== 'planned') continue
726    const unmet = unmetDeps(row, done, stacked).map(dep => `${dep} (${byId.get(canonId(dep))?.status ?? 'unknown'})`)
727    if (unmet.length > 0) out.push({ id: row.id, title: row.title, unmet })
728  }
729  return out
730}
731
732// The names directly under `dir` in a set of absolute file paths: a file's
733// name, or the first part of a deeper path. Null when nothing is under it.
734export function listNames(paths: string[], dir: string): string[] | null {
735  const prefix = `${dir.replace(/[\\/]+$/, '')}/`
736  const names = new Set<string>()
737  for (const path of paths) if (path.startsWith(prefix)) names.add(path.slice(prefix.length).split('/')[0])
738  return names.size === 0 ? null : [...names]
739}
740
741// An in-memory file source over absolute paths, for the tests. A path in
742// `unreadable` stats as a file, and its read fails.
743export function memorySource(files: Record<string, string>, cwd: string, unreadable: string[] = []): FileSource {
744  return {
745    cwd: async () => cwd,
746    isFile: async path => Object.prototype.hasOwnProperty.call(files, path),
747    read: async path =>
748      Object.prototype.hasOwnProperty.call(files, path) && !unreadable.includes(path) ? files[path] : null,
749    list: async dir => listNames(Object.keys(files), dir),
750  }
751}
752
hooks/status/track.ts 267 lines
1import type { Flow, Span } from './band'
2import type { FlowPhase } from './band'
3import { FLOW_COLORS, FLOW_PHASES } from './band'
4
5// The flow track (M204, M206), the band's one progress form. On the
6// desktop it is an SVG of one rounded track whose three equal segments run
7// plan, implement, and review. register.tsx draws it as the desktop's `Svg`
8// element, an image, so it cannot read the app's theme keys. In a
9// browser-pane preview, a `prefers-color-scheme` rule inside such an image
10// followed the browser's setting, not the page's (M204). The track draws
11// from one palette meant for a light and a dark ground instead (M217).
12//
13// Back to front: the ground; a field of 2-pixel specks from the left edge
14// to the head (the active phase's fill edge), sparse at the left and dense
15// near the head, each gray or the active phase's color, the colored share
16// growing toward the head; the item ticks; the two phase-edge marks; and
17// the pill on the head, in the active phase's color, its label bold and its
18// count dimmer. Item ticks fall in the active phase's segment, past the
19// head, and only when the items are SPACING pixels apart or more.
20// The operator picked this look at a live look over a solid dither per
21// segment and two other speck designs (M204).
22//
23// The track is TRACK_PX wide where the row has room, and shorter where it
24// does not. A track too short for the whole pill shows the pill's short
25// text: its count alone, `none` for a section with no boxes, or `Planned`
26// on the idle row (M206, the operator's pick from three narrow looks).
27//
28// In the terminal the track is a run of braille cells on the theme's
29// `userMessageBackground` ground, with the same specks as dots and the pill
30// as `inverseText` text on the phase's theme key (`brailleSpans`, M206, the
31// operator's pick from five terminal looks, in theme keys since M217).
32
33export const TRACK_PX = 360
34export const TRACK_H = 18
35
36const CELL = 2
37const ROWS = TRACK_H / CELL
38// The least spacing of item ticks, in pixels.
39export const SPACING = 6
40// palette
41// The desktop track's colors (M217). The pane's icons (icons.ts, M286) and
42// count badges (badge.ts, M289) keep their own raw colors. The
43// image cannot read theme keys, so the ground, the gray specks, and the
44// marks are translucent grays for a light or a dark ground. The phase fills
45// keep the M204 hues, darker, so the pill's white label and its count at
46// COUNT_OPACITY reach the WCAG 2.2 text contrast of 4.5:1 on the fill
47// whatever the app's ground (the band tests compute it).
48const GROUND = 'rgba(128,128,128,0.16)'
49const GRAY = 'rgb(160,160,160)'
50const MARK = 'rgb(200,200,200)'
51const PHASE_FILLS: Record<FlowPhase, string> = {
52  plan: 'rgb(71,103,158)',
53  implement: 'rgb(152,85,57)',
54  review: 'rgb(68,113,81)',
55}
56const PILL_LABEL = 'rgb(255,255,255)'
57// palette end
58const COUNT_OPACITY = 0.85
59// A speck's strength, by one of three levels.
60const LEVELS = [0.4, 0.65, 0.95]
61const PILL_H = TRACK_H - 2
62// The pill's width per character of its label and its count, and its side
63// padding, an estimate for the system font at the pill's size.
64const LABEL_CHAR = 6.3
65const COUNT_CHAR = 5.6
66const COUNT_GAP = 5
67const PILL_PAD = 16
68
69// A fixed hash of a cell, in [0, 1), so every drawing of a state is the
70// same.
71function hash(x: number, y: number, salt: number): number {
72  let h = (x * 374761393 + y * 668265263 + salt * 2147483647) | 0
73  h = Math.imul(h ^ (h >>> 13), 1274126177)
74  h ^= h >>> 16
75  return ((h >>> 0) % 100000) / 100000
76}
77
78// A speck's chance at a share `t` of the way from the left edge to the
79// head, and its chance of the phase's color rather than gray.
80const density = (t: number) => 0.22 + 0.7 * Math.pow(t, 1.4)
81const colored = (t: number) => 0.95 * Math.pow(t, 2.2)
82
83// Two decimals at most, no trailing zeros.
84function n(value: number): string {
85  return String(Math.round(value * 100) / 100)
86}
87
88function escape(text: string): string {
89  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
90}
91
92// The active phase's fill edge, as a share of the track from the left.
93function headShare(flow: Flow): number {
94  const index = FLOW_PHASES.indexOf(flow.phase)
95  const fill = flow.fills[index]
96  return (index + fill.num / fill.den) / 3
97}
98
99// The active phase's fill edge, in pixels from the left of a track `width`
100// pixels wide.
101export function headOf(flow: Flow, width = TRACK_PX): number {
102  return width * headShare(flow)
103}
104
105// The x of each item tick: the active segment's inner item edges k with
106// checked < k < n, none when the items are closer than SPACING. The test
107// compares whole numbers, k × den > num × n, so an edge at the head never
108// draws through rounding.
109export function ticksOf(flow: Flow, width = TRACK_PX): number[] {
110  const segment = width / 3
111  const index = FLOW_PHASES.indexOf(flow.phase)
112  const items = index === 0 ? 0 : flow.items[index - 1]
113  const step = segment / Math.max(items, 1)
114  if (items < 2 || step < SPACING) return []
115  const fill = flow.fills[index]
116  const out: number[] = []
117  for (let k = 1; k < items; k++) {
118    if (k * fill.den > fill.num * items) out.push(segment * index + step * k)
119  }
120  return out
121}
122
123// A pill text splits into a bold label and a dimmer count: `Implement 3/7`.
124function pillParts(pill: string): [string, string] {
125  const match = /^(.*) (\d+\/\d+)$/.exec(pill)
126  return match === null ? [pill, ''] : [match[1], match[2]]
127}
128
129function pillWidth(pill: string): number {
130  const [label, count] = pillParts(pill)
131  return label.length * LABEL_CHAR + (count === '' ? 0 : count.length * COUNT_CHAR + COUNT_GAP) + PILL_PAD
132}
133
134// The pill's text on a track `width` pixels wide: the whole pill when it
135// takes a third of the track or less, else its short text.
136export function pillText(flow: Flow, width = TRACK_PX): string {
137  return pillWidth(flow.pill) * 3 <= width ? flow.pill : flow.short
138}
139
140// The pill's left edge and width: its right edge just past the head, kept
141// inside the track.
142export function pillBox(flow: Flow, width = TRACK_PX): { x: number; width: number } {
143  const w = pillWidth(pillText(flow, width))
144  const x = Math.min(Math.max(headOf(flow, width) - w + 6, 1), width - w - 1)
145  return { x, width: w }
146}
147
148// The specks, one path per color and level, in the desktop palette.
149function specks(flow: Flow, width: number): string {
150  const head = headOf(flow, width)
151  const paths = new Map<string, string[]>()
152  for (let cx = 0; cx * CELL < head; cx++) {
153    const x = cx * CELL
154    // The last column is cut at the head, so no speck runs past it.
155    const w = n(Math.min(CELL, head - x))
156    const t = x / head
157    for (let cy = 0; cy < ROWS; cy++) {
158      if (hash(cx, cy, 1) > density(t)) continue
159      const level = Math.floor(hash(cx, cy, 2) * LEVELS.length)
160      const color = hash(cx, cy, 3) < colored(t) ? flow.phase : 'gray'
161      const key = `${color}:${level}`
162      const cells = paths.get(key) ?? []
163      cells.push(`M${x} ${cy * CELL}h${w}v${CELL}h-${w}z`)
164      paths.set(key, cells)
165    }
166  }
167  return [...paths.entries()]
168    .map(([key, cells]) => {
169      const [color, level] = key.split(':')
170      const fill = color === 'gray' ? GRAY : PHASE_FILLS[flow.phase]
171      return `<path class="specks" data-color="${color}" d="${cells.join('')}" fill="${fill}" fill-opacity="${LEVELS[Number(level)]}"/>`
172    })
173    .join('')
174}
175
176export function trackSvg(flow: Flow, width = TRACK_PX): string {
177  const segment = width / 3
178  const head = headOf(flow, width)
179  const marks = [1, 2]
180    .map(i => {
181      const x = segment * i
182      return `<rect class="edge" x="${n(x - 0.5)}" y="2" width="1" height="${TRACK_H - 4}" fill="${MARK}" fill-opacity="${x < head ? 0.7 : 0.25}"/>`
183    })
184    .join('')
185  const ticks = ticksOf(flow, width)
186    .map(x => `<rect class="tick" x="${n(x - 0.5)}" y="${TRACK_H / 2 - 3}" width="1" height="6" fill="${GRAY}" fill-opacity="0.4"/>`)
187    .join('')
188  const [label, count] = pillParts(pillText(flow, width))
189  const pill = pillBox(flow, width)
190  const countSpan = count === '' ? '' : `<tspan dx="${COUNT_GAP}" fill-opacity="${COUNT_OPACITY}" font-weight="500">${escape(count)}</tspan>`
191  return (
192    `<svg xmlns="http://www.w3.org/2000/svg" width="${n(width)}" height="${TRACK_H}" viewBox="0 0 ${n(width)} ${TRACK_H}">` +
193    `<defs><clipPath id="track"><rect width="${n(width)}" height="${TRACK_H}" rx="${TRACK_H / 2}"/></clipPath></defs>` +
194    `<g clip-path="url(#track)"><rect class="ground" width="${n(width)}" height="${TRACK_H}" fill="${GROUND}"/>` +
195    `${specks(flow, width)}${ticks}${marks}</g>` +
196    `<rect class="pill" x="${n(pill.x)}" y="1" width="${n(pill.width)}" height="${PILL_H}" rx="${PILL_H / 2}" fill="${PHASE_FILLS[flow.phase]}"/>` +
197    // `textLength` holds the text to the estimated width, so a wider
198    // fallback font squeezes the text rather than running past the pill.
199    `<text class="pill-text" x="${n(pill.x + PILL_PAD / 2)}" y="${TRACK_H / 2}" textLength="${n(pill.width - PILL_PAD)}" lengthAdjust="spacingAndGlyphs" dominant-baseline="central" font-family="-apple-system,system-ui,sans-serif" font-size="10.5" fill="${PILL_LABEL}">` +
200    `<tspan font-weight="650">${escape(label)}</tspan>${countSpan}</text>` +
201    `</svg>`
202  )
203}
204
205// The terminal track's ground and the pill's text color as theme keys, and
206// its blank cell and its mark at each third as braille characters, the
207// mark drawn in `MARK_KEY` and the specks in the phase's key or
208// `SPECK_KEY`. The pill's text is `inverseText` on the phase's key (M217):
209// white in the light themes, black in the dark.
210export const BRAILLE_GROUND = 'userMessageBackground'
211export const BRAILLE_BLANK = '⠀'
212export const BRAILLE_MARK = '⡇'
213const MARK_KEY = 'subtle'
214const SPECK_KEY = 'inactive'
215export const PILL_TEXT = 'inverseText'
216// The eight dots of a braille cell, as bits of its code point.
217const DOTS = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]
218
219// The terminal track `cells` columns wide: the specks as braille dots, the
220// pill (one space each side of its text), and a mark at each third past the
221// head. The pill ends at the head's cell, or starts there when that would
222// leave no speck before it. Either way it is then kept inside the track, so
223// on a short track the head can fall inside the pill. The last speck
224// before the pill or the head always draws in the phase's color, so a short
225// track still shows its fill. A track too short for the whole pill in a
226// third of it shows the short text. Runs of one style merge into one span.
227export function brailleSpans(flow: Flow, cells: number): Span[] {
228  const color = FLOW_COLORS[flow.phase]
229  const head = Math.round(cells * headShare(flow))
230  const full = ` ${flow.pill} `
231  const pill = full.length * 3 <= cells ? full : ` ${flow.short} `
232  const before = head - pill.length
233  const start = Math.max(0, Math.min(before >= 1 ? before : head, cells - pill.length))
234  const lastSpeck = Math.min(start, head) - 1
235  const thirds = [Math.round(cells / 3), Math.round((2 * cells) / 3)]
236  const out: Span[] = []
237  const push = (text: string, style: Omit<Span, 'text'>) => {
238    const last = out[out.length - 1]
239    if (last !== undefined && last.color === style.color && last.backgroundColor === style.backgroundColor && last.bold === style.bold) {
240      last.text += text
241    } else {
242      out.push({ text, ...style })
243    }
244  }
245  for (let i = 0; i < cells; i++) {
246    if (i >= start && i < start + pill.length) {
247      push(pill[i - start], { color: PILL_TEXT, backgroundColor: color, bold: true })
248      continue
249    }
250    if (i >= head) {
251      const mark = thirds.includes(i)
252      push(mark ? BRAILLE_MARK : BRAILLE_BLANK, { color: MARK_KEY, backgroundColor: BRAILLE_GROUND })
253      continue
254    }
255    const t = i / head
256    let bits = 0
257    DOTS.forEach((bit, k) => {
258      if (hash(i, k, 1) < density(t)) bits |= bit
259    })
260    const last = i === lastSpeck
261    const hue = last || hash(i, 0, 3) < colored(t) ? color : SPECK_KEY
262    if (last && bits === 0) bits = 0xff
263    push(String.fromCharCode(0x2800 + bits), { color: hue, backgroundColor: BRAILLE_GROUND })
264  }
265  return out
266}
267
types/index.d.ts 179 lines
1// The cairn plugin's `$.state` contract: the values its hooks module keeps
2// for the session. `claude plugin validate` holds the module to it.
3
4// One active milestone. The counts and next items are null when its
5// milestone path is not a readable regular file; a next item is also null
6// when its section holds no open box.
7export type CairnBandRow = {
8  id: string
9  title: string
10  status: string
11  tasksChecked: number | null
12  tasksTotal: number | null
13  criteriaChecked: number | null
14  criteriaTotal: number | null
15  nextTask: string | null
16  nextCriterion: string | null
17}
18
19// A planned milestone whose dependencies are all done.
20export type CairnWorkableRow = { id: string; title: string }
21
22// The active milestones in ROADMAP order, the workable planned milestones
23// by priority and then id, and the repo root of the last read, null when no
24// ROADMAP was found or the working directory could not be read (M210).
25export type CairnBandState = { rows: CairnBandRow[]; workable: CairnWorkableRow[]; root: string | null }
26
27// One active milestone's id and status, as the close button stores them.
28export type CairnBandMark = { id: string; status: string }
29
30// What the close button stores at a press: the active ids and statuses in
31// ROADMAP order, `milestone-review` while that skill runs and moves the band
32// to another row, else null, and the idle row's id while no row is active
33// (M206). A step stored before a reload that names a skill the cairn list
34// has since dropped reads as no step (M200).
35export type CairnBandHidden = { marks: CairnBandMark[]; skill: string | null; idle: string | null }
36
37// The running cairn skill's bare name (`milestone-plan`). A main-loop Stop
38// with no background work in flight, or a prompt the operator types while
39// the session is idle, ends it (M201).
40export type CairnStep = { skill: string }
41
42// One checkbox item of a milestone file's Tasks or Acceptance criteria,
43// less its box, with a wrapped item's lines joined (M205).
44export type CairnPaneItem = { text: string; checked: boolean }
45
46// One active milestone as the cairn pane shows it. `file` is null when the
47// milestone file is missing or its read fails; `log` holds the newest five
48// work-log lines, less their `- `, which the pane has not drawn since M286.
49export type CairnPaneMilestone = {
50  id: string
51  title: string
52  status: string
53  file: { goal: string; tasks: CairnPaneItem[]; criteria: CairnPaneItem[]; log: string[] } | null
54}
55
56// What the cairn pane shows (M205): `found` is false when no ROADMAP is
57// found. `next` is `recommend` in scripts/cairn_next.py, its `id` null for
58// planning and its `title` the short title `highTitle` names while
59// planning (the first `[high]` candidate row no counted started token
60// names, every `#` token counted), else null (M272, M273); the band's Plan
61// press picks its own row (`nextTitle`), and since M305 the pane's Next
62// line names none. `waiting` is its `waiting`, each row's undone dependencies
63// as written with their status. `candidates` holds the ROADMAP's candidate
64// rows, each its priority, its short title (the text before its first
65// `: `, else before its first ` — `, else all of it; M207, M251), and its
66// whole text after the priority token, trimmed (M293).
67// `blocked` holds the `blocked` rows in ROADMAP order, each with the number
68// of the pull request its milestone file's `Branch/PR` header names, or
69// null (M223), and that pull request's URL up to its number, or null (M224).
70// `archived` is true when the row's file is gone and its one archive file
71// reads done, the number and URL then read from its Status paragraph (M246).
72// `taken` holds each candidate row's ` — started <ref>` token with the row's
73// short title: an `M<NNN>` token only while the table holds that id as
74// `planned` or `blocked`, and every `#<n>` token (M258).
75export type CairnPaneState = {
76  found: boolean
77  milestones: CairnPaneMilestone[]
78  next: { action: string; command: string; id: string | null; title: string | null } | null
79  workable: CairnWorkableRow[]
80  waiting: { id: string; title: string; unmet: string[] }[]
81  // `parked`: a row whose promotion condition has not held (M284).
82  candidates: { priority: 'high' | 'normal' | 'low' | 'parked'; title: string; text: string }[]
83  blocked: { id: string; title: string; pr: number | null; url: string | null; archived: boolean }[]
84  taken: { title: string; ref: string }[]
85}
86
87// The state word of a blocked milestone's pull request, as the pane last
88// read it from `gh api graphql`, or from `gh pr view` for a URL on another
89// host (M224, M237).
90export type CairnPrWord = 'merged' | 'closed' | 'changes requested' | 'approved' | 'in review' | 'unknown'
91
92// An open pull request's merge state, from GitHub's `mergeable` field
93// (M301): MERGEABLE reads `mergeable` and CONFLICTING reads `conflicts`.
94export type CairnPrMerge = 'mergeable' | 'conflicts'
95
96// One read of a blocked milestone's pull request: its state word (M224),
97// and for an open one, its review threads not marked resolved (M225, M236).
98// `counts` is null for a pull request that is not open, or whose threads
99// failed the shape check (M237). `mergeable` is null for a pull request
100// that is not open, or whose `mergeable` is UNKNOWN, another value, or
101// absent (M301).
102export type CairnPrRead = { word: CairnPrWord; counts: { unresolved: number } | null; mergeable: CairnPrMerge | null }
103
104// One open pull request that the operator opened from a `hotfix-*` branch,
105// as `gh pr list` gave it (M226).
106export type CairnHotfixPr = { number: number; title: string; url: string }
107
108// One `Candidate row: <short title>` line of an open pull request's body,
109// with that pull request's number, from any head branch (M252).
110export type CairnStartedRow = { title: string; number: number }
111
112// The hotfix list that the last read wrote, and the repo root it is for
113// (M226): a good `gh pr list` read's result, the list kept after a failed
114// call in the same root, or empty when no call ran or the kept list was
115// for another root. `root` is null before any read and when no ROADMAP
116// root was known. `started` holds the same read's candidate rows that the
117// listed bodies name, kept and emptied with `prs` (M252).
118export type CairnHotfixRead = { root: string | null; prs: CairnHotfixPr[]; started: CairnStartedRow[] }
119
120// The summary card's numbers (M286): the base remote repo's open pull
121// requests and open issues, and the milestones done since the latest
122// release tag, with the whole days since that tag's commit. `counts` is null
123// until a read for `root` gives numbers, and a read that gives none keeps
124// the last good ones for the same root. `done` is the last read's, null
125// when that read could not count. `name` is the project name the last read
126// for `root` found (M291), null only with no root, and '' for a root with
127// no folder name, such as `/`. `web` is the repo page of the last read's
128// github.com base remote (M311), null for any other remote, for none, and
129// for an owner or repo name a link cannot carry. The shape moved to
130// `repo-2` with `days`, to `repo-3` with `name`, and to `repo-4` with `web`.
131export type CairnRepoCounts = { prs: number; issues: number }
132export type CairnRepoDone = { tag: string; days: number; count: number }
133export type CairnRepoRead = {
134  root: string | null
135  counts: CairnRepoCounts | null
136  done: CairnRepoDone | null
137  name: string | null
138  web: string | null
139}
140
141declare module 'claude-code' {
142  interface PluginState {
143    // Each value is kept under a shape tag (register.tsx), so a value an
144    // older layout wrote reads as absent after a reload. `dismissed` is
145    // null while the band shows, and `step` is null while no cairn skill
146    // runs.
147    cairn: {
148      band: Shaped<CairnBandState>
149      dismissed: Shaped<CairnBandHidden | null>
150      step: Shaped<CairnStep | null>
151      // True from a cairn skill's prompt until the next prompt, Stop, turn
152      // end, or session end (M201).
153      expanded: Shaped<boolean>
154      // True from a Stop that ends a cairn skill's step until the next idle
155      // typed prompt that enters, cairn skill, or session end. A row that
156      // draws the action Buttons then carries the Clear Button too, when it
157      // has room (M216).
158      ended: Shaped<boolean>
159      // What the cairn pane shows, written at each refresh (M205).
160      pane: Shaped<CairnPaneState>
161      // Each blocked milestone's pull request state word, its counts, and
162      // its merge state, by its URL, as the last read at a pane open or a
163      // Refresh press found them (M224, M225, M301). A URL with no entry has
164      // not been read.
165      prs: Shaped<Record<string, CairnPrRead>>
166      // The open hotfix pull requests and the repo root they are for, as
167      // the last read at a pane open or a Refresh press wrote them (M226).
168      // Their words and counts sit in `prs` by URL.
169      hotfixes: Shaped<CairnHotfixRead>
170      // The summary card's numbers, written by the same read (M286).
171      repo: Shaped<CairnRepoRead>
172      // True from the start of a read of the pull request states until the
173      // newest read started has settled, while the pane's ↻ Button reads ⋯
174      // (M236).
175      reading: Shaped<boolean>
176    }
177  }
178}
179