A spellbook of agent skills for AI. Cast wisely. Four skills: eagle-eye, which lays coupled decisions out as a morphological box and renders one self-contained…

<img src="docs/brand/grimoire/grimoire-mark.svg" width="128" alt="grimoire mark">
<h1 align="center">G R I M O I R E</h1>
<a href="skills/contract"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/brand/contract/contract-sigil-dark.svg"><img src="docs/brand/contract/contract-sigil-light.svg" width="112" alt="contract"></picture></a> <a href="skills/head-chef"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/brand/head-chef/head-chef-sigil-dark.svg"><img src="docs/brand/head-chef/head-chef-sigil-light.svg" width="112" alt="head-chef"></picture></a> <a href="skills/eagle-eye"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/brand/eagle-eye/eagle-eye-sigil-dark.svg"><img src="docs/brand/eagle-eye/eagle-eye-sigil-light.svg" width="112" alt="eagle-eye"></picture></a> <a href="skills/groundtrack"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/brand/groundtrack/groundtrack-sigil-dark.svg"><img src="docs/brand/groundtrack/groundtrack-sigil-light.svg" width="112" alt="groundtrack"></picture></a>
A skill is a folder of instructions your coding agent reads when the moment calls for it — a reference book it knows when to open. Grimoire holds four. contract helps you build a skill, an agent or a CLAUDE.md of your own. head-chef lets one Claude Desktop session start and lead others, and comes with a pane that shows them. eagle-eye and groundtrack do the same kind of work: they take something you can only hold in your head and put it on a page you can look at.
[See one before you install anything.][gallery] The gallery holds every page eagle-eye and groundtrack have drawn. Start with [a live decision grid][eagle-demo] about whether to publish this repository. Click an option and watch it recolour. eagle-eye wrote it, about itself.
Four skills today, more later. Works with any agent:
npx skills@latest add mephistopheles4/grimoire
That is skills, which installs into Claude Code, Cursor, Codex, Gemini CLI, Copilot, Windsurf, Zed, opencode, Amp and around seventy more. It copies the whole skill directory, renderer included.
The Brigade pane needs grimoire installed as a Claude Code plugin. The command above copies skill folders only, so it gives you head-chef but not /brigade. To get both, run:
claude plugin marketplace add mephistopheles4/grimoire
claude plugin install grimoire@mephistopheles4
As a Claude Code plugin, if you would rather the marketplace handled updates:
/plugin marketplace add mephistopheles4/grimoire
/plugin install grimoire@mephistopheles4
Plugin skills are namespaced, so that route invokes them as /grimoire:eagle-eye, /grimoire:groundtrack, /grimoire:contract and /grimoire:head-chef. The installer route keeps the plain /eagle-eye, /groundtrack, /contract and /head-chef.
By hand, if you want neither installer:
git clone https://github.com/mephistopheles4/grimoire.git
cp -r grimoire/skills/eagle-eye ~/.claude/skills/
cp -r grimoire/skills/groundtrack ~/.claude/skills/
cp -r grimoire/skills/contract ~/.claude/skills/
cp -r grimoire/skills/head-chef ~/.claude/skills/
Pinned to one commit, if you want a copy that only changes when you choose. Use the full 40-character commit SHA:
npx skills@latest add mephistopheles4/grimoire#<commit-sha>
No skill names a fixed path to its own scripts, so each runs from wherever it lands. eagle-eye has been run from three directories: the author's skills folder, the plugin install, and a copy made by skills.
Every route gives you all four skill directories, each with its SKILL.md and the scripts that go with it. Only the plugin route also gives you the Brigade pane. Each skill carries a README of its own, which is where it is documented; contract, eagle-eye and head-chef also carry the CONTRACT.md their SKILL.md is generated from. What follows is only enough to tell you which one you want.
Agree the terms first. The prompt is build output.
Reach for it when you want a skill, an agent or a CLAUDE.md of your own and have never written one. contract interviews you through a template, one question at a time, and writes your answers down as a contract. What you build is a skill, an agent or a main agent file (a CLAUDE.md) that does one job for you.
It then generates the file from the contract and validates it with claude plugin validate --strict. When a skill or agent goes wrong, you amend the contract and generate the file again. It never installs what it builds. Not for a one-off prompt.
The questions, the levels and the marks: skills/contract/references/template.md. The skill's own contract, which its SKILL.md is generated from: skills/contract/references/CONTRACT.md.
Lead the sessions; let them do the work.
Reach for it in Claude Desktop when you want work to run in another session, or want to lead several at once. head-chef starts each session as a Desktop session under the lead, one you can talk to directly, with the model and effort set. Its start prompt points the session to its issue, which holds the brief. It takes the session's milestone reports, relays between sessions, and cleans a session up when you say it is done, after one name-back and one yes. It takes the when and the why from your own process, and it never counts a message from another session as your yes to start, archive or delete. On your own words in its chat, it can also merge, close, edit, delete or label an issue or a pull request, file an issue, or post a comment. The sessions it starts take a message from the lead as a relayed decision, labelled so; a session cannot tell a forged sender from the lead. Before its first launch in a lead, a permission warning above the prompt says so. Read the skill's README before you install. Not for work in the same session.
/brigade opens the Brigade pane, and so does loading the head-chef skill from the plugin or from your own skills folder: one compact row per session the lead started. A switch at the top shows either Sessions or Pull requests, and the pane opens on Sessions each time. Sessions keeps three foldable groups: Waiting on you, Working, and Done · stopped, which starts folded and counts the reports its sessions sent since you opened the pane. A row shows a checkbox, a status dot, the title, the phase, the latest report's first line, the live busy or idle state (a session that waits on you moves its row under Waiting on you, and a row shows the session's own title) and how long the session has been in its status and phase. Model and effort show as one character each, with the full settings in a tooltip. Open and Dismiss appear when you point at a row; in the terminal they are always shown. Tick several rows and a bar at the foot dismisses them together. A session that waits on you has no Dismiss and is never hidden. Reopening the pane brings dismissed rows back. The pane's section bars, hover and selection bar are drawn for Desktop's dark theme, so in a light theme they look darker than the rest of the app.
The lead can put each session's pull request on its row. A pill shows the number in the state's colour. The Pull requests view lists those pull requests grouped Open, Merged and Closed, with title, added and removed lines, repository and age. While the pane is open and a row carries a pull request, the pane asks gh for the details once a minute, and stops once every pull request it shows is merged. The details need gh installed, signed in, and run from a github.com repository. On macOS and Linux the pane also asks only when every folder on PATH is an absolute path. Without them the pill shows the number and the state the lead last knew, and the Pull requests view says "PR details unavailable". A pull request opened from a fork is never shown as the brigade's.
A row that waits on you and holds a large context says when to reply to keep its cache, or suggests a hand-off once it has gone cold. Under its cache bar, a context meter shows how full the session's context is: amber from 70%, red from 90%. Icon buttons on the row switch to two more views. Burn rate is a sparkline of the new tokens the session spent in each of the last 30 minutes, with its rate per minute. Context trend is a sparkline of its last 30 calls' context; it marks each call under half the one before it, a compaction, and counts them. A row shows these buttons only when it has more than one view, and keeps your choice while the lead session lasts. The reply reminder shows under whichever view you chose. At the bottom of the pane it shows the lead session's own rate limits and context. A faint extension on the session and weekly limit bars shows where each will be at its reset if the current pace holds, and a red note says how early a limit runs out when that pace would pass 100%. It needs the plugin install above. The skill works without it.
What it does, what counts as your yes, and how cleanup refuses: skills/head-chef/README.md. The skill's contract, which its SKILL.md is generated from: skills/head-chef/references/CONTRACT.md.
Since 0.60.0 every session with the plugin writes its own usage numbers to a small summary file. Since 0.61.0 the pane draws a member's card from that file whenever it passes its checks, so a member whose transcript is too large to read keeps its cache line, context meter and views. A card that reads "summary path refused" or "not a summary file" is drawn from its transcript instead: the member's file failed the path check, or the same file failed its checks two polls running. SECURITY.md says where the files are. Since 0.62.0 a member keeps the Remote Control link the pane read while its transcript was 4 MiB or less, once the transcript grows past that and after a plugin reload. Known limits: a member first seen with a transcript already over 4 MiB, or one that turned Remote Control on after it passed 4 MiB, shows no link; and after a reload, a card whose name moved to another large session can show the old session's link. If you notice a missing link, a read of just the start of a large transcript, through a process, is the next step (issue #308). SECURITY.md says what the file holds and who can read it. Known limit: a card the pane draws from that file counts its cache down from 1 hour after the last call, because the engine's per-call usage does not say whether a call cached for 5 minutes or for 1 hour. A session whose main conversation is not on the 1-hour cache can then show warm for up to 55 minutes after its cache went cold, and its "reply within N min" reminder comes up to 55 minutes late. This holds at every transcript size, including members whose transcript the pane could read and whose window it showed correctly before. Examples: a session in usage overage; a session on an API key, or on Bedrock, Vertex or Foundry, without the 1-hour opt-in; a session through the Claude apps gateway, or a gateway that drops the 1-hour header; and a session where a setting or environment variable chooses 5 minutes.
A decision is made once it has been seen against the whole system.
Reach for it when three or more decisions are open and one choice changes what is possible in another: picking the cheap database changes what the deployment can be, which changes who can be on call. Asked one at a time, those questions hide the thing you need to see.
eagle-eye draws a morphological box instead — one row per decision, one cell per option, an edge wherever two options rule each other out or require each other — then renders a page that reads any configuration back. Not for two independent choices.
Live: [the decision to publish this repository][eagle-demo].
The seven findings, why every edge carries an evidence tier, and the renderer's flags: skills/eagle-eye/README.md.
A reader who did not write a change cannot see its shape.
Reach for it when a plan is made or the work is done and someone else has to understand it. A change arrives as a list of files. A plan arrives as a list of tickets. Neither says what calls what, what each part hands back, where it can break, or what it needs in order to work.
groundtrack writes one call graph with recorded traces through it, renders a self-contained page you can step a cursor across, and prints the same graph as an indented tree on request. Not for a conversation, because nothing durable exists to check the graph against.
Live: [a pull request, stepped through][track-demo]. For a complex sheet, see [a larger pull request with 88 nodes][track-complex]. Every published page is in [the gallery][gallery].
The three channels, what a layer redraws, the page's controls, and the honesty property's stated limit: skills/groundtrack/README.md.
The marks, the cards and the tokens behind them are in docs/brand/.
The repository is the plugin. .claude-plugin/plugin.json names it grimoire; .claude-plugin/marketplace.json is the shelf that lists it with "source": "./". Skills sit at skills/<name>/, which is the one level the default scan reads and the layout the skills installer finds first.
The two manifests carry different names on purpose: the shelf is mephistopheles4, the book is grimoire. The version lives in plugin.json and nowhere else, because a second copy is a second place to forget.
This shape follows mattpocock/skills, which ships a marketplace manifest and a plugin manifest side by side at the root. The Claude Code docs describe each separately and never that pairing, so the evidence it works is a repository that does it, plus claude plugin validate . passing here.
On claude.ai chat and in Cowork, only the four skills load. Brigade is a mod, so it runs only in Claude Code: the terminal, the Desktop app's Code tab and the VS Code extension. head-chef needs Claude Code in the Desktop app, git and a signed-in gh.
Everything the plugin runs, sends or writes beyond reading and writing the files you ask for:
audit.mjs) sends the box's text to TypeSafe, or to OpenRouter, which passes it on to TypeSafe. It runs only when you set TYPESAFE_API_KEY or OPENROUTER_API_KEY, and the skill does a dry run and asks for your yes in chat first. EAGLE_EYE_AUDIT_ENDPOINT points it at another endpoint. Each request is charged to your key.gh pr list once a minute for the pull requests its rows carry, which uses your GitHub sign-in. It reads Claude Code's own session files and the transcripts of the sessions the lead started. It writes a roster file and a usage summary file in the plugin's data folder; the summary file is written in every session, pane open or not. Open in app asks the Desktop app to show a session, or opens a claude:// link with your system's opener.set_roster tool, which writes the roster file, the show_permission_warning tool, which shows a reminder, and Open in app's call to the Desktop app's mcp__ccd_window__open_session_in. A deny rule for each name stops it.What each of Brigade's hooks does with what it sees:
| Hook | What it does |
|---|---|
session.start, classic.SessionStart | Registers /brigade, notes the session's id and transcript path to find the plugin's data folder, and offers show_permission_warning, and set_roster while the pane is open, again after a reload, a clear or a resume. It changes nothing in the event and passes it on. |
command.run for /brigade | Opens the pane. It answers only /brigade. |
skill.prompt | Opens the pane when the head-chef skill loads from grimoire or your own skills folder, or finds it open, and adds one line to that skill's text saying whether set_roster is ready, or why not. Every other skill load passes on unchanged. |
tool.call for Skill, and command.run for /head-chef and /grimoire:head-chef | Watch a head-chef load for the case where skill.prompt never reached the plugin (see below). Each reads the skill's or command's name and the load's answer, and returns that answer unchanged; where skill.prompt was skipped, a typed load also reads the session's local skill list once. Any other skill, and a subagent's load, passes on with no other work. |
tool.call for set_roster and show_permission_warning | Answers for the mod's own two tools, which have no other code behind them. |
turn.start | Only after a head-chef load whose pane was open but not shown, not yet listed, or opened without its reads: looks at the pane once a turn, and once it is shown and listed, starts the pane's reads, offers set_roster if it was not offered yet, and adds one note saying it is ready. Otherwise, and on a subagent's turn, it passes on with no other work. It reads no text of the prompt. |
turn.step, turn.complete | Counts each model call's token numbers for the usage summary file. It reads no text of the conversation and passes every step on unchanged. |
session.measure, session.receive | While the pane is open, refreshes the usage numbers and keeps the first line of each report another session sends. |
ui.render, ui.press, ui.close | Draws the pane and the warning band, and handles their buttons. |
Claude Code's bundled security default, on a machine with managed settings or a Team or Enterprise account, keeps the plugins you install from seeing skill.prompt and classic.SessionStart. What Brigade does with and without it:
| Without the security default | With it | |
|---|---|---|
A typed /head-chef | skill.prompt opens the pane, with one line in the skill's text | after the load, the pane opens if the session's local skill list shows the loaded copy is grimoire's or yours and no other copy of that name is listed, with one note; otherwise a note asks for /brigade |
| The model loading head-chef itself | the same as typed | no pane: one note asks for /brigade |
| A pane opened but not shown, or not yet listed | its reads, and set_roster with one note if it was not offered yet, start at the first turn that finds it shown and listed | the same |
| A refused or failed load | nothing | nothing |
/brigade | as before | as before |
The session id, set_roster after a resume, show_permission_warning | as before | from session.start and the id read live |
| The transcript path | from classic.SessionStart | not known: the data folder comes from where the plugin is installed, and the pane says when it cannot find it |
Nothing the mod reads leaves the machine except the gh pr list request above and Open in app's two routes: the call to the Desktop app carries the session's id and the fixed target split, and the fallback hands a checked claude:// link to your system's opener.
The threat model, docs/security/threat-model.md, has the detail and the accepted risks.
CONTRIBUTING.md. The contract is one command:
node scripts/check.mjs
Security problems go through private reporting, not a public issue: SECURITY.md.
MIT. © 2026 Ayman Diab.
[eagle-demo]: https://mephistopheles4.github.io/grimoire/docs-decisions-publish-eagle-eye.html [track-demo]: https://mephistopheles4.github.io/grimoire/skills-groundtrack-examples-pr-313.html [track-complex]: https://mephistopheles4.github.io/grimoire/docs-examples-realtime-shadows.html [gallery]: https://mephistopheles4.github.io/grimoire/
brigade/register.tsx 2184 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Card, Roster } from './types'
5import type { Moves } from './view.ts'
6import {
7 GH_ARGV,
8 MAX_ROSTER_BYTES,
9 PR_NUMBER,
10 PR_STATES,
11 MAX_TEXT,
12 OPEN_NAME,
13 OPEN_SERVER,
14 OPEN_TARGET,
15 OPEN_TOOL,
16 OPEN_WAIT_MS,
17 SESSION_ID,
18 STATUSES,
19 HOST_PROBES,
20 appLink,
21 checkRoster,
22 dataFolder,
23 dataPlace,
24 listsOpenTool,
25 liveWord,
26 listedAsOurs,
27 lookup,
28 matchRows,
29 skillLoadRan,
30 typedLoadRan,
31 oneLine,
32 openerArgv,
33 parsePrList,
34 placeRoster,
35 readOpenAnswer,
36 remoteLink,
37 report,
38 rosterFile,
39 rulesAllowTool,
40 serialize,
41 stampSince,
42 statRejection,
43 toolSession,
44 probeHost,
45 windowsEnv,
46 rowMove,
47} from './roster.ts'
48import type { GhPr, HostOs, StatAnswer } from './roster.ts'
49import {
50 CACHE_CELLS,
51 EMPTY_USAGE,
52 GROUP_HINTS,
53 GROUP_KEYS,
54 GROUP_NAMES,
55 linksOnRoster,
56 MAX_NAME,
57 MAX_PICKED,
58 MAX_TRANSCRIPT_BYTES,
59 SESSIONS_UNREAD,
60 SVG_MAX,
61 VIEW_LABELS,
62 ageText,
63 addSample,
64 burnRate,
65 cacheBar,
66 cacheBarSvg,
67 cacheCells,
68 cardViews,
69 chooseTab,
70 chosenView,
71 contextCells,
72 contextMeter,
73 contextMeterSvg,
74 compactSettings,
75 contextTrend,
76 drawnTitle,
77 foldedFrom,
78 groupCards,
79 liveFrom,
80 movedLook,
81 movesFrom,
82 hairlineSvg,
83 idsFrom,
84 isReason,
85 linkStep,
86 liveState,
87 metersFrom,
88 newFinder,
89 newSummaryMemory,
90 pickedFrom,
91 pillColor,
92 pillSvg,
93 pillState,
94 prUrl,
95 prNumber,
96 prRows,
97 readCalls,
98 readSessions,
99 refusalLines,
100 reportCount,
101 reportNote,
102 settleTicks,
103 sizeText,
104 snapshotFrom,
105 sparkRuns,
106 sparkSvg,
107 statusOf,
108 statusStrip,
109 ticksFrom,
110 todoBar,
111 toggleTick,
112 usageView,
113 viewFrom,
114 viewOf,
115 waitingCount,
116 warmthFrom,
117 warmthLine,
118 withoutSize,
119} from './view.ts'
120import type { Finder, PrRow, ReadMemory, Spark, SummaryMemory } from './view.ts'
121import { registerWriter, writerEpoch, writerSession } from './writer.ts'
122import { DESCRIPTION as WARNING_DESCRIPTION, SCHEMA as WARNING_SCHEMA, STORE_KEY as WARNING_KEY, TOOL as WARNING_TOOL, ackFrom, registerWarning } from './warning.tsx'
123
124// The Brigade pane: one compact row per session a lead session started, in
125// three foldable groups (Waiting on you, Working, Done · stopped) behind a
126// switch to a Pull requests view. A row shows its status dot, title, phase,
127// live busy or idle state, age, PR pill and latest report, and on a needs-you
128// or working row the cache warmth, context meter and the burn and trend views;
129// the owner's to-dos sit under Waiting on you, each ticked with a press that a
130// second press undoes; at the foot are the selection bar and this session's
131// own rate limits and context. The pane reads the roster file while it is
132// open, and asks `gh` for the PR details once a minute. The head chef fills
133// the roster through the set_roster tool below, which writes the file for it
134// with no permission prompt; the head chef writes no file itself. The usage
135// section is worked out in view.ts, as plain values; this file reads and
136// stores the reading and turns the view's result into elements.
137//
138// The pane waits for /brigade or the head-chef skill's load. At session start
139// it registers /brigade, the skill hook and the usage summary writer
140// (writer.ts), reads the engine clock and the session id once for the writer,
141// and nothing else: no timer, no process, no file read, no tool and no pane.
142// The writer's hooks record each step and write this session's own summary
143// file; ADR 0008 records why the mod is no longer idle by default. The pane
144// opens only on /brigade or when the plugin's own or the owner's own
145// head-chef skill loads with the pane closed, and closing it stops every
146// timer. A message from another session never opens it directly.
147
148const PANE = 'brigade'
149const TITLE = 'Brigade'
150const ROSTER_MS = 5000
151// The live poll reads the engine's session files this often (#347).
152const LIVE_MS = 10000
153const GH_MS = 60000
154const TOOL = 'set_roster'
155
156// The values are the plugin's, so they sit under its manifest name.
157const armed = atom({ plugin: 'grimoire', key: 'armed' } as const, false)
158// The engine's record of a session's start, the last one raised; writer.ts reads the same key.
159const started = atom({ plugin: 'grimoire', key: 'start' } as const, { sessionId: '', transcript: '' })
160const files = atom({ plugin: 'grimoire', key: 'files' } as const, { current: '', previous: '' })
161const roster = atom({ plugin: 'grimoire', key: 'roster' } as const, { cards: [], todos: [] })
162const rosterError = atom({ plugin: 'grimoire', key: 'rosterError' } as const, '')
163const live = atom({ plugin: 'grimoire', key: 'live' } as const, [])
164const liveError = atom({ plugin: 'grimoire', key: 'liveError' } as const, '')
165const links = atom({ plugin: 'grimoire', key: 'links' } as const, [])
166const reports = atom({ plugin: 'grimoire', key: 'reports' } as const, [])
167const dismissed = atom({ plugin: 'grimoire', key: 'dismissed' } as const, [])
168const doneTodos = atom({ plugin: 'grimoire', key: 'doneTodos' } as const, [])
169const ticking = atom({ plugin: 'grimoire', key: 'ticking' } as const, [])
170const usage = atom({ plugin: 'grimoire', key: 'usage' } as const, EMPTY_USAGE)
171const samples = atom({ plugin: 'grimoire', key: 'samples' } as const, [])
172const warmth = atom({ plugin: 'grimoire', key: 'warmth' } as const, [])
173const meters = atom({ plugin: 'grimoire', key: 'meters' } as const, [])
174const refusals = atom({ plugin: 'grimoire', key: 'refusals' } as const, [])
175const tabs = atom({ plugin: 'grimoire', key: 'tabs' } as const, [])
176// The chosen view, the selected cards and the folded groups. Each is read
177// again through its fixed set or shape before use (view.ts).
178const viewAtom = atom({ plugin: 'grimoire', key: 'view' } as const, 'sessions')
179const picked = atom({ plugin: 'grimoire', key: 'picked' } as const, [])
180const folded = atom({ plugin: 'grimoire', key: 'folded' } as const, [])
181// The group that starts folded each time the pane opens.
182const STARTS_FOLDED = ['finished']
183
184// Text and status colours are the app's own theme keys, so they follow the
185// person's theme, light or dark, as the rest of Claude Code does; the fills
186// are the fixed colours below. The status the head chef wrote on a card, and
187// the live state, take theirs from view.ts.
188
189// The cells of the cache block's label column, the width of "◆ context", so
190// the cache bar and the context meter start at the same place.
191const LABEL_CELLS = 9
192
193// A button's key: the verb, the card's place, and its title folded to letters
194// and digits, so a press finds the card it was drawn for or nothing.
195const slug = (title: string) => title.toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 40)
196const keyFor = (verb: string, i: number, title: string) => `${verb}-${i}-${slug(title)}`
197// A Button must carry onPress. The ui.press hook below answers every press
198// itself, so this bottom of the chain never runs.
199const noop = () => {}
200// The prototype's fills, read off Desktop's dark theme, for every surface that
201// draws images: fixed values, never from file data. No theme key draws them,
202// and the engine names none for the pane's background, so the pane takes
203// them and reads poorly in a light theme (the owner's decision at the
204// rebuild's visual check). A round border in a fill's own colour rounds it;
205// one in the pane's colour is unseen at rest, so a hover rounds a card.
206const DARK_FILLS = {
207 pane: '#1a1a19',
208 bar: '#2b2b2a',
209 hover: '#262625',
210 tip: '#3a3a38',
211} as const
212// The icon of each card view, with its name in the tooltip. A Button carries
213// no `label`: a desktop draws the label in place of the Button's text.
214const VIEW_ICONS: ReadonlyMap<string, string> = new Map([
215 ['cache', '◆'],
216 ['burn', '↯'],
217 ['trend', '∿'],
218])
219// A to-do's checkbox on the terminal: one plain space at rest, in a slot as
220// wide as `[ ✓ ]`. A desktop gives a native button a minimum width the label
221// no longer sets (#396), so there a to-do's box is a plain ○ that a press
222// turns into ✓, and a card is selected by pressing its status dot, drawn
223// the same way in its status colour. Each sits in a slot CHECK_CELLS_DESKTOP
224// wide, so the text beside it never moves when it is ticked.
225const UNTICKED_TERMINAL = ' '
226const CHECK_CELLS_TERMINAL = 5
227const CHECK_CELLS_DESKTOP = 3
228
229// The module's own timers. A reload starts the module over and the engine
230// drops the old timers with it.
231let timers: Timer[] = []
232
233// Where this lead session's roster file is, or why it cannot be named. The
234// roster lives in the plugin's data folder, built by the plugin-manifest
235// reference's rule from the config folder alone: <config>/plugins/data/<id>.
236// `CLAUDE_PLUGIN_DATA` is never read: a mod's environment usually lacks it,
237// and another plugin can set it. The config folder comes from where the plugin
238// was installed, else from the transcript path the engine reported at a
239// session's start, else from Desktop's synced install folder (`dataPlace`,
240// which the usage summary writer shares); with none, nothing is read or
241// written. The config folder also locates other
242// sessions' transcripts.
243type Where = { file: string; config: string; plugin: string; id: string }
244async function where($: EngineInterface): Promise<Where | { error: string }> {
245 const id = await $.session.id()
246 if (!SESSION_ID.test(id)) return { error: 'the session id is not the engine\'s shape, so no roster file is named. Nothing was read.' }
247 const { config, plugin } = dataPlace($.plugin.root, $.plugin.name, await read($, started))
248 if (config === undefined) {
249 return {
250 error: `Cannot find the Claude config folder from where the plugin was loaded. The roster would be <Claude config folder>/plugins/data/${plugin}/brigade/${id}.json. Nothing was read.`,
251 }
252 }
253 return { file: rosterFile(dataFolder(config, plugin), id), config, plugin, id }
254}
255
256// One `stat` for the path rule in roster.ts: resolving, and a rejection
257// sorted into missing or failed by its message.
258function statPath($: EngineInterface, path: string): Promise<StatAnswer> {
259 return $.fs.stat(path, { resolve: true }).then(
260 found => ({ found }),
261 err => statRejection(String(err instanceof Error ? err.message : err)),
262 )
263}
264// Resolves the to-do ids of the roster it loaded, or undefined when it loaded
265// none: no file named, no file, or a file that failed its check. The file is
266// read only where the path rule allows it, so the pane follows no link either.
267async function loadRoster($: EngineInterface): Promise<string[] | undefined> {
268 const at = await where($)
269 if ('error' in at) {
270 await update($, rosterError, () => at.error)
271 await update($, roster, () => ({ cards: [], todos: [] }))
272 return undefined
273 }
274 // After a clear or a resume the session id changes, and so does the file:
275 // keep the new one and the one before it. Nothing draws them since #339.
276 await update($, files, f =>
277 f.current === at.file ? f : { current: at.file, previous: f.current },
278 )
279 try {
280 const placed = await placeRoster(at.config, at.plugin, at.id, (path: string) => statPath($, path))
281 if ('refused' in placed) {
282 throw new Error(placed.refused.startsWith('link:') ? `${placed.refused}; the roster path must not pass through a link or junction` : placed.refused)
283 }
284 if (placed.existing === undefined) {
285 await update($, roster, () => ({ cards: [], todos: [] }))
286 await update($, rosterError, () => '')
287 return undefined
288 }
289 if (placed.existing.size > MAX_ROSTER_BYTES) throw new Error(`the roster is over ${MAX_ROSTER_BYTES} bytes`)
290 const checked = checkRoster(String(await $.fs.read(placed.file)))
291 if ('error' in checked) throw new Error(checked.error)
292 const value: Roster = checked.value
293 await update($, roster, () => value)
294 await update($, rosterError, () => '')
295 return value.todos.map(t => t.id)
296 } catch (err) {
297 await update($, rosterError, () => `Roster not shown: ${oneLine(String(err instanceof Error ? err.message : err), 200)}`)
298 return undefined
299 }
300}
301
302// After each roster load: move the ticks past their grace period to done, and
303// drop a tick whose to-do left the roster. The rules are in view.ts; a load
304// that read no roster changes no tick.
305async function sweepTodos($: EngineInterface, todoIds: string[] | undefined) {
306 try {
307 await settleTicks(
308 fn => update($, ticking, fn),
309 fn => update($, doneTodos, fn),
310 await $.clock.now(),
311 todoIds,
312 )
313 } catch {
314 // The next roster tick sweeps again.
315 }
316}
317
318// What the warmth reads remember of each transcript, keyed by its path. A
319// reload starts it over, which costs one read per member.
320const memory: ReadMemory = new Map()
321// What the transcript finder remembers between polls: its last listing of
322// the projects folder, its searches and this poll's found transcripts. It
323// holds paths and listed names, so it stays here and never enters plugin
324// state. A reload starts it over, which costs one listing.
325const finder: Finder = newFinder()
326// What the summary reads keep between polls, by session id: each member's
327// last summary that passed its checks, and the file that last failed one. A
328// reload starts it over, which costs a refused file one more poll.
329const summaries: SummaryMemory = newSummaryMemory()
330// By member name, the transcript path its Remote Control link was last read
331// from, so the link is read again when the found path changes.
332const linkFrom = new Map<string, string>()
333let polling = false
334
335async function pollLive($: EngineInterface, open: () => boolean) {
336 // One poll at a time: the transcript reads can take a while, so a tick
337 // that finds the last poll still running does nothing.
338 if (polling) return
339 polling = true
340 try {
341 // With no roster file to read there is no brigade to show, so nothing is
342 // read either; the pane already shows why.
343 const at = await where($)
344 if ('error' in at) return
345 // The stat resolves, so the place checks and the summary's path rule get
346 // a real path. An engine with no listing makes the transcript finder's
347 // listing reject, quietly, and the session-file read draw the fixed line.
348 const io = {
349 live: open,
350 now: () => $.clock.now(),
351 stat: (path: string) => $.fs.stat(path, { resolve: true }),
352 list: async (path: string) => $.fs.list(path),
353 read: async (path: string) => String(await $.fs.read(path)),
354 }
355 // The live state, from the engine's session files every poll. The pane
356 // runs no `claude agents --json`, which makes every running session do
357 // work at once (#347). A file that fails its check draws no row, and it,
358 // or a folder that cannot be read, draws the one fixed line.
359 const files = await readSessions(at.config, io)
360 if (!open()) return
361 const rows = files?.rows ?? []
362 // Each roster card finds its session by id (a title only when it has no
363 // id, or when no session file carries a Desktop id), and only the cards'
364 // entries are kept: the live word, the session's own name and the group
365 // the card moves to. No id is stored. A card two sessions share keeps an
366 // entry per session and no move.
367 const cards = (await read($, roster)).cards
368 const now = await Promise.resolve($.clock.now()).catch(() => Number.NaN)
369 const matched = matchRows(cards, rows, now)
370 await update($, live, () =>
371 cards.flatMap(c => {
372 const own = matched.get(c.title) ?? []
373 const row = own[0]
374 if (row === undefined) return []
375 // One entry per card: a card two sessions share draws the first one's word, and no move.
376 const move = own.length === 1 ? rowMove(c.status, row) : undefined
377 return [{ name: c.title, value: liveWord(row), shown: oneLine(row.name, MAX_NAME), ...(move === undefined ? {} : { move }) }]
378 }),
379 )
380 await update($, liveError, () => (files?.complete === true ? '' : SESSIONS_UNREAD))
381 // With no session read at all, the cards keep the cache and meter values
382 // they had: no rows would only redraw every card as not found.
383 if (files === undefined) return
384 try {
385 // Transcripts are found under the config folder.
386 const config = at.config
387
388 // Each roster member's cache warmth and meters: from its summary file
389 // in this plugin's data folder when one passes its checks, else from
390 // its transcript's call series, found by the transcript finder. The
391 // rules for what is found and read, and when, are in view.ts.
392 // The matched rows are handed over under their card's title.
393 const retitled = cards.flatMap(c => (matched.get(c.title) ?? []).map(row => ({ ...row, name: c.title })))
394 const found = await readCalls(retitled, cards.map(c => c.title), config, memory, io, finder, { plugin: at.plugin, held: summaries })
395 if (found === undefined || !open()) return
396 await update($, warmth, () => found.warmth)
397 await update($, meters, () => found.meters)
398 await update($, refusals, () => found.refusals)
399
400 // A Remote Control session's claude.ai link sits in its transcript, in a
401 // row the engine writes. Read only a roster member's, through the
402 // finder's result for this poll, which passed the place check: again
403 // whenever the found path changes, the misses kept too, and nothing
404 // over the read cap: a transcript past 4 MiB keeps the link read while
405 // it was smaller, a reload and a moved path included (#308). A link
406 // from a path the finder dropped, or from one it moved off at 4 MiB or
407 // less, goes, and so does a stored link when nothing is found, even
408 // after a reload has emptied `linkFrom`. A name the finder did not look
409 // for, one with no row or one two rows share, is left as it was. The
410 // read comes first and is kept only if the pane is still open, so a
411 // close during it records nothing and the next poll tries again.
412 const members = new Set(cards.filter(c => c.desktopId === undefined && c.url === undefined).map(c => c.title))
413 const stored = new Set((await read($, links)).map(p => p.name))
414 for (const [name, at] of finder.byName) {
415 const step = linkStep(at?.path, linkFrom.get(name), stored.has(name), at?.size)
416 if (!members.has(name) || step === 'skip') continue
417 if (step === 'keep' && at !== undefined) {
418 linkFrom.set(name, at.path)
419 continue
420 }
421 if (!open()) return
422 // No transcript, one too large, or none for this kind of session: no link.
423 const url =
424 at === undefined || step === 'drop' || !(at.size <= MAX_TRANSCRIPT_BYTES)
425 ? undefined
426 : await $.fs.read(at.path).then(t => remoteLink(String(t)), () => undefined)
427 if (!open()) return
428 if (at === undefined) linkFrom.delete(name)
429 else linkFrom.set(name, at.path)
430 await update($, links, list => [...list.filter(p => p.name !== name), ...(url === undefined ? [] : [{ name, value: url }])])
431 }
432 // A link whose card left the roster goes with it, and so does the path
433 // it was read from: a card that returns reads its link again (#281).
434 if (!open()) return
435 const titles = cards.map(c => c.title)
436 for (const name of [...linkFrom.keys()]) if (!titles.includes(name)) linkFrom.delete(name)
437 await update($, links, list => linksOnRoster(list, titles))
438 } catch {
439 // The reads are tried again at the next poll.
440 }
441 } finally {
442 polling = false
443 }
444}
445
446// The groups the last poll moved cards to, by card title, read through the
447// checked live entries.
448async function movesOf($: EngineInterface): Promise<Moves> {
449 return movesFrom(liveFrom(await read($, live)))
450}
451
452// --- the PR details --------------------------------------------------------
453//
454// While the pane is open and a shown card carries a PR number, the pane runs one
455// fixed `gh pr list` a minute. The argument list is a constant: no roster text,
456// number or title reaches the command. The answers, and the numbers known to be
457// merged, stay in the module for the session and never enter plugin state;
458// a reload starts them over. `gh`'s error text is never read, shown or stored.
459
460// By PR number, the last good answers.
461let ghAnswers: ReadonlyMap<number, GhPr> = new Map()
462// The numbers `gh` said are merged. The call stops once every shown PR is in here.
463const ghMerged = new Set<number>()
464// Whether the last call failed: the Pull requests view says so in fixed words.
465let ghDown = false
466// The owner/name the first good answer named. `gh` answers for the repository the
467// environment and the working folder's git config choose, which a member session
468// can change; an answer naming another repository counts as no answer.
469let ghRepo: string | undefined
470// When the last call started, on the engine clock.
471let ghAt: number | undefined
472let asking = false
473
474// The numbers of the PRs the shown cards carry, as numbers.
475const shownPrs = (cards: readonly Card[], hidden: ReadonlySet<unknown>, moves: Moves): number[] => {
476 const g = groupCards(cards, hidden, moves)
477 return [...g.needsYou, ...g.working, ...g.finished].flatMap(({ c }) => {
478 const n = prNumber(c)
479 return n === undefined ? [] : [Number(n)]
480 })
481}
482
483// On macOS and Linux `gh` is found by name on the inherited PATH, so a PATH with
484// an empty or relative entry could let a file in the project folder run in its
485// place, with the session's environment. Such a host runs nothing then. Windows
486// is measured: the engine runs the real `gh` there (threat model, row 15).
487//
488// The host is worked out on each call, here and at Open in app, or is none.
489// The engine gives a mod no platform field. Windows is known first, by its
490// environment; then each probe in turn, as `probeHost` judges it. A read that
491// fails means no host, never unset. Each name is spelled at its call, so
492// `claude plugin validate` lists what the pane reads, and the reads stay in
493// these two callers because the directory's checker refuses `$` passed to a
494// helper that reads the host.
495async function ghFindable($: EngineInterface): Promise<boolean> {
496 try {
497 if (windowsEnv('OS', await $.env.get('OS')) || windowsEnv('SystemRoot', await $.env.get('SystemRoot')) || windowsEnv('windir', await $.env.get('windir'))) return true
498 let os: HostOs | 'next' | undefined = 'next'
499 for (const [probe, file] of HOST_PROBES) {
500 os = probeHost(probe, await statPath($, file))
501 if (os !== 'next') break
502 }
503 if (os === 'next' || os === undefined) return false
504 const path = await $.env.get('PATH')
505 return typeof path === 'string' && path !== '' && path.split(':').every(entry => entry.startsWith('/'))
506 } catch {
507 return false
508 }
509}
510
511// `tick` is the timer's own call, which always runs; the call at arm waits out
512// a minute since the last one, so a quick reopen asks once.
513async function askGh($: EngineInterface, open: () => boolean, tick: boolean) {
514 if (asking) return
515 asking = true
516 try {
517 const [{ cards }, hid, moves] = await Promise.all([read($, roster), read($, dismissed), movesOf($)])
518 const wanted = shownPrs(cards, new Set(hid), moves)
519 if (wanted.length === 0 || wanted.every(n => ghMerged.has(n))) return
520 const now = await $.clock.now()
521 if (!tick && ghAt !== undefined && now - ghAt < GH_MS) return
522 ghAt = now
523 if (!(await ghFindable($))) {
524 if (open()) ghDown = true
525 return
526 }
527 let found: ReadonlyMap<number, GhPr> | undefined
528 try {
529 const ran = await $.process.run([...GH_ARGV], { timeoutMs: 15000 })
530 if (!open()) return
531 if (ran.exitCode === 0 && ran.isStdoutTruncated === false && typeof ran.stdout === 'string') {
532 const parsed = parsePrList(ran.stdout)
533 if ('value' in parsed) found = parsed.value
534 }
535 } catch {
536 // A failure to start counts as no answer.
537 }
538 if (!open()) return
539 if (found === undefined) {
540 ghDown = true
541 return
542 }
543 // The first good answer pins the repository; another one is no answer.
544 const answered = [...found.values()]
545 if (ghRepo === undefined) ghRepo = answered[0]?.repo
546 if (ghRepo !== undefined && answered.some(a => a.repo !== ghRepo)) {
547 ghDown = true
548 return
549 }
550 // A merged PR is kept even when a later answer no longer lists it.
551 const next = new Map<number, GhPr>()
552 for (const [n, a] of ghAnswers) if (ghMerged.has(n)) next.set(n, a)
553 for (const [n, a] of found) {
554 next.set(n, a)
555 if (a.state === 'merged') ghMerged.add(n)
556 }
557 ghAnswers = next
558 // A call that answered for none of the shown numbers (another host, say) says so too.
559 ghDown = wanted.every(n => !next.has(n))
560 } finally {
561 asking = false
562 }
563}
564
565// This session's own usage, for the section at the bottom of the pane. The
566// plain reading costs nothing. The context breakdown is asked for only when
567// the session draws somewhere other than the terminal, the one place the
568// image shows its rows, and only as the local summary estimate, which sends
569// no request. Only the fields the section draws are stored. Each reading also
570// samples the session limit for its projection, by view.ts's rules. A failed
571// reading keeps the last one, and a reading that started before the pane
572// closed is dropped, so it cannot land over a fresh one after a reopen.
573// The seated head-chef check reads the same local summary for its skill list.
574const LOCAL_BREAKDOWN = { breakdown: 'summary' } as const
575async function readUsage($: EngineInterface) {
576 const mine = generation
577 try {
578 const surfaces = await $.session.surfaces()
579 const image = surfaces.some(s => s !== 'terminal')
580 const reading = await $.session.usage(image ? LOCAL_BREAKDOWN : undefined)
581 if (generation !== mine) return
582 const snapshot = snapshotFrom(reading)
583 await update($, usage, () => snapshot)
584 const now = await $.clock.now()
585 if (generation === mine) await update($, samples, list => addSample(list, snapshot, now))
586 } catch {
587 // No reading this time: the section keeps what it showed.
588 }
589}
590
591// The measure hook's reads, one at a time. A measurement that comes while one
592// runs asks for one more after it, so a burst folds into one trailing read,
593// an older reading never lands after a newer one, and a reading that hung
594// holds at most one waiting behind it. A close ends the run.
595let measuring = -1
596let again = false
597async function measureUsage($: EngineInterface) {
598 const mine = generation
599 if (measuring === mine) {
600 again = true
601 return
602 }
603 measuring = mine
604 try {
605 do {
606 again = false
607 await readUsage($)
608 } while (again && generation === mine)
609 } finally {
610 if (measuring === mine) measuring = -1
611 }
612}
613
614// Start the reads, once: a second /brigade while they run starts nothing.
615// The timers are taken before the first await, so two arms that overlap
616// cannot both pass the check. Each arm carries its generation, and a close
617// moves the generation on, so neither its first reads nor a tick already
618// queued run after the pane closed. STARTS_FOLDED says which groups start folded at each arm.
619let generation = 0
620async function arm($: EngineInterface) {
621 if (timers.length === 0) {
622 const mine = ++generation
623 const live = () => generation === mine
624 timers = [
625 $.clock.every(ROSTER_MS, () => void (live() && rosterTick($, live))),
626 $.clock.every(LIVE_MS, () => void (live() && pollLive($, live))),
627 $.clock.every(GH_MS, () => void (live() && askGh($, live, true))),
628 ]
629 await update($, armed, () => true)
630 await update($, folded, () => STARTS_FOLDED)
631 if (live()) await readUsage($)
632 if (live()) await loadRoster($)
633 if (live()) await pollLive($, live)
634 // Not awaited: a slow gh must not hold up the /brigade reply, the skill's text or the tool's offer.
635 if (live()) void askGh($, live, false)
636 return
637 }
638 await update($, armed, () => true)
639 await update($, folded, () => STARTS_FOLDED)
640}
641function disarm() {
642 generation++
643 for (const t of timers) t.cancel()
644 timers = []
645}
646
647// The roster timer's tick. The engine drops a pane whose drawing threw
648// without telling its close hook, so each tick first checks that the pane is
649// still listed, and stops every read when it is not: the timers, the measure
650// hook's reads and the report keeping all end with it.
651async function rosterTick($: EngineInterface, live: () => boolean) {
652 try {
653 const panes = await $.ui.panes()
654 const listed = panes.some(p => p.id === PANE)
655 // A close or a fresh arm while the answer was on its way: act on nothing.
656 if (!live()) return
657 if (!listed) {
658 disarm()
659 await update($, armed, () => false)
660 return
661 }
662 } catch {
663 // No answer this time: the next tick asks again.
664 return
665 }
666 const ids = await loadRoster($)
667 if (live()) await sweepTodos($, ids)
668}
669
670// The Desktop ids whose press is in its tool route now. A second press for
671// one of them is ignored until the route ends, so a press inside the wait
672// sends no second call and cannot run the link route twice. The card's button
673// and its to-do's share the mark, since both name the same id.
674const opening = new Set<string>()
675
676// Open in app, first through the Desktop app's own tool, which shows a session
677// this lead started in a split beside it. The tool is called only where the
678// Desktop app draws the session, when the engine lists the tool by its exact
679// name and the owner's rules allow it, and its
680// answer is read as untrusted. No permission prompt sees this call, so those
681// checks stand in for one. Any refusal, rejection, throw or a wait past 5 s
682// on the engine's clock, from the tool list to the answer, ends the route, and
683// the press goes on to the link. Resolves true when the app said it opened
684// the session.
685async function viaTool($: EngineInterface, session: string): Promise<boolean> {
686 let over = false
687 let timer: Timer | undefined
688 const waited = new Promise<false>(res => {
689 timer = $.clock.after(OPEN_WAIT_MS, () => {
690 over = true
691 res(false)
692 })
693 })
694 const route = askTool($, session, () => over)
695 // A route that ends or fails after the wait is dropped here, unread.
696 route.catch(() => undefined)
697 try {
698 return await Promise.race([route, waited])
699 } finally {
700 timer?.cancel()
701 }
702}
703
704// The tool route itself. After the wait is over it makes no call and shows
705// nothing; a call already made may still show the split after the link route
706// ran.
707async function askTool($: EngineInterface, session: string, over: () => boolean): Promise<boolean> {
708 // Only where the Desktop app draws this session: elsewhere its server is
709 // absent, and a server of the same name would be the only one to answer.
710 const surfaces = await $.session.surfaces()
711 if (!surfaces.includes('desktop')) return false
712 if (!listsOpenTool(await $.tool.list())) return false
713 const args = { session_id: session, target: OPEN_TARGET }
714 if (!rulesAllowTool(await $.tool.check({ tool: OPEN_TOOL, input: args }))) return false
715 if (over()) return false
716 const outcome = readOpenAnswer(await $.mcp.call(OPEN_SERVER, OPEN_NAME, args))
717 if (over()) return false
718 if (outcome.opened) {
719 $.ui.toast(outcome.toast)
720 return true
721 }
722 if (outcome.reason !== undefined) $.ui.toast(outcome.reason)
723 return false
724}
725
726// The links with a link-route press in progress, from host detection through
727// the opener's run. Any press on one of them, a Desktop card's included, does
728// nothing until that press ends, whether its run succeeds or fails, as
729// `opening` does for the tool route.
730const linking = new Set<string>()
731
732// The pane's Link takes https only, so the app link goes to the host's own
733// handler for claude://, through the host's opener: explorer.exe on Windows,
734// /usr/bin/open on macOS, /usr/bin/xdg-open on Linux, and none on a host the
735// pane cannot prove. Only a link of the two known shapes goes, built from a
736// checked id, as one argument with no shell, one press per link at a time,
737// for at most 15 s. A card with a Desktop id tries the app's own tool first,
738// one press at a time.
739async function openInApp($: EngineInterface, c: Card) {
740 const app = appLink(c, lookup(await read($, links)).get(c.title))
741 if (app === undefined || linking.has(app)) return
742 const session = toolSession(c)
743 if (session !== undefined) {
744 if (opening.has(session)) return
745 opening.add(session)
746 try {
747 if (await viaTool($, session).catch(() => false)) return
748 } finally {
749 opening.delete(session)
750 }
751 }
752 if (linking.has(app)) return
753 linking.add(app)
754 try {
755 let os: HostOs | 'next' | undefined = 'next'
756 try {
757 if (windowsEnv('OS', await $.env.get('OS')) || windowsEnv('SystemRoot', await $.env.get('SystemRoot')) || windowsEnv('windir', await $.env.get('windir'))) os = 'windows'
758 else for (const [probe, file] of HOST_PROBES) {
759 os = probeHost(probe, await statPath($, file))
760 if (os !== 'next') break
761 }
762 } catch {
763 os = undefined
764 }
765 if (os === 'next' || os === undefined) {
766 $.ui.toast('Open in app has no opener on this system.')
767 return
768 }
769 const argv = openerArgv(os, app)
770 const ran = await $.process.run(argv, { timeoutMs: 15000 }).catch(() => undefined)
771 // The rejection's own text is never shown: name the program instead.
772 if (ran === undefined) {
773 $.ui.toast(`Could not open ${oneLine(c.title, 40)} with ${argv[0]}.`)
774 return
775 }
776 // explorer.exe exits 1 even when it hands the link on, so on every host the
777 // toast reports the exit code rather than judging it.
778 $.ui.toast(`Opening ${oneLine(c.title, 40)} in the app (${ran.exitCode})`)
779 } finally {
780 linking.delete(app)
781 }
782}
783
784// --- set_roster ---------------------------------------------------------------
785//
786// The tool the head chef keeps the roster with. A file write of its own into
787// the plugin's data folder asks the owner every time, in every mode, because
788// Claude Code protects that folder; this tool writes the same file with no
789// prompt. So it is guarded here instead: it is offered only once the owner
790// opens the pane, writes only while the engine lists the pane open, refuses a
791// subagent's call, a deny verdict and an owner's ask rule, takes only a roster
792// that passes the shared check and cap, writes only the one file the path rule
793// in roster.ts allows, and never names a path from its input.
794
795const TOOL_NAME = 'mcp__grimoire__set_roster'
796
797const DESCRIPTION =
798 "Keeps the Brigade pane's roster for this lead session. Pass the whole roster every time, every card and every to-do; it replaces the last one. Both lists are required; two empty lists are an empty roster. A card may carry its session's pull request: `pr` (its number as text, 1 to 7 digits) and `prState` (`open`, `merged` or `closed`, the last state known). Send no `since`: the pane stamps how long each card has been in its status and phase from its own clock. It works only while the Brigade pane is open, which the owner opens with /brigade or a load of the head-chef skill opens, and refuses otherwise. A refusal names the rule that failed."
799
800const field = (max: number) => ({ type: 'string', maxLength: max })
801const SCHEMA = {
802 type: 'object',
803 additionalProperties: false,
804 required: ['cards', 'todos'],
805 properties: {
806 cards: {
807 type: 'array',
808 maxItems: 50,
809 items: {
810 type: 'object',
811 additionalProperties: false,
812 required: ['title', 'status'],
813 properties: {
814 title: field(80),
815 work: field(MAX_TEXT),
816 phase: field(MAX_TEXT),
817 settings: field(MAX_TEXT),
818 status: { type: 'string', enum: [...STATUSES] },
819 desktopId: field(100),
820 bgId: field(100),
821 url: field(100),
822 pr: { type: 'string', pattern: PR_NUMBER.source },
823 prState: { type: 'string', enum: [...PR_STATES] },
824 },
825 },
826 },
827 todos: {
828 type: 'array',
829 maxItems: 50,
830 items: {
831 type: 'object',
832 additionalProperties: false,
833 required: ['id', 'text'],
834 properties: { id: field(40), text: field(MAX_TEXT), session: field(80) },
835 },
836 },
837 },
838}
839
840// The engine's own fields on a tool call. Everything else is the model's
841// input and goes to the shared check whole, so an unknown key is refused.
842const ENVELOPE = ['tool', 'tool_use_id', 'agentId', 'consent']
843
844const refuse = (rule: string) => ({ deny: `set_roster refused: ${rule}. The roster file is unchanged.` })
845// Once the write has started, a failure cannot say the file is unchanged.
846const failedAfterWrite = (why: string) => ({
847 deny: `set_roster failed after the write began: ${why}. The roster may or may not have been kept; stop keeping the roster and tell the owner.`,
848})
849
850async function paneOpen($: EngineInterface): Promise<boolean> {
851 return (await paneListed($)) !== undefined
852}
853
854async function paneListed($: EngineInterface) {
855 const panes = await $.ui.panes()
856 return panes.find(p => p.id === PANE)
857}
858
859async function offerTool($: EngineInterface) {
860 await $.tool.register({ name: TOOL, description: DESCRIPTION, inputSchema: SCHEMA })
861}
862
863// Set when a head-chef load leaves the pane waiting (#380), and read by the
864// turn.start hook: 'offer' when the pane is open but not shown, or open
865// without its reads, so the next turn that finds it shown starts the reads,
866// offers the tool and says so in a note; 'arm' when the tool is offered
867// already and only the reads wait for the engine to list the pane, so that
868// turn starts them and says in a note that the tool now works.
869let lateOffer: false | 'offer' | 'arm' = false
870
871// Opens the pane for /brigade and for a head-chef load. Each open starts on
872// Sessions, with the dismissed cards back and nothing selected, and reports
873// count from the open. The open comes first, and the reads start only once
874// the engine lists the pane: a pane another plugin refuses or answers for
875// starts none. The tool is offered once the pane is listed, or, with
876// `needPlaced`, once it is placed; it refuses every call while the pane is not
877// listed. `wait` says whether to wait for the first reads: /brigade does, and
878// a head-chef load does not, so the skill's text is never held up by a slow
879// read. `reached.open` is set once the engine has answered the open, for a
880// caller whose later step throws. `needPlaced` is for a head-chef load: a pane
881// the engine answers is not placed starts no reads and offers no tool, so
882// nothing runs while it waits unseen. `listed` says whether the engine listed
883// it.
884type Offer = 'offered' | 'not listed' | 'not placed' | { why: string }
885async function openPane($: EngineInterface, wait: boolean, reached: { open: boolean } = { open: false }, needPlaced = false) {
886 await update($, viewAtom, () => 'sessions')
887 await update($, dismissed, () => [])
888 await update($, picked, () => [])
889 await update($, reports, () => [])
890 const opened = await $.ui.open({ id: PANE, title: TITLE })
891 reached.open = true
892 let offer: Offer = 'not listed'
893 if (needPlaced && !opened.isPlaced) return { opened, offer: 'not placed' as const, listed: false }
894 const listed = await paneOpen($)
895 if (listed || needPlaced) {
896 // Not awaited when the caller does not wait: arm takes its timers before
897 // its first await, so a second arm still starts nothing.
898 if (!listed) lateOffer = 'arm'
899 else if (wait) await arm($)
900 else arm($).catch(() => undefined)
901 try {
902 await offerTool($)
903 offer = 'offered'
904 } catch (err) {
905 offer = { why: oneLine(String(err instanceof Error ? err.message : err), 200) }
906 }
907 }
908 return { opened, offer, listed }
909}
910
911// The fixed lines a head-chef load may append to the skill's text, or store
912// as a note. Fixed text: nothing from the event, the roster or an error
913// reaches the model's prompt through them.
914const READY_LINE = `The Brigade pane is open. \`${TOOL}\` is ready: call it with the full roster on your next turn.`
915const READY_UNLISTED_LINE = `The Brigade pane is opening but not ready yet, so a \`${TOOL}\` call is refused for now. Wait for a Brigade note saying it is ready, then call it with the full roster.`
916// Shown when the engine opens the pane but does not place it: no reads start
917// and no tool is offered, and /brigade shows the pane and starts them.
918const NOT_SHOWN_TOAST = 'The Brigade pane opened but is not shown, so its reads did not start. Type /brigade to show it.'
919const NOT_OFFERED_LINE = `The Brigade pane is open, but \`${TOOL}\` could not be offered; keep no roster.`
920const ALREADY_OPEN_LINE = `The Brigade pane was already open. \`${TOOL}\` is ready: call it with the full roster on your next turn.`
921const NOT_SHOWN_LINE = `The Brigade pane is open but not shown, so \`${TOOL}\` is not ready yet. It is offered once the pane is shown; if it does not come, ask the owner to type /brigade.`
922const NO_READS_LINE = `The Brigade pane opened without its reads, so \`${TOOL}\` is not ready. Ask the owner to type /brigade.`
923const NO_READS_TOAST = 'The Brigade pane opened without its reads. Type /brigade to start them.'
924
925const LATE_NOTE = `The Brigade pane is now shown. \`${TOOL}\` is ready: call it with the full roster.`
926
927// One fixed row for the model, where no skill text can carry a line. It is
928// stored as a user row, so each starts by saying it is the plugin's.
929const NOTE_FROM = 'Brigade (plugin note): '
930async function note($: EngineInterface, text: string) {
931 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: `${NOTE_FROM}${text}` }] } })
932}
933
934// The late look, at a turn of the lead's own while the flag is set: one look
935// at the pane. Listed and shown: the reads start, on 'offer' the tool is
936// offered, and one note says it is ready. Gone: the flag clears. Still
937// waiting: the next turn looks again.
938async function lateTurn($: EngineInterface) {
939 const pane = await paneListed($)
940 if (pane === undefined) {
941 lateOffer = false
942 return
943 }
944 if (!pane.isPlaced) return
945 if (timers.length === 0) arm($).catch(() => undefined)
946 // The flag clears only once the tool is offered: a failed offer is tried
947 // again at the next turn.
948 if (lateOffer === 'offer') await offerTool($)
949 lateOffer = false
950 await note($, LATE_NOTE)
951}
952
953// What a head-chef load does, as one fixed line for the model: the pane opened
954// or found open, and whether the tool is ready. Undefined when a throw came
955// before the open, which opened nothing and has nothing to say.
956async function headChefLoad($: EngineInterface): Promise<string | undefined> {
957 const reached = { open: false }
958 try {
959 const pane = await paneListed($)
960 if (pane !== undefined) {
961 if (!pane.isPlaced) {
962 lateOffer = 'offer'
963 return NOT_SHOWN_LINE
964 }
965 // Found open: nothing is reset, the reads start only if they are not
966 // running, and the tool is offered again, which replaces it.
967 if (timers.length === 0) arm($).catch(() => undefined)
968 try {
969 await offerTool($)
970 } catch {
971 return NOT_OFFERED_LINE
972 }
973 lateOffer = false
974 return ALREADY_OPEN_LINE
975 }
976 const { offer, listed } = await openPane($, false, reached, true)
977 if (offer === 'not placed') {
978 lateOffer = 'offer'
979 $.ui.toast(NOT_SHOWN_TOAST)
980 return NOT_SHOWN_LINE
981 }
982 if (offer !== 'offered') return NOT_OFFERED_LINE
983 if (listed) lateOffer = false
984 return listed ? READY_LINE : READY_UNLISTED_LINE
985 } catch {
986 if (!reached.open) return undefined
987 lateOffer = 'offer'
988 $.ui.toast(NO_READS_TOAST)
989 return NO_READS_LINE
990 }
991}
992
993// Whether a skill load is the head-chef skill from the plugin's own copy or the
994// owner's own skills folder (any user-level skill of that name), read from the event alone. The engine's documents
995// do not say which spelling a plugin skill's name takes, so both are matched.
996const isOurHeadChef = (e: { skill: string; source: string; pluginName?: string }) =>
997 (e.skill === 'head-chef' || (e.skill === 'grimoire:head-chef' && e.source === 'plugin')) &&
998 ((e.source === 'plugin' && e.pluginName === 'grimoire') || e.source === 'userSettings')
999
1000// --- where the security default is seated (#380) ----------------------------
1001//
1002// The security default is a plugin Claude Code bundles; where it is seated
1003// (managed settings, or a Team or Enterprise account) a user plugin's
1004// skill.prompt hook never runs, so a head-chef load is seen through the Skill
1005// call or the typed command around it. "Core" is Claude Code's own handler,
1006// beneath every plugin hook: its answer to a typed command carries a `ref`.
1007// Each wrapper sets `loadPending` (the mark) and runs the load; the skill
1008// hook, where it runs, clears it for any load of a head-chef name, ours or
1009// not, and handles the load itself. A mark still set after a load that ran
1010// means the hook was skipped. Then, as the owner settled on #380 (q6), only a
1011// typed load core answered opens the pane, and only when the session's local
1012// skill listing shows the loaded copy is ours; a model's load stores one note
1013// asking for /brigade. The note follows the load's own answer.
1014const isHeadChefName = (name: unknown) => name === 'head-chef' || name === 'grimoire:head-chef'
1015let loadPending = false
1016
1017const CONFIRM_FAILED_NOTE = `Brigade did not open its pane for this head-chef load: it could not confirm which copy of the skill loaded, so \`${TOOL}\` is not ready. Ask the owner to type /brigade.`
1018const OPEN_FAILED_NOTE = `Brigade could not open its pane for this head-chef load, so \`${TOOL}\` is not ready. Ask the owner to type /brigade.`
1019const MODEL_LOAD_NOTE = `The Brigade pane was not opened, so \`${TOOL}\` is not ready: in this session a head-chef load the owner did not type opens no pane. Ask the owner to type /brigade.`
1020
1021async function seatedLoad($: EngineInterface, name: string) {
1022 let ours = false
1023 try {
1024 const reading = await $.session.usage(LOCAL_BREAKDOWN)
1025 ours = listedAsOurs(reading.context?.breakdown?.skills, name)
1026 } catch {
1027 // An unread listing confirms nothing.
1028 }
1029 const line = ours ? await headChefLoad($) : CONFIRM_FAILED_NOTE
1030 await note($, line ?? OPEN_FAILED_NOTE)
1031}
1032
1033// Runs a head-chef load with `loadPending` set, and returns its own answer. Only a
1034// load that ran, with the mark still set, starts `seated`, unawaited.
1035async function wrapLoad<T>(load: () => Promise<T>, ran: (answer: T) => boolean, seated: () => Promise<void>): Promise<T> {
1036 loadPending = true
1037 let answer: T
1038 try {
1039 answer = await load()
1040 } catch (err) {
1041 loadPending = false
1042 throw err
1043 }
1044 const skipped = loadPending
1045 loadPending = false
1046 if (skipped && ran(answer)) void seated().catch(() => undefined)
1047 return answer
1048}
1049
1050// Writes run one after another, so two calls in one turn cannot interleave
1051// their checks and writes. A call whose dispatch was abandoned while it
1052// waited, because it ran out of time or the owner interrupted it, writes
1053// nothing when its turn comes. A write that never returns holds the queue
1054// until the module reloads; row 15 names it.
1055let writing: Promise<unknown> = Promise.resolve()
1056function oneAtATime<T>(work: () => Promise<T>): Promise<T> {
1057 const run = writing.then(work, work)
1058 writing = run.catch(() => undefined)
1059 return run
1060}
1061
1062// What a call has done so far, so a failure says the right thing about the file.
1063type Progress = { written: boolean }
1064
1065async function setRoster($: EngineInterface, e: Record<string, unknown>, signal: AbortSignal, progress: Progress) {
1066 if (e.agentId !== undefined) return refuse("subagent: only the lead session's own turns keep the roster")
1067 if (!(await paneOpen($))) return refuse('pane closed; roster not kept')
1068
1069 // Own entries copied into a fresh object, so no key reaches a prototype.
1070 const input = Object.fromEntries(Object.entries(e).filter(([k]) => !ENVELOPE.includes(k)))
1071
1072 const verdict = await $.tool.check({ tool: TOOL_NAME, input })
1073 if (verdict.decision === 'deny') return refuse(`deny verdict: ${oneLine(verdict.reason ?? 'a rule denies this tool', 200)}`)
1074 if (verdict.decision === 'ask' && verdict.rule !== undefined) {
1075 return refuse(`ask rule: the owner's rule ${oneLine(verdict.rule, 120)} covers this tool`)
1076 }
1077 // An organisation's ceiling below allow: the tool may never run unasked.
1078 if (verdict.ceiling !== undefined && verdict.ceiling !== 'allow') return refuse(`organisation ceiling: ${verdict.ceiling}`)
1079
1080 for (const k of ['cards', 'todos']) {
1081 if (!Object.hasOwn(input, k)) return refuse(`malformed input: "${k}" is missing; pass both lists, empty if need be`)
1082 }
1083 const checked = checkRoster(JSON.stringify(input), true, 'tool')
1084 if ('error' in checked) return refuse(`shape: ${checked.error}`)
1085 const at = await where($)
1086 if ('error' in at) return refuse(`path: ${at.error}`)
1087
1088 return oneAtATime(async () => {
1089 if (signal.aborted) return refuse('abandoned: the call ran out of time or was interrupted before its turn')
1090 if (!(await paneOpen($))) return refuse('pane closed; roster not kept')
1091 const placed = await placeRoster(at.config, at.plugin, at.id, (path: string) => statPath($, path))
1092 if ('refused' in placed) return refuse(placed.refused)
1093 // A file already there is overwritten only if it is a roster, both lists
1094 // and all. What it holds otherwise is never echoed. Its cards are the
1095 // ages' source.
1096 let previous: Roster | undefined
1097 if (placed.existing !== undefined) {
1098 const was = placed.existing.size <= MAX_ROSTER_BYTES ? checkRoster(String(await $.fs.read(placed.file)), true) : undefined
1099 if (was === undefined || 'error' in was) {
1100 return refuse(`not a roster: ${placed.file} holds something other than a roster, so it is not overwritten. Ask the owner to delete that file`)
1101 }
1102 previous = was.value
1103 }
1104 // The ages: stamped here, in the queue, from the file just read and the
1105 // engine clock, so two calls in one turn stamp in order. The model sent no
1106 // time; the tool's check refused one.
1107 const stamped = stampSince(previous, checked.value.cards, await $.clock.now())
1108 if ('error' in stamped) return refuse(stamped.error)
1109 const value: Roster = { cards: stamped.value, todos: checked.value.todos }
1110 const text = serialize(value)
1111 if ('error' in text) return refuse(`size: ${text.error}`)
1112 const again = checkRoster(text.value, true, 'file')
1113 if ('error' in again) return refuse(`shape: ${again.error}`)
1114 if (signal.aborted) return refuse('abandoned: the call ran out of time or was interrupted before its write')
1115 progress.written = true
1116 await $.fs.write(placed.file, text.value)
1117 // A link swapped in between the check and the write, at the file or at
1118 // any folder above it, is caught here by the same path rule, after the
1119 // fact, and said loudly. A hard link is not.
1120 const after = await placeRoster(at.config, at.plugin, at.id, (path: string) => statPath($, path)).catch(err => ({
1121 refused: `the check failed (${oneLine(String(err instanceof Error ? err.message : err), 200)})`,
1122 }))
1123 const why = 'refused' in after ? after.refused : after.existing === undefined ? 'the file is not there' : undefined
1124 if (why !== undefined) {
1125 const warning = `Brigade: after the roster write, the roster path failed its check: ${why}. Something changed it between the check and the write; check ${placed.file} and where it leads.`
1126 await update($, rosterError, () => warning)
1127 $.ui.toast(warning, { timeoutMs: 15000 })
1128 return failedAfterWrite(`the path then failed its check (${why}); the owner has been told`)
1129 }
1130 // Only now does the pane change: it redraws at once, and the 5 s poll
1131 // stays the reader for changes made elsewhere.
1132 await update($, roster, () => value)
1133 await update($, rosterError, () => '')
1134 return { result: `Roster kept: ${value.cards.length} card(s), ${value.todos.length} to-do(s).` }
1135 })
1136}
1137
1138// The owner's "Don't show again", read from the store at each start. The
1139// band in warning.tsx reads the same key.
1140const warningAck = atom({ plugin: 'grimoire', key: 'warningAck' } as const, null)
1141
1142async function offerWarning($: EngineInterface) {
1143 await $.tool.register({ name: WARNING_TOOL, description: WARNING_DESCRIPTION, inputSchema: WARNING_SCHEMA })
1144}
1145
1146/** At each session start: read the owner's "Don't show again" back from the
1147 * store, and offer the permission warning's tool. A failure leaves no tool,
1148 * and the skill then says the warning in chat. */
1149async function warningStart($: EngineInterface) {
1150 try {
1151 let kept: ReturnType<typeof ackFrom> = null
1152 try {
1153 kept = ackFrom(await $.store.get(WARNING_KEY))
1154 } catch {
1155 // An unreadable store is no acknowledgement.
1156 }
1157 await update($, warningAck, () => kept)
1158 await offerWarning($)
1159 } catch {
1160 // No warning tool this time.
1161 }
1162}
1163
1164/** At each classic.SessionStart, a startup, a clear or a resume: offer the
1165 * tool again, since a clear or a resume does not fire session.start, and
1166 * registering a name again replaces it. */
1167async function warningOfferAgain($: EngineInterface) {
1168 try {
1169 await offerWarning($)
1170 } catch {
1171 // As above.
1172 }
1173}
1174
1175export const register: Register = on => {
1176 // Every session's own usage summary, written from its steps and turn ends.
1177 registerWriter(on)
1178 // The head chef's permission warning, above the prompt in a lead session.
1179 registerWarning(on)
1180
1181 on('session.start', async ($, e, next) => {
1182 // The usage summary writer's clock and session: the engine's epoch and
1183 // this session's id, read once here and never awaited. Only numbers and
1184 // text cross into writer.ts.
1185 const perf = performance.now()
1186 $.clock.now().then(t => writerEpoch(t, perf), () => undefined)
1187 $.session.id().then(id => writerSession(id), () => undefined)
1188 await $.command.register({
1189 name: 'brigade',
1190 description: 'Show the Brigade pane: the sessions this lead session started',
1191 })
1192 // The permission warning's tool, offered in every session: the head chef
1193 // calls it before its first launch, with or without the pane.
1194 await warningStart($)
1195 // A reload of the module while the pane stays up finds it in the engine's
1196 // record. Only then do the reads start again, and the tool is offered
1197 // again; a fresh session has no pane and no tool.
1198 if (await paneOpen($)) {
1199 await arm($)
1200 await offerTool($)brigade/view.ts 2815 lines1import { AHEAD_MS, PR_NUMBER, PR_STATES, SESSION_ID, foldsCase, oneLine, pathKey, placeSummary, projectFolder, sepOf, sessionRow, statRejection } from './roster.ts'
2import type { GhPr, Move, SessionRow, StatAnswer } from './roster.ts'
3import type { Meter, Pair, Sample, UsageCategory, UsageLimit, UsageSnapshot, Warmth } from './types'
4
5// What the Brigade pane draws, worked out from plain values: the render hook
6// in register.tsx only turns these results into elements. Plain TypeScript
7// with erasable syntax only and no engine import, so `node --test` imports
8// this file as it is.
9//
10// The to-dos: a tick that can be undone for a grace period, then moves the
11// to-do to done.
12//
13// The cache warmth: each card's ◆ line, read from the last real model call in
14// its session's summary file or transcript, and which of them the live poll
15// reads.
16//
17// The call series and the context meter: what one read of a transcript gives
18// beyond the last call, stored as each card's meters record, and the meter
19// drawn from it under the cache bar.
20//
21// Burn rate, the context trend and card tabs: two sparklines drawn from the
22// same record, each in a tab of its own, and which tab each card shows.
23//
24// The usage summary writer: which steps count, the numbers kept in module
25// memory, the summary file's shape and strict check, its byte cap, and the
26// throttle and single-flight decision; brigade/writer.ts feeds them.
27//
28// The transcript finder: where a member's transcript is, from its working
29// directory or, after it moved into a worktree, from the worktree folders of
30// its launch folder, each checked to lie where its name says before a read.
31//
32// The usage section: this session's own rate limits and context fill, at the
33// bottom of the pane. On the terminal it is rows of text bars. Everywhere else
34// it is an SVG image, built here as a string. Every piece of text in that
35// string goes through `svgText`, and every attribute value is a number or
36// percentage this module worked out (`num`, `pct`), or a fixed name: a class
37// from `STYLE`, a clip id (`cb` for the usage image, `st` for the status
38// strip), `end`, the one gap transform. The test's attribute allowlist holds
39// every image this module builds to those forms: the usage image, the status
40// strip, the to-do bar, the cache bar, the context meter and the two
41// sparklines.
42
43/** A snapshot before the first reading: what the pane holds until one comes. */
44export const EMPTY_USAGE: UsageSnapshot = { limits: [], context: {} }
45
46// What a stored snapshot may hold. A reading comes from the engine, and a
47// rate limit's kind may come from a gateway, so each field is checked and cut
48// here as well as where it is drawn. Plugin state is readable by other
49// plugins, so only the fields the view draws are kept.
50const MAX_LIMITS = 20
51const MAX_CATEGORIES = 50
52const MAX_STORED_TEXT = 200
53const MAX_PERCENT = 100000
54const MAX_TOKENS = 1e10
55
56const isRecord = (v: unknown): v is Record<string, unknown> =>
57 typeof v === 'object' && v !== null && !Array.isArray(v)
58const inRange = (v: unknown, max: number): v is number =>
59 typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= max
60const storedText = (v: unknown): v is string => typeof v === 'string' && v.length <= MAX_STORED_TEXT
61
62// One rate limit, one context and one list of breakdown rows, each checked.
63// A reading names a limit's percent `percentUsed`; a stored snapshot, `percent`.
64function limitsFrom(rows: unknown, percentKey: 'percentUsed' | 'percent'): UsageLimit[] {
65 const out: UsageLimit[] = []
66 if (!Array.isArray(rows)) return out
67 for (const r of rows.slice(0, MAX_LIMITS)) {
68 if (!isRecord(r) || !storedText(r.kind) || !inRange(r[percentKey], MAX_PERCENT)) continue
69 const limit: UsageLimit = { kind: r.kind, percent: r[percentKey] as number }
70 if (typeof r.resetsAt === 'string' && r.resetsAt.length <= 40) limit.resetsAt = r.resetsAt
71 out.push(limit)
72 }
73 return out
74}
75
76function contextFrom(ctx: unknown): UsageSnapshot['context'] {
77 const out: UsageSnapshot['context'] = {}
78 if (!isRecord(ctx)) return out
79 if (inRange(ctx.percent, MAX_PERCENT)) out.percent = ctx.percent
80 if (inRange(ctx.tokens, MAX_TOKENS)) out.tokens = ctx.tokens
81 if (inRange(ctx.window, MAX_TOKENS)) out.window = ctx.window
82 return out
83}
84
85function categoriesFrom(rows: unknown[]): UsageCategory[] {
86 const out: UsageCategory[] = []
87 for (const c of rows.slice(0, MAX_CATEGORIES)) {
88 if (!isRecord(c) || !storedText(c.name) || typeof c.kind !== 'string' || !KINDS.has(c.kind) || !inRange(c.tokens, MAX_TOKENS)) continue
89 out.push({ name: c.name, kind: c.kind, tokens: c.tokens })
90 }
91 return out
92}
93
94/** The fields the view draws from a `$.session.usage()` reading, each checked:
95 * per rate limit its kind, percent and reset time; the context's percent,
96 * tokens and window; per breakdown row its name, kind and tokens. A field
97 * that fails its check is left out, and a row whose kind or number fails is
98 * dropped. */
99export function snapshotFrom(reading: unknown): UsageSnapshot {
100 if (!isRecord(reading)) return { limits: [], context: {} }
101 const out: UsageSnapshot = { limits: limitsFrom(reading.rateLimits, 'percentUsed'), context: contextFrom(reading.context) }
102 const b = isRecord(reading.context) ? reading.context.breakdown : undefined
103 if (isRecord(b) && Array.isArray(b.categories)) out.categories = categoriesFrom(b.categories)
104 return out
105}
106
107/** A stored snapshot checked again before it is drawn, by the same rules.
108 * Only `snapshotFrom` writes it, but plugin state is the engine's, and the
109 * engine lets another plugin rewrite a value as it is set: a value of the
110 * wrong shape draws as far as it checks, and never throws. */
111export function storedSnapshot(stored: unknown): UsageSnapshot {
112 if (!isRecord(stored)) return { limits: [], context: {} }
113 const out: UsageSnapshot = { limits: limitsFrom(stored.limits, 'percent'), context: contextFrom(stored.context) }
114 if (Array.isArray(stored.categories)) out.categories = categoriesFrom(stored.categories)
115 return out
116}
117const KINDS = new Set(['used', 'free', 'buffer', 'deferred'])
118
119// The names the app gives its own windows. Looked up in a Map, never a plain
120// object: a kind is free text, and on a plain object `constructor` or
121// `toString` would answer with a function.
122const LIMIT_NAMES = new Map([
123 ['five_hour', 'Current session'],
124 ['seven_day', 'Weekly limit'],
125 ['spend_limit', 'Spend limit'],
126])
127const MAX_KIND = 30
128const MAX_CATEGORY = 60
129
130/** A rate limit's name as drawn: the app's own for a window it knows, else
131 * its kind made safe to draw on one line and cut to 30 characters. */
132export const limitName = (kind: string): string => LIMIT_NAMES.get(kind) ?? oneLine(kind, MAX_KIND)
133
134// An ISO 8601 time with seconds and either Z or an offset, read by hand so
135// every engine reads it alike.
136const ISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/
137
138function isoTime(text: string): number | undefined {
139 const m = ISO.exec(text)
140 if (m === null) return undefined
141 const [, y, mo, d, h, mi, s, frac, zone] = m
142 const month = Number(mo)
143 const day = Number(d)
144 const hour = Number(h)
145 const minute = Number(mi)
146 const second = Number(s)
147 if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59 || second > 59) return undefined
148 const ms = frac === undefined ? 0 : Number(frac.padEnd(3, '0').slice(0, 3))
149 let at = Date.UTC(Number(y), month - 1, day, hour, minute, second, ms)
150 if (zone !== undefined && zone !== 'Z') {
151 const sign = zone.startsWith('-') ? -1 : 1
152 const zh = Number(zone.slice(1, 3))
153 const zm = Number(zone.slice(4, 6))
154 if (zh > 23 || zm > 59) return undefined
155 at -= sign * (zh * 60 + zm) * 60000
156 }
157 // Date.UTC rolls 31 April over to 1 May; a day that rolled is refused.
158 return new Date(Date.UTC(Number(y), month - 1, day)).getUTCDate() === day && Number.isFinite(at) ? at : undefined
159}
160
161/** "Resets in N d N hr", "Resets in N hr N min" or "Resets in N min", or
162 * undefined when the time is missing or not a valid ISO time. A time in the
163 * past reads as 0 min. */
164export function resetsIn(iso: string | undefined, now: number): string | undefined {
165 if (iso === undefined) return undefined
166 const at = isoTime(iso)
167 if (at === undefined || !Number.isFinite(now)) return undefined
168 const mins = Math.max(0, Math.round((at - now) / 60000))
169 const d = Math.floor(mins / 1440)
170 const h = Math.floor((mins % 1440) / 60)
171 const m = mins % 60
172 return `Resets in ${d > 0 ? `${d} d ${h} hr` : h > 0 ? `${h} hr ${m} min` : `${m} min`}`
173}
174
175/** A token count as the pane draws it: "Nk" from 10,000, "N.Nk" from 1,000,
176 * and "N" below that. */
177export function tokens(n: number): string {
178 if (!Number.isFinite(n) || n < 0) return '0'
179 if (n >= 10000) return `${Math.round(n / 1000)}k`
180 if (n >= 1000) return `${(Math.floor(n / 100) / 10).toFixed(1)}k`
181 return `${Math.round(n)}`
182}
183
184const percentText = (p: number) => `${Math.round(p)}%`
185
186// From 75% a bar is amber, from 90% red.
187const level = (p: number) => (p >= 90 ? 'hot' : p >= 75 ? 'warn' : 'ok')
188const TONE = new Map([
189 ['ok', 'success'],
190 ['warn', 'warning'],
191 ['hot', 'error'],
192])
193
194/** One row of the terminal's text bars. `tone` is a theme colour key, for
195 * `bar`. `ahead` is drawn dim after it: the projection's ░ cells, then the
196 * blanks; the two together are always 20 cells, and with no projection
197 * `bar` is all 20 and `ahead` is empty. `noteTone` is a theme colour key for
198 * the note, or empty for a dim note. */
199export type UsageRow = { name: string; bar: string; ahead: string; percent: string; note: string; tone: string; noteTone: string }
200
201/** What the usage section draws: nothing yet, text bars, or an SVG image.
202 * The image has a fixed height and no width: it is placed in percentages,
203 * so it takes the width of the box it is drawn in. */
204export type UsageView =
205 | { kind: 'none' }
206 | { kind: 'text'; rows: UsageRow[] }
207 | { kind: 'svg'; source: string; alt: string; height: number }
208
209const BAR_CELLS = 20
210
211// The partial cells, one to seven eighths full.
212const EIGHTHS = ['▏', '▎', '▍', '▌', '▋', '▊', '▉']
213
214/** A terminal bar of `cells` cells: full blocks, one partial block to the
215 * nearest eighth of a cell, then blanks. The fraction is clamped to between
216 * 0 and 1, and one that is not a finite number is 0. It never throws and
217 * always returns exactly `cells` characters, the end marks left to the
218 * caller; a cell count that is not a positive whole number gives an empty
219 * string. */
220export function eighthBar(fraction: number, cells: number): string {
221 const n = Number.isInteger(cells) && cells > 0 ? cells : 0
222 const f = Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0
223 const eighths = Math.round(f * n * 8)
224 const full = Math.floor(eighths / 8)
225 const part = EIGHTHS[(eighths % 8) - 1] ?? ''
226 const drawn = '█'.repeat(full) + part
227 return drawn + ' '.repeat(n - [...drawn].length)
228}
229
230/** The engine's cap on an SVG's source. */
231export const SVG_MAX = 131072
232/** The most breakdown rows the legend lists. */
233export const LEGEND_MAX = 12
234
235/** The breakdown rows the context bar draws: not the tools loaded on demand,
236 * which sit outside the window, and not a row with no tokens. */
237const drawnCategories = (s: UsageSnapshot) =>
238 (s.categories ?? []).filter(c => c.kind !== 'deferred' && Number.isFinite(c.tokens) && c.tokens > 0)
239
240/** The usage section for one surface at one moment, from the stored snapshot,
241 * checked again here. With no rate limit, no breakdown and no context reading
242 * it is nothing yet, on every surface. The terminal gets text bars: a Context
243 * row from the context's percent and tokens, then a row per rate limit. Every
244 * other surface gets the SVG, or the text bars when there is no rate limit
245 * and no breakdown to draw or the SVG would pass the engine's cap. max is
246 * that cap; the stored caps keep a real snapshot far below it, so a test
247 * passes a smaller one to reach the fallback. `samples` is the stored
248 * sample buffer, checked again here, for the session limit's projection. */
249export function usageView(stored: unknown, surface: string, now: number, max = SVG_MAX, samples: unknown = []): UsageView {
250 const s = storedSnapshot(stored)
251 if (s.limits.length === 0 && drawnCategories(s).length === 0 && s.context.percent === undefined) return { kind: 'none' }
252 const kept = samplesFrom(samples)
253 if (surface !== 'terminal') {
254 const svg = usageSvg(s, now, kept)
255 if (svg !== undefined && svg.source.length <= max) return svg
256 }
257 const rows = textRows(s, now, kept)
258 return rows.length === 0 ? { kind: 'none' } : { kind: 'text', rows }
259}
260
261function textRows(s: UsageSnapshot, now: number, samples: readonly Sample[]): UsageRow[] {
262 const rows: Omit<UsageRow, 'name'>[] = []
263 const names: string[] = []
264 const cells = (p: number) => eighthBar(p / 100, BAR_CELLS)
265 const { percent, tokens: used, window } = s.context
266 if (percent !== undefined && Number.isFinite(percent)) {
267 names.push('Context')
268 rows.push({
269 bar: cells(percent),
270 ahead: '',
271 percent: percentText(percent),
272 note: used !== undefined && window !== undefined ? `${tokens(used)} of ${tokens(window)}` : '',
273 tone: TONE.get(level(percent)) ?? 'success',
274 noteTone: '',
275 })
276 }
277 for (const limit of s.limits) {
278 if (!Number.isFinite(limit.percent)) continue
279 names.push(limitName(limit.kind))
280 const p = projection(limit, samples, now)
281 rows.push({
282 ...projectedCells(limit.percent, p),
283 percent: percentText(limit.percent),
284 note: p?.earlyMs !== undefined ? earlyText(p.earlyMs) : (resetsIn(limit.resetsAt, now) ?? ''),
285 tone: TONE.get(level(limit.percent)) ?? 'success',
286 noteTone: p?.earlyMs !== undefined ? 'error' : '',
287 })
288 }
289 const width = Math.max(0, ...names.map(n => [...n].length))
290 return rows.map((r, i) => ({ name: (names[i] ?? '').padEnd(width), ...r }))
291}
292
293// The image cannot read the app's theme, so it carries a palette of its own
294// that only approximates the app's, with a dark-mode rule. The class names
295// here are the only ones the SVG uses. Exported so the allowlist test can
296// hold every image's style block to exactly this text.
297export const STYLE = [
298 "text{font-family:system-ui,-apple-system,'Segoe UI',sans-serif;font-size:12px;fill:#3d3d3a}",
299 '.muted{fill:#73726c}',
300 '.track{fill:#e8e6dc}',
301 '.ok{fill:#2c84db}.warn{fill:#c27c0e}.hot{fill:#c6413a}',
302 // The usage projection: a faint form of ok's blue.
303 '.proj{fill:#a9cdf0}',
304 '.done{fill:#3f8f4f}.stopped{fill:#9c9a92}',
305 '.free{fill:#e8e6dc}.buffer{fill:#d6d3c8}',
306 // The hairline between cards.
307 '.rule{fill:#e0ded6}',
308 // A PR pill, as Desktop draws its own: a tint of the state and its ink.
309 '.tint-open{fill:#dff3e4}.tint-merged{fill:#ece6fb}.tint-closed{fill:#fbe3e1}',
310 '.ink-open,.ink-merged,.ink-closed{font-size:11px;font-weight:500}.ink-open{fill:#2f7d3f}.ink-merged{fill:#6f4fc9}.ink-closed{fill:#c6413a}',
311 '.c0{fill:#d97757}.c1{fill:#6a9bcc}.c2{fill:#788c5d}.c3{fill:#c46686}.c4{fill:#8b7fc7}.c5{fill:#c9a227}.c6{fill:#5fa8a0}',
312 '@media (prefers-color-scheme: dark){text{fill:#e8e6e1}.muted{fill:#9c9a92}.track,.free{fill:#3a3935}.buffer{fill:#4a4944}.ok{fill:#5aa2ef}.proj{fill:#2f5f8f}.warn{fill:#e8a23a}.hot{fill:#ef6b62}.done{fill:#62b56f}.stopped{fill:#6b6a64}.tint-open{fill:#1f3a26}.tint-merged{fill:#2e2547}.tint-closed{fill:#3a1f1f}.ink-open{fill:#62b56f}.ink-merged{fill:#a48be0}.ink-closed{fill:#ef6b62}.rule{fill:#333331}}',
313].join('')
314
315const XMLNS = 'http://www.w3.org/2000/svg'
316
317// Code points XML forbids even escaped: a lone surrogate, U+FFFE and U+FFFF.
318// One of them makes the whole image fail to draw. The controls XML forbids
319// are gone already: the one-line cleaner makes them spaces.
320const XML_INVALID = /[\u{D800}-\u{DFFF}\u{FFFE}\u{FFFF}]/gu
321const XML_ESCAPE = new Map([
322 ['&', '&'],
323 ['<', '<'],
324 ['>', '>'],
325 ['"', '"'],
326 ["'", '''],
327])
328
329/** Text made safe for the SVG's element content: the one-line cleaner, cut to
330 * `max`, then the code points XML forbids removed, then the XML escape. */
331export function svgText(text: string, max: number): string {
332 return oneLine(text, max)
333 .replace(XML_INVALID, '')
334 .replace(/[&<>"']/g, ch => XML_ESCAPE.get(ch) ?? '')
335}
336
337/** A number as an attribute value: finite, clamped to the drawing's range and
338 * rounded to two places, so no NaN or Infinity is ever written. */
339export function num(v: number, max = 100000): string {
340 const n = Number.isFinite(v) ? Math.min(max, Math.max(0, v)) : 0
341 return String(Math.round(n * 100) / 100)
342}
343
344/** A number as a percentage attribute value: `num` up to 100, then `%`. */
345export const pct = (v: number): string => `${num(v, 100)}%`
346
347// A name on the left, a note on the right, and a thin rounded bar beneath,
348// placed in percentages so the row spans the image's width. A projection is a
349// faint bar from 0 to the projected percent, capped at 100%, drawn under the
350// fill: the fill covers it up to the bar's end, so what shows is the part from
351// the bar's end to the projected percent. An early note is red, else muted.
352function barRow(y: number, name: string, right: string, percent: number, projected?: number, early = false): string {
353 return (
354 `<text x="0" y="${num(y + 12)}">${svgText(name, MAX_KIND)}</text>` +
355 `<text class="${early ? 'hot' : 'muted'}" x="100%" y="${num(y + 12)}" text-anchor="end">${svgText(right, 80)}</text>` +
356 `<rect class="track" x="0" y="${num(y + 20)}" width="100%" height="6" rx="3"/>` +
357 (projected !== undefined ? `<rect class="proj" x="0" y="${num(y + 20)}" width="${pct(Math.min(100, projected))}" height="6" rx="3"/>` : '') +
358 // A fill never narrower than 6 px: a pixel minimum cannot be written as
359 // a percentage, so a fixed 6 px stub sits under the percentage fill, and
360 // the two cover whichever is wider.
361 (percent > 0
362 ? `<rect class="${level(percent)}" x="0" y="${num(y + 20)}" width="6" height="6" rx="3"/>` +
363 `<rect class="${level(percent)}" x="0" y="${num(y + 20)}" width="${pct(percent)}" height="6" rx="3"/>`
364 : '')
365 )
366}
367
368function usageSvg(s: UsageSnapshot, now: number, samples: readonly Sample[]): Extract<UsageView, { kind: 'svg' }> | undefined {
369 const parts: string[] = []
370 const alt: string[] = []
371 let y = 0
372
373 for (const limit of s.limits) {
374 if (!Number.isFinite(limit.percent)) continue
375 const name = limitName(limit.kind)
376 const p = projection(limit, samples, now)
377 const earlyNote = p?.earlyMs !== undefined ? earlyText(p.earlyMs) : undefined
378 const when = earlyNote ?? resetsIn(limit.resetsAt, now)
379 parts.push(barRow(y, name, when === undefined ? percentText(limit.percent) : `${when} · ${percentText(limit.percent)}`, limit.percent, p?.percent, earlyNote !== undefined))
380 alt.push(
381 `${name} ${percentText(limit.percent)}` +
382 (p === undefined ? '' : `, on pace for ${percentText(p.percent)} at reset`) +
383 (earlyNote === undefined ? '' : `, ${earlyNote}`),
384 )
385 y += 38
386 }
387
388 const shown = drawnCategories(s)
389 if (shown.length > 0) {
390 // The bar's segments are the breakdown's rows, free space and buffer
391 // included. The figures beside it are the engine's own context reading,
392 // the ones the terminal's Context row shows, so one reading shows one
393 // figure everywhere; only without that reading are they summed from the
394 // rows: used is the rows of kind `used`, the window every row drawn.
395 const total = shown.reduce((sum, c) => sum + c.tokens, 0)
396 const used = shown.filter(c => c.kind === 'used')
397 const { percent: ctxPercent, tokens: ctxTokens, window: ctxWindow } = s.context
398 const engine = ctxPercent !== undefined && ctxTokens !== undefined && ctxWindow !== undefined
399 const usedTokens = engine ? ctxTokens : used.reduce((sum, c) => sum + c.tokens, 0)
400 const windowTokens = engine ? ctxWindow : total
401 const usedPercent = engine ? ctxPercent : total > 0 ? (usedTokens / total) * 100 : 0
402 const cls = (c: UsageCategory) => (c.kind === 'free' ? 'free' : c.kind === 'buffer' ? 'buffer' : `c${Math.max(0, used.indexOf(c)) % 7}`)
403
404 parts.push(`<text x="0" y="${num(y + 12)}">${svgText('Context', MAX_KIND)}</text>`)
405 parts.push(
406 `<text class="muted" x="100%" y="${num(y + 12)}" text-anchor="end">${svgText(`${tokens(usedTokens)} / ${tokens(windowTokens)} · ${percentText(usedPercent)}`, 80)}</text>`,
407 )
408 parts.push(`<clipPath id="cb"><rect x="0" y="${num(y + 20)}" width="100%" height="8" rx="4"/></clipPath>`)
409 parts.push(`<rect class="track" x="0" y="${num(y + 20)}" width="100%" height="8" rx="4"/>`)
410 const segments: string[] = []
411 let x = 0
412 for (const c of shown) {
413 const w = total > 0 ? (c.tokens / total) * 100 : 0
414 // A gap between used segments, as the app's segmented bar has. A gap
415 // in pixels cannot be written in percentages, so the segment sits in a
416 // nested <svg> and its rect moves 2 px left: the nested <svg> cuts off
417 // what spills, leaving 2 px clear at its right edge at any width. `w`
418 // is the segment's percentage of the bar; at 1% or less the 2 px gap
419 // would eat most of it on a narrow pane, so it gets none.
420 if (c.kind === 'used' && w > 1) {
421 segments.push(
422 `<svg x="${pct(x)}" y="${num(y + 20)}" width="${pct(w)}" height="8"><rect class="${cls(c)}" width="100%" height="8" transform="translate(-2 0)"/></svg>`,
423 )
424 } else {
425 segments.push(`<rect class="${cls(c)}" x="${pct(x)}" y="${num(y + 20)}" width="${pct(w)}" height="8"/>`)
426 }
427 x += w
428 }
429 parts.push(`<g clip-path="url(#cb)">${segments.join('')}</g>`)
430 y += 40
431
432 // The legend: two columns of dot, name and tokens, at most LEGEND_MAX
433 // rows. Each entry is a nested <svg> half the image wide, at 0 or 50%,
434 // so its dot and name can sit a fixed number of pixels in; the right
435 // column's entries sit 10 px further in, clear of the left column's
436 // tokens.
437 const legend = shown.slice(0, LEGEND_MAX)
438 legend.forEach((c, i) => {
439 const inset = (i % 2) * 10
440 parts.push(
441 `<svg x="${i % 2 === 0 ? '0' : '50%'}" y="${num(y + Math.floor(i / 2) * 18)}" width="50%" height="18">` +
442 `<circle class="${cls(c)}" cx="${num(inset + 4)}" cy="8" r="4"/>` +
443 `<text x="${num(inset + 14)}" y="12">${svgText(c.name, MAX_CATEGORY)}</text>` +
444 `<text class="muted" x="100%" y="12" text-anchor="end">${svgText(tokens(c.tokens), 20)}</text>` +
445 '</svg>',
446 )
447 })
448 y += Math.ceil(legend.length / 2) * 18
449 alt.push(`Context ${percentText(usedPercent)}: ${legend.map(c => `${oneLine(c.name, MAX_CATEGORY)} ${tokens(c.tokens)}`).join(', ')}`)
450 }
451
452 if (y === 0) return undefined
453 // No viewBox: nothing is scaled, so text keeps its size, and the image
454 // takes its box's width. Only the height is fixed.
455 const height = num(y)
456 const source = `<svg xmlns="${XMLNS}" width="100%" height="${height}">` + `<style>${STYLE}</style>${parts.join('')}</svg>`
457 return { kind: 'svg', source, alt: oneLine(`Usage: ${alt.join('; ')}`, 2000), height: Number(height) }
458}
459
460// --- Usage projection --------------------------------------------------------
461//
462// Where the session limit and the weekly limit will be at reset if the
463// current pace holds. Only `five_hour` and `seven_day` get one, each with a
464// reset time `isoTime` reads; a kind a gateway names gets none. The session
465// limit's pace is recent: the change across the samples the pane took of it
466// in the last 30 minutes. The weekly limit's is its average since the week
467// began, so it takes no samples. The samples are plugin state, which another
468// plugin can rewrite, so every read goes through `samplesFrom`.
469
470/** The least time between two samples of the session limit. */
471export const SAMPLE_MS = 30000
472/** The most samples kept: an hour at one every 30 s. */
473export const MAX_SAMPLES = 120
474const RECENT_MS = 30 * 60000
475const MIN_SPAN_MS = 5 * 60000
476const WEEK_MS = 7 * 24 * 3600000
477const MIN_WEEK_MS = 3600000
478
479/** The stored sample buffer, checked again: a list of at most 120 samples,
480 * each `at` a finite number and `percent` from 0 to 100, times increasing.
481 * A buffer that fails any check is treated as empty, whole: a buffer cut
482 * down to its good samples could hold a pace nobody measured. Each field is
483 * read once, and a read that throws counts as a failed check, so a value
484 * that changes or throws as it is read cannot pass or break it. */
485export function samplesFrom(stored: unknown): Sample[] {
486 try {
487 if (!Array.isArray(stored)) return []
488 // The length is read once and the list walked by position up to it,
489 // never by its own walker, which could yield more than it reports.
490 const length = stored.length
491 if (typeof length !== 'number' || length > MAX_SAMPLES) return []
492 const out: Sample[] = []
493 for (let i = 0; i < length; i++) {
494 const s: unknown = stored[i]
495 if (!isRecord(s)) return []
496 const at = s.at
497 const percent = s.percent
498 if (typeof at !== 'number' || !Number.isFinite(at) || !inRange(percent, 100)) return []
499 const last = out[out.length - 1]
500 if (last !== undefined && at <= last.at) return []
501 out.push({ at, percent })
502 }
503 return out
504 } catch {
505 return []
506 }
507}
508
509/** The buffer after a usage reading: the session limit's percent at `now`
510 * appended, at most one sample every 30 s and at most 120 kept. A percent
511 * lower than the last sample's means the window reset, and a last sample
512 * dated after `now` means the clock went back or the value was rewritten:
513 * either way the buffer starts over at this sample. A reading with no
514 * session limit, or one over 100%, which the check would refuse, adds
515 * nothing. */
516export function addSample(stored: unknown, s: UsageSnapshot, now: number): Sample[] {
517 const kept = samplesFrom(stored)
518 const limit = s.limits.find(l => l.kind === 'five_hour')
519 if (limit === undefined || !inRange(limit.percent, 100) || !Number.isFinite(now)) return kept
520 const next = { at: now, percent: limit.percent }
521 const last = kept[kept.length - 1]
522 if (last === undefined || limit.percent < last.percent || now < last.at) return [next]
523 if (now - last.at < SAMPLE_MS) return kept
524 return [...kept, next].slice(-MAX_SAMPLES)
525}
526
527// Percent a millisecond, from the oldest sample in the last 30 minutes to the
528// newest, or undefined when they are under 5 minutes apart. A sample dated
529// after `now` is left out.
530function recentPace(samples: readonly Sample[], now: number): number | undefined {
531 const recent = samples.filter(x => x.at >= now - RECENT_MS && x.at <= now)
532 const first = recent[0]
533 const last = recent[recent.length - 1]
534 if (first === undefined || last === undefined || last.at - first.at < MIN_SPAN_MS) return undefined
535 return (last.percent - first.percent) / (last.at - first.at)
536}
537
538/** A limit's projection: the percent it will be at reset at the current
539 * pace, and past 100% how many milliseconds before the reset it runs out. */
540export type Projection = { percent: number; earlyMs?: number }
541
542/** The projection for one limit, or undefined: for a kind other than
543 * `five_hour` and `seven_day`, for a limit already run out, with no reset
544 * time to read or none still ahead, with too little to measure a pace from
545 * (under 5 minutes between
546 * the session limit's samples, under an hour since the weekly limit's week
547 * began), or when the pace is 0 or less. */
548export function projection(limit: UsageLimit, samples: readonly Sample[], now: number): Projection | undefined {
549 if (limit.kind !== 'five_hour' && limit.kind !== 'seven_day') return undefined
550 // A limit at or over 100%, as its row draws it rounded, has run out: no
551 // projection, so its row keeps the reset time, when it comes back (owner
552 // decision q1 A).
553 if (Math.round(limit.percent) >= 100) return undefined
554 const reset = limit.resetsAt === undefined ? undefined : isoTime(limit.resetsAt)
555 if (reset === undefined || !Number.isFinite(now) || !Number.isFinite(limit.percent) || reset <= now) return undefined
556 let pace: number | undefined
557 if (limit.kind === 'five_hour') {
558 pace = recentPace(samples, now)
559 } else {
560 const since = now - (reset - WEEK_MS)
561 pace = since >= MIN_WEEK_MS ? limit.percent / since : undefined
562 }
563 if (pace === undefined || !Number.isFinite(pace) || pace <= 0) return undefined
564 const percent = limit.percent + pace * (reset - now)
565 if (!Number.isFinite(percent)) return undefined
566 if (percent <= 100) return { percent }
567 const earlyMs = reset - (now + (100 - limit.percent) / pace)
568 return Number.isFinite(earlyMs) ? { percent, earlyMs } : { percent }
569}
570
571/** A span as the early note reads it: minutes under an hour, hours under a
572 * day, then days, each rounded, and never under 1 minute. A span that is not
573 * a finite number reads as 1 minute. */
574export function roughTime(ms: number): string {
575 const mins = Number.isFinite(ms) ? Math.max(1, Math.round(ms / 60000)) : 1
576 if (mins >= 1440) return `${Math.round(mins / 1440)} d`
577 if (mins >= 60) return `${Math.round(mins / 60)} hr`
578 return `${mins} min`
579}
580
581const earlyText = (ms: number) => `runs out about ${roughTime(ms)} early`
582
583// A limit's terminal cells: its bar, then with a projection the ░ cells from
584// the bar's end to the projected percent, capped at 20 cells, then blanks.
585function projectedCells(percent: number, p: Projection | undefined): { bar: string; ahead: string } {
586 const full = eighthBar(percent / 100, BAR_CELLS)
587 if (p === undefined) return { bar: full, ahead: '' }
588 const bar = full.trimEnd()
589 const used = [...bar].length
590 const to = Math.round((Math.min(100, Math.max(0, p.percent)) / 100) * BAR_CELLS)
591 const cells = Math.max(0, to - used)
592 return { bar, ahead: '░'.repeat(cells) + ' '.repeat(BAR_CELLS - used - cells) }
593}
594
595// --- Tick and undo ---------------------------------------------------------
596//
597// A press on a to-do's box ticks it: the to-do stays, crossed out, for the
598// grace period, and a second press inside it undoes the tick. The roster
599// timer's sweep then moves it to done. `ticking` holds pairs of to-do id and
600// tick time, in epoch ms as text.
601
602/** How long a ticked to-do stays, crossed out, before the sweep moves it. */
603export const GRACE_MS = 30000
604const MAX_TICKS = 50
605
606/** The stored ticks, checked again: a list of pairs whose name is text within
607 * the stored cap, the first of a repeated name kept, at most 50. A value
608 * that is not text is kept as an empty value, which the sweep counts as due.
609 * Plugin state is the engine's, and another plugin may rewrite it. */
610export function ticksFrom(stored: unknown): Pair[] {
611 const out: Pair[] = []
612 if (!Array.isArray(stored)) return out
613 const names = new Set<string>()
614 for (const p of stored) {
615 if (out.length >= MAX_TICKS) break
616 if (!isRecord(p) || typeof p.name !== 'string' || p.name === '' || p.name.length > MAX_STORED_TEXT || names.has(p.name)) continue
617 names.add(p.name)
618 out.push({ name: p.name, value: typeof p.value === 'string' ? p.value : '' })
619 }
620 return out
621}
622
623/** The stored done list, checked again: the text entries of a list, and
624 * nothing from any other shape, so a value another plugin wrote cannot make
625 * the render throw. */
626export function idsFrom(stored: unknown): string[] {
627 return Array.isArray(stored) ? stored.filter((v): v is string => typeof v === 'string') : []
628}
629
630/** A press: tick the to-do with the press time, or undo its tick. */
631export function toggleTick(stored: unknown, id: string, now: number): Pair[] {
632 const ticking = ticksFrom(stored)
633 return ticking.some(p => p.name === id) ? ticking.filter(p => p.name !== id) : [...ticking, { name: id, value: String(now) }]
634}
635
636// Due: the grace period has passed, the time is not a number, or the time is
637// more than a grace period ahead of the clock, so a planted far-future time
638// cannot keep a to-do crossed out for good.
639const isDue = (p: Pair, now: number) => {
640 const age = now - Number(p.value)
641 return !Number.isFinite(age) || age >= GRACE_MS || age <= -GRACE_MS
642}
643
644/** The sweep: a tick whose to-do is no longer in the roster is dropped, a due
645 * one moves to `done`, and the rest stay. `todoIds` is undefined when the
646 * roster load failed or found no file: then every tick stays, due ones too,
647 * so a brief miss cannot silently undo a tick. */
648export function sweepTicks(stored: unknown, now: number, todoIds: readonly string[] | undefined): { ticking: Pair[]; done: string[] } {
649 const ticking = ticksFrom(stored)
650 if (todoIds === undefined) return { ticking, done: [] }
651 const present = new Set(todoIds)
652 const kept: Pair[] = []
653 const done: string[] = []
654 for (const p of ticking) {
655 if (!present.has(p.name)) continue
656 if (isDue(p, now)) done.push(p.name)
657 else kept.push(p)
658 }
659 return { ticking: kept, done }
660}
661
662/** One write to a stored value, as the engine's `update` makes it: the
663 * function may run more than once, and the last run's result is written. */
664export type Updater<T> = (fn: (value: T) => T) => Promise<unknown>
665
666/** The roster timer's sweep, carried out. The due ids are worked out inside
667 * the `ticking` update, from the value that update writes over, so an undo
668 * that lands between a read and a write cannot be lost to a stale read. Then
669 * those ids, and no others, are added to `doneTodos`, each once. With no
670 * roster load to go by (`todoIds` undefined) nothing is written. Resolves the
671 * ids it moved. */
672export async function settleTicks(
673 ticking: Updater<Pair[]>,
674 doneTodos: Updater<string[]>,
675 now: number,
676 todoIds: readonly string[] | undefined,
677): Promise<string[]> {
678 if (todoIds === undefined) return []
679 let due: string[] = []
680 await ticking(list => {
681 const swept = sweepTicks(list, now, todoIds)
682 due = swept.done
683 return swept.ticking
684 })
685 if (due.length > 0) {
686 const moved = due
687 await doneTodos(list => {
688 const had = idsFrom(list)
689 const seen = new Set(had)
690 return [...had, ...moved.filter(id => !seen.has(id))]
691 })
692 }
693 return due
694}
695
696// --- Severity groups --------------------------------------------------------
697//
698// The cards sit in three groups by the status the head chef wrote: Waiting on
699// you, Working, and Done · stopped. Any group folds on a press, and
700// STARTS_FOLDED in register.tsx says which start folded. The stored
701// roster is drawn as stored, and another plugin can rewrite it, so a status is
702// read only through the fixed Map below: one outside the four words, or one
703// that names a prototype key, has no look and counts nowhere. No key, class or
704// text is ever built from the status text.
705
706/** How a status draws: its glyph, word, theme colour key, SVG class and
707 * group. Colour is never the only signal: the glyph and word go with it. */
708export type StatusLook = {
709 glyph: string
710 word: string
711 color: string
712 cls: string
713 group: 'needsYou' | 'working' | 'finished'
714}
715
716/** The four statuses, in display order: needs you, working, done, stopped. */
717export const STATUS: ReadonlyMap<string, StatusLook> = new Map([
718 ['needs-you', { glyph: '●', word: 'needs you', color: 'warning', cls: 'warn', group: 'needsYou' }],
719 ['working', { glyph: '◐', word: 'working', color: 'suggestion', cls: 'ok', group: 'working' }],
720 ['done', { glyph: '✓', word: 'done', color: 'success', cls: 'done', group: 'finished' }],
721 ['stopped', { glyph: '–', word: 'stopped', color: 'inactive', cls: 'stopped', group: 'finished' }],
722] as const)
723
724/** A stored status's look, or undefined for anything but the four words. */
725export const statusOf = (status: unknown): StatusLook | undefined =>
726 typeof status === 'string' ? STATUS.get(status) : undefined
727
728/** A card and its place in the roster. Every button a card draws keys on that
729 * place, never its place inside a group: the press handler finds a card by
730 * roster place and title slug, and the slug folds many titles to one. */
731export type Placed<T> = { c: T; i: number }
732export type Groups<T> = { needsYou: Placed<T>[]; working: Placed<T>[]; finished: Placed<T>[] }
733
734/** The stored cards in their groups, each in roster order. A card whose title
735 * is in `hidden`, the dismissed ones, is in none unless it waits on the owner,
736 * and a card that is not a record or has no look is in none; cards that are
737 * not a list give three empty groups. A working card the poll moved (see
738 * `movedLook`) is in the group of its move. */
739export function groupCards<T>(cards: readonly T[], hidden: ReadonlySet<unknown>, moves?: Moves): Groups<T> {
740 const out: Groups<T> = { needsYou: [], working: [], finished: [] }
741 if (!Array.isArray(cards)) return out
742 cards.forEach((c, i) => {
743 const look = shownLook(c, hidden, moves)
744 if (look !== undefined) out[look.group].push({ c, i })
745 })
746 return out
747}
748
749/** Where the live poll moved cards, by card title. */
750export type Moves = ReadonlyMap<string, Move>
751
752/** The moves the stored live entries hold, by card title. */
753export function movesFrom(list: readonly Live[]): Moves {
754 return new Map(list.flatMap(l => (l.move === undefined ? [] : [[l.name, l.move] as const])))
755}
756
757/** The look a card's move gives it, or undefined: a move applies only while
758 * the card's own status is `working`, so a status the head chef wrote since
759 * the poll holds. A move to `waiting` draws as needs-you, one to
760 * `finished` as stopped. */
761export function movedLook(c: unknown, moves: Moves | undefined): StatusLook | undefined {
762 if (moves === undefined || !isRecord(c) || c.status !== 'working' || typeof c.title !== 'string') return undefined
763 const move = moves.get(c.title)
764 return move === 'waiting' ? STATUS.get('needs-you') : undefined
765}
766
767/** A stored card's look when the pane shows it: a record with one of the four
768 * statuses, or a working card's moved look (see `movedLook`), that is not
769 * dismissed, or waits on the owner; else undefined. The groups, the heading and the
770 * status strip all count cards by this one rule. */
771function shownLook(c: unknown, hidden: ReadonlySet<unknown>, moves?: Moves): StatusLook | undefined {
772 if (!isRecord(c)) return undefined
773 const look = movedLook(c, moves) ?? statusOf(c.status)
774 // A card that waits on the owner is never hidden, whatever was dismissed.
775 return look !== undefined && look.group !== 'needsYou' && hidden.has(c.title) ? undefined : look
776}
777
778// --- views, folds, selection and the redesigned pane -----------------------------
779//
780// The pane's own values are plugin state another plugin can rewrite, so each is
781// read through a fixed set or a fixed shape and a length cap, and a value that
782// fails reads as empty.
783
784/** The six groups that fold, in the order the pane draws them. */
785export const GROUP_KEYS: readonly string[] = ['waiting', 'working', 'finished', 'pr-open', 'pr-merged', 'pr-closed']
786
787/** A group's name on its section bar. */
788export const GROUP_NAMES: ReadonlyMap<string, string> = new Map([
789 ['waiting', 'Waiting on you'],
790 ['working', 'Working'],
791 ['finished', 'Done · stopped'],
792 ['pr-open', 'Open'],
793 ['pr-merged', 'Merged'],
794 ['pr-closed', 'Closed'],
795])
796
797/** The quiet line an empty group shows. */
798export const GROUP_HINTS: ReadonlyMap<string, string> = new Map([
799 ['waiting', 'Decisions, reviews, and permission requests.'],
800 ['working', 'No session is working.'],
801 ['finished', 'Sessions the owner closed.'],
802 ['pr-open', 'No open pull requests.'],
803 ['pr-merged', 'Nothing merged yet.'],
804 ['pr-closed', 'No closed pull requests.'],
805])
806
807const MAX_SCAN = 200
808const MAX_KEPT = 50
809const MAX_PICK_TITLE = 80
810/** The most cards selected at once. */
811export const MAX_PICKED = 50
812
813/** The chosen view: `prs` only when exactly that word, else `sessions`. */
814export const viewFrom = (stored: unknown): 'sessions' | 'prs' => (stored === 'prs' ? 'prs' : 'sessions')
815
816/** The folded groups: names from the fixed six only, no repeat, from the
817 * first 200 entries, at most 50 kept. Anything else reads as none. */
818export function foldedFrom(stored: unknown): string[] {
819 if (!Array.isArray(stored)) return []
820 const out: string[] = []
821 for (const g of stored.slice(0, MAX_SCAN)) {
822 if (typeof g === 'string' && GROUP_KEYS.includes(g) && !out.includes(g) && out.length < MAX_KEPT) out.push(g)
823 }
824 return out
825}
826
827/** The selected cards' titles: text within the title cap, no repeat, from the
828 * first 200 entries, at most 50 kept. Anything else reads as none. */
829export function pickedFrom(stored: unknown): string[] {
830 if (!Array.isArray(stored)) return []
831 const out: string[] = []
832 for (const t of stored.slice(0, MAX_SCAN)) {
833 if (typeof t === 'string' && [...t].length <= MAX_PICK_TITLE && !out.includes(t) && out.length < MAX_PICKED) out.push(t)
834 }
835 return out
836}
837
838/** The count a section bar adds after its name: the reports its cards sent
839 * since the pane opened, when there are any. */
840export const reportNote = (reports: number): string => (reports > 0 ? ` · ${reports} ${reports === 1 ? 'report' : 'reports'}` : '')
841
842/** A time on the engine clock as an age: `now` under a minute, then whole
843 * minutes, hours and days. A time that is not a whole number from 0 to
844 * 2^53 - 1, or is more than 2 minutes ahead of the clock, has no age. */
845export function ageText(since: unknown, now: number): string | undefined {
846 if (typeof since !== 'number' || !Number.isSafeInteger(since) || since < 0 || !Number.isFinite(now)) return undefined
847 const gap = now - since
848 if (gap < -AHEAD_MS) return undefined
849 if (gap < MIN_MS) return 'now'
850 if (gap < 3600000) return `${Math.floor(gap / MIN_MS)}m`
851 if (gap < 86400000) return `${Math.floor(gap / 3600000)}h`
852 return `${Math.floor(gap / 86400000)}d`
853}
854
855const EFFORT_MARKS: ReadonlyMap<string, string> = new Map([
856 ['low', 'L'],
857 ['medium', 'M'],
858 ['high', 'H'],
859 ['xhigh', 'X'],
860 ['max', '∞'],
861])
862
863/** A card's settings line as one character for the model and one for the
864 * effort, joined by `·` (`O·H`), and the line itself, cleaned and cut to 80,
865 * for the tooltip. */
866export function compactSettings(settings: unknown): { text: string; full: string } {
867 const line = typeof settings === 'string' ? settings : ''
868 const parts = line.split(',').map(p => oneLine(p, 40))
869 const model = [...(parts[0] ?? '')][0]?.toUpperCase() ?? ''
870 const effort = EFFORT_MARKS.get((parts[1] ?? '').toLowerCase()) ?? ''
871 const text = [model, effort].filter(x => x !== '').join('·')
872 return { text: text === '' ? '?' : text, full: oneLine(line, 80) || 'No settings on the card.' }
873}
874
875/** The PR pill's theme key by state, never looked up in a plain object. */
876export const PILLS: ReadonlyMap<string, string> = new Map([
877 ['open', 'success'],
878 ['merged', 'merged'],
879 ['closed', 'error'],
880])
881
882/** The pill's theme key, or undefined for a state the Map does not hold. */
883export const pillColor = (state: unknown): string | undefined => (typeof state === 'string' ? PILLS.get(state) : undefined)
884
885/** A card's PR state as the pill draws it: `gh`'s answer, else the card's own,
886 * else open. The card's is passed on as stored; the Map decides its colour. */
887export const pillState = (gh: string | undefined, card: unknown): string => gh ?? (typeof card === 'string' ? card : 'open')
888
889/** The PR chip's link: GitHub's page for the card's number in the repository
890 * `gh` answered with, each held again to the shape `gh`'s answer is read to,
891 * so no card text reaches the URL. Anything else: no link. */
892export const prUrl = (repo: string, n: string): string | undefined =>
893 /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}$/.test(repo) && !['.', '..'].includes(repo.split('/')[1] ?? '') && /^[1-9][0-9]{0,6}$/.test(n) ? `https://github.com/${repo}/pull/${n}` : undefined
894
895/** A pull request row: the card it comes from, its place in the roster, its
896 * number, the state it is grouped by, its title and the dim line's parts. */
897export type PrRow = {
898 c: Record<string, unknown>
899 i: number
900 number: string
901 state: string
902 title: string
903 detail: { cardTitle: string; counts?: string; repo?: string; age?: string }
904}
905
906/** A stored card's PR number as text, or undefined: the card must be a record
907 * and `pr` text of 1 to 7 digits, by the roster module's own pattern. */
908export const prNumber = (c: unknown): string | undefined => (isRecord(c) && typeof c.pr === 'string' && PR_NUMBER.test(c.pr) ? c.pr : undefined)
909
910/** The pull requests the shown cards carry, grouped Open, Merged and Closed:
911 * one row per card, `gh`'s state when it answered for the number, else the
912 * card's, else open. With an answer a row has the PR's title, counts,
913 * repository and age; without one, the card's title alone. */
914export function prRows(cards: unknown, hidden: ReadonlySet<unknown>, answers: ReadonlyMap<number, GhPr>, now: number, moves?: Moves): { open: PrRow[]; merged: PrRow[]; closed: PrRow[] } {
915 const out = { open: [] as PrRow[], merged: [] as PrRow[], closed: [] as PrRow[] }
916 if (!Array.isArray(cards)) return out
917 cards.forEach((c, i) => {
918 const number = prNumber(c)
919 if (!isRecord(c) || number === undefined || shownLook(c, hidden, moves) === undefined) return
920 const answer = answers.get(Number(number))
921 const own = typeof c.prState === 'string' && (PR_STATES as readonly string[]).includes(c.prState) ? c.prState : 'open'
922 const state = answer?.state ?? own
923 const cardTitle = drawnTitle(String(c.title))
924 const detail: PrRow['detail'] = { cardTitle }
925 if (answer !== undefined) {
926 detail.counts = `+${num(answer.additions)} −${num(answer.deletions)}`
927 detail.repo = answer.repo
928 const age = ageText(answer.updatedAt, now)
929 if (age !== undefined) detail.age = age
930 }
931 const row: PrRow = { c, i, number, state, title: answer?.title ?? cardTitle, detail }
932 if (state === 'merged') out.merged.push(row)
933 else if (state === 'closed') out.closed.push(row)
934 else out.open.push(row)
935 })
936 return out
937}
938
939/** The hairline between cards: one rect in the rule class, across the width. */
940export function hairlineSvg(): BarImage {
941 return { source: `${svgOpen(9)}<rect class="rule" x="0" y="4" width="100%" height="1"/></svg>`, alt: 'divider', height: 9 }
942}
943
944// A PR pill's class suffix and mark by state, read only through this Map.
945const PILL_LOOKS: ReadonlyMap<string, { cls: string; mark: string }> = new Map([
946 ['open', { cls: 'open', mark: '⇄' }],
947 ['merged', { cls: 'merged', mark: '⎇' }],
948 ['closed', { cls: 'closed', mark: '⊘' }],
949])
950const PILL_HEIGHT = 18
951
952/** A PR pill as Desktop draws its own: a rounded tint of the state, its mark
953 * and `#` with the number in the state's ink, 18 px high and as wide as its
954 * text, by an estimate of the font's widths. Undefined for a number that is
955 * not 1 to 7 digits or a state the Map does not hold, `constructor` included. */
956export function pillSvg(n: string, state: string): (BarImage & { width: number }) | undefined {
957 const look = PILL_LOOKS.get(state)
958 if (look === undefined || !/^[0-9]{1,7}$/.test(n)) return undefined
959 const width = Math.round(36 + 6.3 * n.length)
960 const source =
961 `<svg xmlns="${XMLNS}" width="${num(width)}" height="${num(PILL_HEIGHT)}"><style>${STYLE}</style>` +
962 `<rect class="tint-${look.cls}" x="0" y="0" width="100%" height="${num(PILL_HEIGHT)}" rx="${num(PILL_HEIGHT / 2)}"/>` +
963 `<text class="ink-${look.cls}" x="7" y="12.5">${look.mark}</text>` +
964 `<text class="ink-${look.cls}" x="22" y="12.5">#${svgText(n, 8)}</text></svg>`
965 return { source, alt: `#${n}, ${state}`, height: PILL_HEIGHT, width }
966}
967
968/** A card's title as drawn and as a report's sender is kept: cleaned and cut
969 * to 80. A report belongs to the card whose drawn title is its sender, both
970 * for the card's report line and for the toggle's count. */
971export const drawnTitle = (title: string): string => oneLine(title, 80)
972
973/** The reports since the pane opened whose sender is one of `titles`, matched
974 * by `drawnTitle`. Every report counts, not one per card. An inbox entry of the wrong shape
975 * counts nothing, and no shape throws. */
976export function reportCount(titles: readonly string[], inbox: unknown): number {
977 if (!Array.isArray(inbox)) return 0
978 const drawn = new Set(titles.map(drawnTitle))
979 return inbox.filter(r => isRecord(r) && typeof r.from === 'string' && drawn.has(r.from)).length
980}
981
982/** The count beside "Waiting on you": the cards that need the owner, plus the
983 * to-dos that are neither done nor ticking. */
984export function waitingCount(needsYou: number, todos: readonly { id: string }[], done: unknown, ticking: unknown): number {
985 const out = doneOrTicking(done, ticking)
986 return needsYou + todos.filter(t => !out.has(t.id)).length
987}
988
989/** The to-do ids that count as done: those in the done list or ticking. The
990 * Waiting on you count and the to-do bar both read this one set. */
991function doneOrTicking(done: unknown, ticking: unknown): Set<string> {
992 return new Set([...idsFrom(done), ...ticksFrom(ticking).map(p => p.name)])
993}
994
995// --- The status strip and the to-do bar ---------------------------------------
996//
997// Under the top row: a strip with one segment per status, its legend,
998// and a bar of the to-dos done. Both are drawn from counts alone. Each builder
999// takes the stored roster and lists as they are, reads a card only through
1000// the status Map and a to-do only by its id, and writes only numbers, fixed
1001// words and fixed class names: no title, to-do text, report or usage text
1002// reaches either image or its alt.
1003
1004/** The strip's cells on the terminal. */
1005export const STRIP_CELLS = 32
1006/** The to-do bar's cells on the terminal. */
1007export const TODO_CELLS = 20
1008
1009const STRIP_HEIGHT = 8
1010const TODO_HEIGHT = 12
1011
1012// A count as the drawing takes it: a finite number above 0, floored, else 0.
1013const whole = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0)
1014
1015/** One status's count among the shown cards. */
1016export type StatusCount = { look: StatusLook; count: number }
1017
1018/** The shown cards' count per status, in the Map's order, with no entry for a
1019 * status with no cards. Shown is as `groupCards` has it: a record, not
1020 * dismissed, and one of the four statuses, by the rule groupCards uses, so
1021 * the strip, its legend, the heading and the groups count the same cards. */
1022export function statusCounts(cards: unknown, hidden: ReadonlySet<unknown>, moves?: Moves): StatusCount[] {
1023 const counts = new Map<StatusLook, number>()
1024 if (Array.isArray(cards)) {
1025 for (const c of cards) {
1026 const look = shownLook(c, hidden, moves)
1027 if (look !== undefined) counts.set(look, (counts.get(look) ?? 0) + 1)
1028 }
1029 }
1030 return [...STATUS.values()].flatMap(look => {
1031 const count = counts.get(look) ?? 0
1032 return count > 0 ? [{ look, count }] : []
1033 })
1034}
1035
1036/** The terminal strip's run lengths, one per count, in the same order. The
1037 * cells go by largest remainder of each count's share, a tie to the earlier
1038 * count; then each count above 0 that got no cell takes one from the
1039 * longest run, the earliest of equal ones. A count that is not a
1040 * finite number above 0 is 0. The runs sum to exactly `cells` whenever a
1041 * count is above 0; with none, or a cell count that is not a positive whole
1042 * number, every run is 0 and there is nothing to draw. Never throws. */
1043export function stripRuns(counts: readonly unknown[], cells: number): number[] {
1044 const c = counts.map(whole)
1045 const total = c.reduce((s, n) => s + n, 0)
1046 const n = Number.isInteger(cells) && cells > 0 ? cells : 0
1047 if (total === 0 || n === 0) return c.map(() => 0)
1048 const quota = c.map(v => (v / total) * n)
1049 const runs = quota.map(Math.floor)
1050 const remainder = quota.map((q, i) => q - (runs[i] ?? 0))
1051 let left = n - runs.reduce((s, r) => s + r, 0)
1052 const byRemainder = remainder.map((_, i) => i).sort((a, b) => (remainder[b] ?? 0) - (remainder[a] ?? 0) || a - b)
1053 for (const i of byRemainder) {
1054 if (left <= 0) break
1055 runs[i] = (runs[i] ?? 0) + 1
1056 left -= 1
1057 }
1058 c.forEach((v, i) => {
1059 if (v === 0 || (runs[i] ?? 0) > 0) return
1060 const longest = runs.reduce((best, r, j) => (r > (runs[best] ?? 0) ? j : best), 0)
1061 // A run of one cell gives none away: with more counts than cells, the
1062 // later ones draw nothing rather than break the sum.
1063 if ((runs[longest] ?? 0) <= 1) return
1064 runs[longest] = (runs[longest] ?? 0) - 1
1065 runs[i] = 1
1066 })
1067 return runs
1068}
1069
1070/** An SVG image of fixed words, numbers and class names, and its alt text. */
1071export type BarImage = { source: string; alt: string; height: number }
1072
1073const svgOpen = (height: number) => `<svg xmlns="${XMLNS}" width="100%" height="${num(height)}"><style>${STYLE}</style>`
1074
1075/** The strip as an SVG: one segment per count above 0, in the order given,
1076 * each as wide as its share, under one rounded clip, id `st`. Each segment
1077 * but the last sits in a nested <svg> with its rect moved 2 px left, so a
1078 * 2 px gap follows it at any width. A count that is not a finite number
1079 * above 0 draws nothing. The alt text is the legend's words and numbers. */
1080export function stripSvg(entries: readonly StatusCount[]): BarImage {
1081 const shown = entries.map(e => ({ look: e.look, count: whole(e.count) })).filter(e => e.count > 0)
1082 const total = shown.reduce((s, e) => s + e.count, 0)
1083 const h = num(STRIP_HEIGHT)
1084 let x = 0
1085 const segments = shown.map((e, i) => {
1086 const w = (e.count / total) * 100
1087 const at = x
1088 x += w
1089 return i < shown.length - 1
1090 ? `<svg x="${pct(at)}" width="${pct(w)}" height="${h}"><rect class="${e.look.cls}" width="100%" height="${h}" transform="translate(-2 0)"/></svg>`
1091 : `<rect class="${e.look.cls}" x="${pct(at)}" y="0" width="${pct(w)}" height="${h}"/>`
1092 })
1093 const source =
1094 svgOpen(STRIP_HEIGHT) +
1095 `<clipPath id="st"><rect x="0" y="0" width="100%" height="${h}" rx="${num(STRIP_HEIGHT / 2)}"/></clipPath>` +
1096 `<g clip-path="url(#st)">${segments.join('')}</g></svg>`
1097 const alt = shown.length === 0 ? 'none' : shown.map(e => `${e.count} ${e.look.word}`).join(', ')
1098 return { source, alt: `Status: ${alt}`, height: STRIP_HEIGHT }
1099}
1100
1101/** What the strip draws: the shown cards' total, the legend's entries, the
1102 * terminal's runs of `█` in each status's theme colour, summing to 32, and
1103 * the SVG. Undefined when no shown card has one of the four statuses. */
1104export type StripView = {
1105 total: number
1106 legend: { text: string; color: string }[]
1107 runs: { text: string; color: string }[]
1108 svg: BarImage
1109}
1110
1111export function statusStrip(cards: unknown, hidden: ReadonlySet<unknown>, moves?: Moves): StripView | undefined {
1112 const counts = statusCounts(cards, hidden, moves)
1113 const total = counts.reduce((s, e) => s + e.count, 0)
1114 if (total === 0) return undefined
1115 const runs = stripRuns(
1116 counts.map(e => e.count),
1117 STRIP_CELLS,
1118 )
1119 return {
1120 total,
1121 legend: counts.map(e => ({ text: `${e.look.glyph} ${e.count} ${e.look.word}`, color: e.look.color })),
1122 runs: counts.flatMap((e, i) => ((runs[i] ?? 0) > 0 ? [{ text: '█'.repeat(runs[i] ?? 0), color: e.look.color }] : [])),
1123 svg: stripSvg(counts),
1124 }
1125}
1126
1127/** The roster's to-dos and how many of them are done: a to-do counts as done
1128 * when its id is in the done list or ticking, once whichever holds it, so
1129 * the bar agrees with the "Waiting on you" count. Lists of the wrong shape
1130 * count as empty, and a to-do that is not a record with a text id counts
1131 * nowhere. */
1132export function todoCounts(todos: unknown, done: unknown, ticking: unknown): { done: number; total: number } {
1133 const list = Array.isArray(todos) ? todos.filter((t): t is { id: string } => isRecord(t) && typeof t.id === 'string') : []
1134 const out = doneOrTicking(done, ticking)
1135 return { done: list.filter(t => out.has(t.id)).length, total: list.length }
1136}
1137
1138/** The to-do bar as an SVG: a rounded track and a rounded green fill, class
1139 * `done`, with no clip and no id. A count that is not a finite number above
1140 * 0 is 0, and done past the total is the total. The fill is never narrower
1141 * than 6 px, as the usage bars' is. The alt text is `To-dos N of M done`. */
1142export function todoSvg(done: number, total: number): BarImage {
1143 const m = whole(total)
1144 const n = Math.min(whole(done), m)
1145 const fraction = m > 0 ? n / m : 0
1146 const rect = (cls: string, width: string) => `<rect class="${cls}" x="0" y="3" width="${width}" height="6" rx="3"/>`
1147 const source =
1148 svgOpen(TODO_HEIGHT) +
1149 rect('track', '100%') +
1150 (fraction > 0 ? rect('done', '6') + rect('done', pct(fraction * 100)) : '') +
1151 '</svg>'
1152 return { source, alt: `To-dos ${n} of ${m} done`, height: TODO_HEIGHT }
1153}
1154
1155/** What the to-do bar draws: "N of M done", the terminal's 20 eighth-block
1156 * cells, and the SVG. Undefined when the roster has no to-dos. */
1157export function todoBar(
1158 todos: unknown,
1159 done: unknown,
1160 ticking: unknown,
1161): { text: string; cells: string; svg: BarImage } | undefined {
1162 const c = todoCounts(todos, done, ticking)
1163 if (c.total === 0) return undefined
1164 return { text: `${c.done} of ${c.total} done`, cells: eighthBar(c.done / c.total, TODO_CELLS), svg: todoSvg(c.done, c.total) }
1165}
1166
1167// --- Cache warmth ----------------------------------------------------------
1168//
1169// A session's prompt cache lasts for the window its last cache write asked
1170// for, one hour or five minutes, from its last model call. The ◆ line says
1171// how long the session has been idle, when it goes cold, and how big its
1172// context is. All of it comes from the session's own transcript, text another
1173// session wrote, so every row is checked for shape and size before it counts.
1174
1175/** The engine refuses to read a file over 4 MiB, so the pane does not try. */
1176export const MAX_TRANSCRIPT_BYTES = 4 * 1024 * 1024
1177/** From this many context tokens a cold cache costs enough to nudge about. */
1178export const NUDGE_TOKENS = 100000
1179
1180const MIN_MS = 60000
1181const HOUR_MS = 60 * MIN_MS
1182const SHORT_MS = 5 * MIN_MS
1183const AMBER_MS = 15 * MIN_MS
1184// A row may claim a time up to this much past the file's modified time, for
1185// the clock's slack; a later one claims to be newer than the file it is in.
1186const SLACK_MS = 2 * MIN_MS
1187const MAX_COUNT = 10000000
1188// The most entries a stored list of warmth records or live entries keeps.
1189const MAX_ENTRIES = 50
1190/** The cap on a card's title and on a session's name as kept in the live state. */
1191export const MAX_NAME = 300
1192const MAX_LIVE = 40
1193
1194/** The last real model call in a transcript: its time, its context tokens,
1195 * and its cache window when a call that wrote cache says it. */
1196export type LastCall = { at: number; tokens: number; windowMs?: number }
1197
1198// The time Claude Code writes, ISO in UTC: an offset is refused.
1199const UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/
1200brigade/roster.ts 842 lines1import type { Card, Pair, PrState, Roster, Status, Todo } from './types'
2
3// What the Brigade pane reads from outside itself, checked before it is drawn
4// or used: the roster, the engine's session files, the transcript
5// paths the engine reports and the reports other sessions send. Every one is
6// text another process wrote, so each is held to a shape, cut to a length and
7// shown as text only. Nothing here runs, and nothing here builds a command or
8// a path from roster text.
9//
10// The roster has two users, and both take their rules from here so the two
11// cannot drift: the pane, which reads the file, and the set_roster tool, which
12// writes it. The shape check, the byte cap and the decision whether a roster
13// path may be read or written are each one function below.
14
15export const STATUSES: readonly Status[] = ['working', 'needs-you', 'done', 'stopped']
16
17// The caps a roster is held to. A roster over them is refused with an error in
18// the pane rather than drawn in part.
19const MAX_CARDS = 50
20const MAX_TODOS = 50
21const MAX_TITLE = 80
22/** The cap on a card's or to-do's text field; the pane draws a wrapped field
23 * whole up to it. */
24export const MAX_TEXT = 300
25const MAX_ID = 100
26
27// The engine's session ids, and so the roster files' names.
28export const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
29
30// C0 and C1 controls, and the characters that reorder or hide text: every
31// default-ignorable code point (the zero-width ones, the variation selectors,
32// the tag block, the soft hyphen and the rest), and the bidi marks,
33// embeddings, overrides and isolates, some of which are not in that set.
34const CONTROL = /[\u{0}-\u{1F}\u{7F}-\u{9F}\u{2028}\u{2029}]/gu
35const HIDDEN = /[\p{Default_Ignorable_Code_Point}\u{61C}\u{200E}\u{200F}\u{202A}-\u{202E}\u{2066}-\u{2069}]/gu
36
37/** Text made safe to draw on one line: controls become spaces, hidden
38 * characters go, runs of space fold, and it is cut to `max` with an ellipsis. */
39export function oneLine(text: string, max: number): string {
40 const flat = text.replace(CONTROL, ' ').replace(HIDDEN, '').replace(/\s+/g, ' ').trim()
41 const chars = [...flat]
42 return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : flat
43}
44
45type Checked<T> = { value: T } | { error: string }
46
47const isRecord = (v: unknown): v is Record<string, unknown> =>
48 typeof v === 'object' && v !== null && !Array.isArray(v)
49
50// Own keys only, and only the ones named: a key the shape does not know is a
51// typo or a field nobody reads, and either way the file is refused.
52function fields(where: string, v: unknown, allowed: readonly string[]): Checked<Record<string, unknown>> {
53 if (!isRecord(v)) return { error: `${where} is not an object` }
54 const extra = Object.keys(v).filter(k => !allowed.includes(k))
55 if (extra.length > 0) return { error: `${where} has a field the roster does not use: ${oneLine(extra[0] ?? '', 40)}` }
56 return { value: v }
57}
58
59function text(where: string, v: unknown, max: number, required: boolean): Checked<string | undefined> {
60 if (v === undefined && !required) return { value: undefined }
61 if (typeof v !== 'string') return { error: `${where} is not text` }
62 if (required && v.trim() === '') return { error: `${where} is empty` }
63 if ([...v].length > max) return { error: `${where} is over ${max} characters` }
64 return { value: v }
65}
66
67/** Where a roster came from. The file may hold a card's `since`; the tool's
68 * input may not, since the tool stamps it. */
69export type Source = 'file' | 'tool'
70
71/** The three states a card's PR can be in, as the card keeps them. */
72export const PR_STATES: readonly PrState[] = ['open', 'merged', 'closed']
73
74/** A PR number as text: 1 to 7 digits. The tool's schema and the view module take this one pattern. */
75export const PR_NUMBER = /^[0-9]{1,7}$/
76
77/** Whether a value is a whole number from 0 to 2^53 - 1. */
78const isWhole = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0
79
80function card(i: number, v: unknown, source: Source): Checked<Card> {
81 const where = `card ${i + 1}`
82 if (source === 'tool' && isRecord(v) && Object.hasOwn(v, 'since')) {
83 return { error: `${where} since is stamped by the pane, not sent by the tool` }
84 }
85 const f = fields(where, v, ['title', 'work', 'phase', 'settings', 'status', 'desktopId', 'bgId', 'url', 'pr', 'prState', 'since'])
86 if ('error' in f) return f
87 const o = f.value
88 const title = text(`${where} title`, o.title, MAX_TITLE, true)
89 if ('error' in title) return title
90 const out: Card = { title: title.value ?? '', work: '', phase: '', settings: '', status: 'working' }
91 for (const k of ['work', 'phase', 'settings'] as const) {
92 const t = text(`${where} ${k}`, o[k], MAX_TEXT, false)
93 if ('error' in t) return t
94 out[k] = t.value ?? ''
95 }
96 if (typeof o.status !== 'string' || !(STATUSES as readonly string[]).includes(o.status)) {
97 return { error: `${where} status is not one of ${STATUSES.join(', ')}` }
98 }
99 out.status = o.status as Status
100 for (const k of ['desktopId', 'bgId', 'url'] as const) {
101 const t = text(`${where} ${k}`, o[k], MAX_ID, false)
102 if ('error' in t) return t
103 if (t.value !== undefined) out[k] = t.value
104 }
105 if (o.pr !== undefined) {
106 if (typeof o.pr !== 'string' || !PR_NUMBER.test(o.pr)) return { error: `${where} pr is not 1 to 7 digits` }
107 out.pr = o.pr
108 }
109 if (o.prState !== undefined) {
110 if (typeof o.prState !== 'string' || !(PR_STATES as readonly string[]).includes(o.prState)) {
111 return { error: `${where} prState is not one of ${PR_STATES.join(', ')}` }
112 }
113 out.prState = o.prState as PrState
114 }
115 if (o.since !== undefined) {
116 if (!isWhole(o.since)) return { error: `${where} since is not a whole number from 0 to ${Number.MAX_SAFE_INTEGER}` }
117 out.since = o.since
118 }
119 return { value: out }
120}
121
122function todo(i: number, v: unknown): Checked<Todo> {
123 const where = `to-do ${i + 1}`
124 const f = fields(where, v, ['id', 'text', 'session'])
125 if ('error' in f) return f
126 const id = text(`${where} id`, f.value.id, 40, true)
127 if ('error' in id) return id
128 const body = text(`${where} text`, f.value.text, MAX_TEXT, true)
129 if ('error' in body) return body
130 const session = text(`${where} session`, f.value.session, MAX_TITLE, false)
131 if ('error' in session) return session
132 const out: Todo = { id: id.value ?? '', text: body.value ?? '' }
133 if (session.value !== undefined) out.session = session.value
134 return { value: out }
135}
136
137/** The roster's text, checked: `{ cards, todos }` with every field a string
138 * of its length, the status from the fixed set, no title twice and no to-do
139 * id twice. The pane reads a missing list as empty. `strict` requires both
140 * lists, as the writer does of a file it would overwrite: `{}` is then no
141 * roster, so a hard link to some other JSON file is not taken for one. */
142export function checkRoster(raw: string, strict = false, source: Source = 'file'): Checked<Roster> {
143 let parsed: unknown
144 try {
145 parsed = JSON.parse(raw)
146 } catch {
147 return { error: 'the roster is not JSON' }
148 }
149 const f = fields('the roster', parsed, ['cards', 'todos'])
150 if ('error' in f) return f
151 if (strict) {
152 for (const k of ['cards', 'todos'] as const) {
153 if (!Object.hasOwn(f.value, k)) return { error: `the roster has no "${k}" list` }
154 }
155 }
156 const cards = f.value.cards ?? []
157 const todos = f.value.todos ?? []
158 if (!Array.isArray(cards)) return { error: 'the roster\'s "cards" is not a list' }
159 if (!Array.isArray(todos)) return { error: 'the roster\'s "todos" is not a list' }
160 if (cards.length > MAX_CARDS) return { error: `the roster has over ${MAX_CARDS} cards` }
161 if (todos.length > MAX_TODOS) return { error: `the roster has over ${MAX_TODOS} to-dos` }
162 const out: Roster = { cards: [], todos: [] }
163 const titles = new Set<string>()
164 for (const [i, v] of cards.entries()) {
165 const c = card(i, v, source)
166 if ('error' in c) return c
167 // Compared as drawn, so two titles that differ only in a hidden
168 // character cannot pose as one card.
169 const drawn = oneLine(c.value.title, MAX_TITLE)
170 if (drawn === '') return { error: `card ${i + 1} title is empty once hidden characters go` }
171 if (titles.has(drawn)) return { error: `card ${i + 1} repeats the title of an earlier card` }
172 titles.add(drawn)
173 out.cards.push(c.value)
174 }
175 const ids = new Set<string>()
176 for (const [i, v] of todos.entries()) {
177 const t = todo(i, v)
178 if ('error' in t) return t
179 if (ids.has(t.value.id)) return { error: `to-do ${i + 1} repeats the id of an earlier to-do` }
180 ids.add(t.value.id)
181 out.todos.push(t.value)
182 }
183 return { value: out }
184}
185
186/** The cap on a roster file, in bytes: the pane reads no larger file, and the
187 * writer saves none. */
188export const MAX_ROSTER_BYTES = 256 * 1024
189
190/** A checked roster as the text the writer saves, measured in UTF-8 bytes
191 * against the cap: what is measured is what is written. */
192export function serialize(roster: Roster): Checked<string> {
193 const text = JSON.stringify(roster)
194 const bytes = new TextEncoder().encode(text).length
195 return bytes > MAX_ROSTER_BYTES ? { error: `the roster is ${bytes} bytes, over the cap of ${MAX_ROSTER_BYTES}` } : { value: text }
196}
197
198// --- the card's age ------------------------------------------------------------
199//
200// A card's `since` is when it entered its current status and phase. The
201// set_roster tool stamps it from the engine clock, inside its queue, and the
202// model never sends one. A `since` written to the file by anything else is
203// drawn as written.
204
205/** How far ahead of the clock a kept or drawn time may be: 2 minutes. */
206export const AHEAD_MS = 120000
207
208/** The cards with `since` set: kept from the previous roster's card of the
209 * same drawn title, status and phase when that value passes the file check
210 * and is at most 2 minutes ahead of the clock, else the clock's answer. A
211 * clock answer that is not a whole number from 0 to 2^53 - 1 refuses. */
212export function stampSince(previous: Roster | undefined, cards: readonly Card[], clock: unknown): Checked<Card[]> {
213 if (!isWhole(clock)) return { error: 'clock: the engine clock gave no whole number of milliseconds' }
214 const before = new Map<string, Card>()
215 for (const c of previous?.cards ?? []) before.set(oneLine(c.title, MAX_TITLE), c)
216 return {
217 value: cards.map(c => {
218 const was = before.get(oneLine(c.title, MAX_TITLE))
219 // The phase is compared as the pane draws it, so a hidden character or a trailing space is no change.
220 const keep = was !== undefined && was.status === c.status && oneLine(was.phase, 160) === oneLine(c.phase, 160) && isWhole(was.since) && was.since <= clock + AHEAD_MS
221 return { ...c, since: keep ? was.since : clock }
222 }),
223 }
224}
225
226// --- the gh answer ---------------------------------------------------------------
227//
228// The pane asks `gh pr list` for the brigade's PRs. The output is text another
229// process wrote, so it is read as untrusted: held to a size, a count and a
230// shape per entry, and kept in a Map keyed by number.
231
232/** The cap on `gh`'s output, in UTF-8 bytes. */
233export const MAX_GH_BYTES = 1024 * 1024
234const MAX_GH_ENTRIES = 100
235const MAX_GH_TITLE = 1000
236const MAX_COUNT = 100000000
237const MAX_PR = 9999999
238
239/** The one argument list the pane runs; no roster text reaches it. */
240export const GH_ARGV: readonly string[] = [
241 'gh',
242 'pr',
243 'list',
244 '--state',
245 'all',
246 '--limit',
247 '100',
248 '--json',
249 'number,title,state,additions,deletions,updatedAt,url,isCrossRepository',
250]
251
252/** One PR `gh` answered for, after its checks. `updatedAt` is epoch ms. */
253export type GhPr = { number: number; title: string; state: PrState; additions: number; deletions: number; updatedAt: number; repo: string }
254
255const GH_STATES: ReadonlyMap<string, PrState> = new Map([
256 ['OPEN', 'open'],
257 ['MERGED', 'merged'],
258 ['CLOSED', 'closed'],
259])
260const GH_URL = /^https:\/\/github\.com\/([A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100})\/pull\/([0-9]{1,7})$/
261const GH_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/
262
263const wholeBetween = (v: unknown, min: number, max: number): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max
264
265/** The PRs `gh pr list` printed, by number. Only an entry of the stated shape
266 * counts, among the first 100; a fork's PR counts as no answer. Output over
267 * 1 MiB, or no JSON list, is an error whose words carry none of the output. */
268export function parsePrList(stdout: string): Checked<Map<number, GhPr>> {
269 if (new TextEncoder().encode(stdout).length > MAX_GH_BYTES) return { error: 'gh printed more than the pane reads' }
270 let parsed: unknown
271 try {
272 parsed = JSON.parse(stdout)
273 } catch {
274 return { error: 'gh printed no JSON' }
275 }
276 if (!Array.isArray(parsed)) return { error: 'gh printed no list' }
277 const out = new Map<number, GhPr>()
278 for (const e of parsed.slice(0, MAX_GH_ENTRIES)) {
279 if (!isRecord(e)) continue
280 const state = typeof e.state === 'string' ? GH_STATES.get(e.state) : undefined
281 const url = typeof e.url === 'string' ? GH_URL.exec(e.url) : null
282 if (
283 !wholeBetween(e.number, 1, MAX_PR) ||
284 typeof e.title !== 'string' ||
285 [...e.title].length > MAX_GH_TITLE ||
286 state === undefined ||
287 !wholeBetween(e.additions, 0, MAX_COUNT) ||
288 !wholeBetween(e.deletions, 0, MAX_COUNT) ||
289 typeof e.updatedAt !== 'string' ||
290 !GH_TIME.test(e.updatedAt) ||
291 url === null ||
292 Number(url[2]) !== e.number ||
293 e.isCrossRepository !== false
294 ) {
295 continue
296 }
297 const updatedAt = Date.parse(e.updatedAt)
298 if (!Number.isFinite(updatedAt) || out.has(e.number)) continue
299 out.set(e.number, { number: e.number, title: oneLine(e.title, 80), state, additions: e.additions, deletions: e.deletions, updatedAt, repo: url[1] ?? '' })
300 }
301 return { value: out }
302}
303
304// --- the roster path ---------------------------------------------------------
305//
306// Whether a roster path may be read or written, decided from `stat` answers
307// alone. The engine offers no write that refuses a link, and a write follows
308// one: through a broken file link it creates the link's target, and through a
309// hard link it replaces the other file's text. So before each write, and each
310// read, every folder from the config folder down is looked at, then the file.
311//
312// The answers come from the caller, so the rule runs the same against the
313// engine and against recorded answers in a test. A `stat` the engine rejects
314// reaches a mod as a message alone, with no error code: a missing path's ends
315// "failed: ENOENT" (measured on 2.1.292), and only that one means missing.
316
317/** What `$.fs.stat(path, { resolve: true })` answered, as far as the rule
318 * reads it. `isLink` is the path's own; `kind` and `realPath` are where it
319 * leads, `realPath` absent when it leads nowhere. */
320export type StatFound = { kind: 'file' | 'dir' | 'other'; size: number; isLink: boolean; realPath?: string }
321
322/** One `stat`: found, missing, or refused for any other reason. */
323export type StatAnswer = { found: StatFound } | { missing: true } | { failed: string }
324
325/** A rejected `stat`'s message, sorted: missing only for ENOENT. */
326export function statRejection(message: string): StatAnswer {
327 return /(?:^|[\s:])ENOENT$/.test(message.trim()) ? { missing: true } : { failed: oneLine(message, 200) }
328}
329
330/** Where the file may go: `existing` is the file there now, which a writer
331 * must still find to be its own kind, a roster or a summary, before it
332 * overwrites it. */
333export type Placed = { file: string; existing?: { size: number } } | { refused: string }
334
335// The folders below the config folder, in order, for each kind of file the
336// mod writes: the lead's roster, and each session's usage summary in a folder
337// apart from the rosters. `plugins` is the engine's own and must be there;
338// the mod may create the rest.
339type Place = 'roster' | 'summary'
340const FOLDERS = (plugin: string, place: Place) =>
341 place === 'roster' ? ['plugins', 'data', plugin, 'brigade'] : ['plugins', 'data', plugin, 'brigade', 'usage']
342
343/** A path as the real-path compare reads it: one separator, no trailing one,
344 * and case folded where the file system ignores it. The roster path rule and
345 * the transcript finder's place check both compare by it. */
346export const pathKey = (path: string, fold: boolean): string => {
347 const flat = path.replace(/[\\/]+/g, '/').replace(/(.)\/$/, '$1')
348 return fold ? flat.toLowerCase() : flat
349}
350
351/** Whether the file system under this path ignores case: Windows' and,
352 * by its default home and volumes, macOS'. Elsewhere the compare is exact,
353 * which can only refuse more. */
354export function foldsCase(path: string): boolean {
355 return /^(?:[A-Za-z]:[\\/]|[\\/]{2})/.test(path) || /^\/(?:Users|Volumes)\//.test(path)
356}
357
358/** Decides whether this session's roster file under the config folder may be
359 * read or written, asking `stat` (resolving) of each folder on the way and
360 * then of the file.
361 *
362 * Refused: a session id or data id not of their shape; a config folder that
363 * does not resolve; `plugins` missing; any folder that is a link, broken or
364 * not, or is not a folder; any `stat` that fails other than as missing, or
365 * finds a path with no real path; any folder whose real path is not the
366 * config folder's real path joined with the same names, which is the
367 * decisive control, since only junctions and file links were measured for
368 * `isLink`; and a file that is a link, is not a plain file, or lands
369 * anywhere but in the checked folder. A missing folder below `plugins` ends
370 * the walk: the write creates it and everything below it. */
371export function placeRoster(
372 config: string,
373 plugin: string,
374 sessionId: string,
375 stat: (path: string) => Promise<StatAnswer>,
376): Promise<Placed> {
377 return placeFile(config, plugin, sessionId, stat, 'roster')
378}
379
380/** Decides whether this session's usage summary file under the config
381 * folder may be read or written: `placeRoster`'s rule, word for word, with
382 * the walk going one folder further, into `usage`, so a summary never lands
383 * where a roster does. */
384export function placeSummary(
385 config: string,
386 plugin: string,
387 sessionId: string,
388 stat: (path: string) => Promise<StatAnswer>,
389): Promise<Placed> {
390 return placeFile(config, plugin, sessionId, stat, 'summary')
391}
392
393async function placeFile(
394 config: string,
395 plugin: string,
396 sessionId: string,
397 stat: (path: string) => Promise<StatAnswer>,
398 place: Place,
399): Promise<Placed> {
400 if (!SESSION_ID.test(sessionId)) return { refused: 'path: the session id is not the engine\'s shape' }
401 if (!/^[A-Za-z0-9_-]{1,200}$/.test(plugin)) return { refused: 'path: the plugin\'s data id is not of its shape' }
402 const sep = sepOf(config)
403 const fold = foldsCase(config)
404 const top = await stat(config)
405 if (!('found' in top) || top.found.kind !== 'dir' || top.found.realPath === undefined) {
406 return { refused: 'path: the config folder does not resolve to a folder' }
407 }
408 const real = pathKey(top.found.realPath, fold)
409 let at = config
410 let expected = real
411 const folders = FOLDERS(plugin, place)
412 for (const name of folders) {
413 at = `${at}${sep}${name}`
414 expected = `${expected}/${fold ? name.toLowerCase() : name}`
415 const s = await stat(at)
416 if ('missing' in s) {
417 if (name === 'plugins') return { refused: 'path: the config folder has no plugins folder' }
418 return { file: `${config}${sep}${folders.join(sep)}${sep}${sessionId}.json` }
419 }
420 if ('failed' in s) return { refused: `path: ${name} could not be read (${s.failed})` }
421 if (s.found.isLink) return { refused: `link: ${name} is a link` }
422 if (s.found.kind !== 'dir') return { refused: `path: ${name} is not a folder` }
423 if (s.found.realPath === undefined || pathKey(s.found.realPath, fold) !== expected) {
424 return { refused: `link: ${name} does not lead where its name says` }
425 }
426 }
427 const file = `${at}${sep}${sessionId}.json`
428 const s = await stat(file)
429 if ('missing' in s) return { file }
430 if ('failed' in s) return { refused: `path: the ${place} file could not be read (${s.failed})` }
431 if (s.found.isLink) return { refused: `link: the ${place} file is a link` }
432 if (s.found.kind !== 'file') return { refused: `path: the ${place} path is not a plain file` }
433 if (s.found.realPath === undefined || pathKey(s.found.realPath, fold) !== `${expected}/${fold ? `${sessionId}.json`.toLowerCase() : `${sessionId}.json`}`) {
434 return { refused: `link: the ${place} file does not lead where its name says` }
435 }
436 return { file, existing: { size: s.found.size } }
437}
438
439// The config folder and the marketplace from where the plugin was installed:
440// the engine keeps an installed plugin under
441// <config>/plugins/cache/<marketplace>/... or reads it from
442// <config>/plugins/marketplaces/<marketplace>. The last such segment wins, so
443// a config folder whose own path holds the words still resolves.
444const INSTALLED = /^(.+)[\\/]plugins[\\/](?:cache|marketplaces)[\\/]([^\\/]+)(?:[\\/]|$)/
445
446/** The config folder the plugin's own location names, or undefined. */
447export function configFromRoot(root: string): string | undefined {
448 return INSTALLED.exec(root)?.[1]
449}
450
451/** The marketplace the plugin's own location names, or undefined: a plugin
452 * loaded from a folder of its own (`--plugin-dir`) has none. */
453export function marketplaceFromRoot(root: string): string | undefined {
454 return INSTALLED.exec(root)?.[2]
455}
456
457/** The plugin's data folder id, by the plugin-manifest reference's rule: the
458 * identifier `<name>@<marketplace>`, or `<name>@inline` for a plugin loaded
459 * from a folder, with every character but a letter, digit, `_` or `-` made
460 * `-`. */
461export function dataId(name: string, marketplace: string | undefined): string {
462 return `${name}@${marketplace ?? 'inline'}`.replace(/[^A-Za-z0-9_-]/g, '-')
463}
464
465/** The plugin's data folder under a config folder, built from the config
466 * folder alone: `CLAUDE_PLUGIN_DATA` is not read, since a mod's environment
467 * usually lacks it and another plugin can set it. */
468export function dataFolder(config: string, id: string): string {
469 const sep = sepOf(config)
470 return `${config}${sep}plugins${sep}data${sep}${id}`
471}
472
473/** The config folder above Desktop's synced install of this plugin:
474 * <config>/plugins/synced/<one folder>/<name>, or the name with `~g` and
475 * digits after it (Desktop keeps such a copy beside it; seen on Windows). Exactly one folder sits between `synced` and the plugin's
476 * folder, which is the last part of the root. It names a config folder only,
477 * never a marketplace. */
478export function configFromSynced(root: string, name: string): string | undefined {
479 const m = /^(.+)[\\/]plugins[\\/]synced[\\/][^\\/]+[\\/]([^\\/]+)$/.exec(root)
480 if (m === null) return undefined
481 const tail = m[2].startsWith(`${name}~g`) ? m[2].slice(name.length + 2) : undefined
482 return m[2] === name || (tail !== undefined && /^\d+$/.test(tail)) ? m[1] : undefined
483}
484
485/** The config folder and the plugin's data id for this session, by one rule
486 * the roster and the usage summary writer share, in order: the config folder
487 * from where the plugin was installed; else from the transcript path the
488 * engine reported at a session's start, whatever session that record holds
489 * (a clear does not change the config folder), when its id is of the
490 * engine's shape, both fields are text and the transcript's file name is its
491 * own id; else from Desktop's synced install folder. `config` is undefined
492 * with none. The data id never takes a marketplace from the synced form. */
493export function dataPlace(root: string, name: string, start: { sessionId: string; transcript: string }): { config: string | undefined; plugin: string } {
494 const config =
495 configFromRoot(root) ??
496 (typeof start.sessionId === 'string' && typeof start.transcript === 'string' ? configFromTranscript(start.transcript, start.sessionId) : undefined) ??
497 configFromSynced(root, name)
498 return { config, plugin: dataId(name, marketplaceFromRoot(root)) }
499}
500
501/** The config folder above the engine's transcript path for the given session id:
502 * <config>/projects/<folder>/<session id>.jsonl, or undefined. */
503export function configFromTranscript(transcript: string, sessionId: string): string | undefined {
504 if (!SESSION_ID.test(sessionId)) return undefined
505 const m = /^(.+)[\\/]projects[\\/][^\\/]+[\\/]([^\\/]+)\.jsonl$/.exec(transcript)
506 return m !== null && m[2] === sessionId ? m[1] : undefined
507}
508
509/** The separator a folder's own path uses: `\` if it holds one, else `/`. */
510export const sepOf = (dir: string): string => (dir.includes('\\') ? '\\' : '/')
511
512/** The roster file of one lead session in the plugin's data folder, named by
513 * its checked session id. */
514export function rosterFile(data: string, sessionId: string): string {
515 const sep = sepOf(data)
516 return `${data}${sep}brigade${sep}${sessionId}.json`
517}
518
519/** A running session, as far as the pane uses it: its name, its live state
520 * (`busy`, `idle`, `waiting`; a background session's `state` when it has no
521 * `status`), its session id and its folder. Besides those, for matching a
522 * card and for the groups only: the Desktop id, the job id, the waiting
523 * reason and the update time, each kept only
524 * in its fixed shape. None of them is ever stored. */
525export type SessionRow = {
526 name: string
527 status: string
528 sessionId?: string
529 cwd?: string
530 hostId?: string
531 jobId?: string
532 waitingFor?: string
533 updatedAt?: number
534}
535
536// The shapes the fields keep: a Desktop id as the link route takes it, a job
537// id of letters, digits and dashes, and fixed words for the rest.
538const HOST_ID = /^local_[0-9a-f-]{1,80}$/
539// The job id as the engine writes it (probed on 2.1.302): 8 hex digits.
540const JOB_ID = /^[0-9a-f]{8}$/
541const WAITING_REASONS: ReadonlySet<string> = new Set(['permission prompt', 'input needed', 'sandbox request', 'worker request', 'goal proposal', 'dialog open'])
542
543/** One of the engine's session files, `<config>/sessions/<pid>.json`, as a
544 * row: the name, the status (`?` while a new session has none yet), the
545 * session id and the folder, and for matching and grouping the Desktop id,
546 * job id, background state, waiting reason and update time. Every other
547 * field the engine writes there (its messaging socket, bridge id, process
548 * start, former names) is never taken. A file that is not one JSON object,
549 * or has no name of at most 300 characters or no session id of the engine's
550 * shape, gives none; the status is cut to one line of 20 characters, a
551 * folder over 1,000 characters is dropped, and a field outside its shape is
552 * dropped with the row kept. */
553export function sessionRow(text: string): SessionRow | undefined {
554 let r: unknown
555 try {
556 r = JSON.parse(text)
557 } catch {
558 return undefined
559 }
560 if (!isRecord(r) || typeof r.name !== 'string' || r.name === '' || r.name.length > MAX_TEXT) return undefined
561 if (typeof r.sessionId !== 'string' || !SESSION_ID.test(r.sessionId)) return undefined
562 const state = typeof r.status === 'string' ? r.status : typeof r.state === 'string' ? r.state : undefined
563 const row: SessionRow = { name: r.name, status: state === undefined ? '?' : oneLine(state, 20), sessionId: r.sessionId }
564 if (typeof r.cwd === 'string' && r.cwd.length <= 1000) row.cwd = r.cwd
565 if (typeof r.hostSessionId === 'string' && HOST_ID.test(r.hostSessionId)) row.hostId = r.hostSessionId
566 if (typeof r.jobId === 'string' && JOB_ID.test(r.jobId)) row.jobId = r.jobId
567 if (typeof r.waitingFor === 'string' && WAITING_REASONS.has(r.waitingFor)) row.waitingFor = r.waitingFor
568 if (typeof r.statusUpdatedAt === 'number' && Number.isFinite(r.statusUpdatedAt)) row.updatedAt = r.statusUpdatedAt
569 return row
570}
571
572/** A group the poll moves a card to. */
573export type Move = 'waiting'
574
575/** Each card's rows at one poll, by card title: a card with a Desktop id takes
576 * the one row holding it, and falls back to its title only when no file
577 * carries any Desktop id; else a card with a bg id takes the row with that
578 * job id; else the card matches by title. Two rows with one id: the later
579 * update time wins and one with a time beats one without. A card with
580 * several rows left (two sessions sharing a name, or sharing an id with no
581 * usable time) gets all of them, as the title match always did, so the poll
582 * draws it as shared. An update time more than 2 minutes ahead of `now`
583 * (the engine clock, when it answered) is no usable time, so a file that
584 * writes itself a far-future time does not win. A card with no row has no
585 * entry. */
586export function matchRows(cards: readonly Card[], rows: readonly SessionRow[], now = Number.NaN): Map<string, SessionRow[]> {
587 const out = new Map<string, SessionRow[]>()
588 const anyHost = rows.some(r => r.hostId !== undefined)
589 const byTitle = (title: string): SessionRow[] => rows.filter(r => r.name === title)
590 const byId = (same: SessionRow[]): SessionRow[] => {
591 if (same.length <= 1) return same
592 const timed = same.filter(r => r.updatedAt !== undefined && !(r.updatedAt > now + AHEAD_MS))
593 if (timed.length === 0) return same
594 const best = Math.max(...timed.map(r => r.updatedAt ?? 0))
595 const top = timed.filter(r => r.updatedAt === best)
596 return top.length === 1 ? top : same
597 }
598 for (const c of cards) {
599 let found: SessionRow[]
600 if (c.desktopId !== undefined) {
601 found = anyHost ? byId(rows.filter(r => r.hostId === c.desktopId)) : byTitle(c.title)
602 } else if (c.bgId !== undefined) {
603 found = byId(rows.filter(r => r.jobId === c.bgId))
604 } else {
605 found = byTitle(c.title)
606 }
607 if (found.length > 0) out.set(c.title, found)
608 }
609 return out
610}
611
612/** Where the pane moves a card, or undefined for no move: only a card the
613 * head chef marked `working` moves, and only toward the owner, to `waiting`
614 * while its session's status is `waiting` (a permission prompt or input).
615 * The head chef's needs-you, done and stopped always hold. The pane takes no
616 * background `state` from a session file (a real one carries none, and a
617 * forged one must not move a card; see #370). */
618export function rowMove(status: string, row: SessionRow | undefined): Move | undefined {
619 if (status !== 'working' || row === undefined) return undefined
620 return row.status === 'waiting' ? 'waiting' : undefined
621}
622
623/** A row's live word, at most 40 characters: `waiting · <reason>` for a
624 * waiting session with a reason, `busy` for a shell, else its status. */
625export function liveWord(row: SessionRow): string {
626 if (row.status === 'shell') return 'busy'
627 if (row.status === 'waiting' && row.waitingFor !== undefined) return oneLine(`waiting · ${row.waitingFor}`, 40)
628 return oneLine(row.status, 40)
629}
630
631/** The projects folder name of a working directory: every separator, colon
632 * and dot made a dash, which leaves no separator in it. */
633export const projectFolder = (cwd: string): string => cwd.replace(/[:\\/.]/g, '-')
634
635// A Remote Control session's link, whole.
636const WEB_LINK = /^https:\/\/claude\.ai\/code\/session_[A-Za-z0-9]{1,80}$/
637
638/** A Remote Control session's link from its transcript, or undefined: only
639 * from a row the engine itself writes when Remote Control starts, a system
640 * row of subtype `bridge_status` carrying `url`, the last one in the file.
641 * A link quoted in a prompt, a brief or a relayed message sits inside another
642 * row's text and is never read. */
643export function remoteLink(transcript: string): string | undefined {
644 let found: string | undefined
645 for (const line of transcript.split('\n')) {
646 if (!line.includes('"bridge_status"')) continue
647 let row: unknown
648 try {
649 row = JSON.parse(line)
650 } catch {
651 continue
652 }
653 if (isRecord(row) && row.type === 'system' && row.subtype === 'bridge_status' && typeof row.url === 'string' && WEB_LINK.test(row.url)) {
654 found = row.url
655 }
656 }
657 return found
658}
659
660// A Desktop session's local id, whole: the one shape both routes of Open in
661// app take from a card.
662const DESKTOP_ID = /^local_[0-9a-f-]{1,80}$/
663
664/** The app's own link to a card's session, of one of the two known shapes,
665 * or undefined: a Desktop session by its local id, or a Remote Control
666 * session by its claude.ai path under the app's scheme. */
667export function appLink(c: Card, found: string | undefined): string | undefined {
668 if (c.desktopId !== undefined && DESKTOP_ID.test(c.desktopId)) {
669 return `claude://claude.ai/epitaxy/${c.desktopId}`
670 }
671 const web = c.url ?? found
672 return web !== undefined && WEB_LINK.test(web)
673 ? `claude://claude.ai/code/${web.slice('https://claude.ai/code/'.length)}`
674 : undefined
675}
676
677/** The host systems the link route has an opener for. */
678export type HostOs = 'windows' | 'macos' | 'linux'
679
680// The link route's programs. Windows' is looked up by name, as measured in the
681// threat model's row 15. The other two are absolute, root-owned on a normal
682// install, so neither the user's PATH nor the project folder can supply a
683// stand-in for the opener itself. On Linux the opener then starts its desktop
684// helper, or a fallback browser, by name on the inherited PATH, from the
685// session's working folder.
686export const EXPLORER = 'explorer.exe'
687export const MAC_OPEN = '/usr/bin/open'
688export const XDG_OPEN = '/usr/bin/xdg-open'
689
690/** The command the link route runs on a host: its program and the link, as
691 * one argument with no shell. The link is always one of `appLink`'s two
692 * shapes, so it never starts with `-`. */
693export function openerArgv(os: HostOs, link: string): string[] {
694 return [os === 'windows' ? EXPLORER : os === 'macos' ? MAC_OPEN : XDG_OPEN, link]
695}
696
697/** Whether a probe's real path, exactly as the engine returned it, is a Unix
698 * one: one `/`, then a character that is not a separator, and no `\`
699 * anywhere. A Windows real path carries a drive letter or a share root
700 * (`\\server\…`), so it fails. Never pass it through a separator helper
701 * first: one that folds `\\server` to `//server` would let a share pass. */
702export function unixRealPath(path: string): boolean {
703 return /^\/[^\\/]/.test(path) && !path.includes('\\')
704}
705
706/** The files that prove a Unix host, in order: macOS' own version file, which
707 * System Integrity Protection guards, then Linux's opener itself. */
708export const HOST_PROBES = [
709 ['macos', '/System/Library/CoreServices/SystemVersion.plist'],
710 ['linux', XDG_OPEN],
711] as const
712
713/** Whether one of Windows' own environment names, read on its own, names a
714 * Windows host: `OS` is `Windows_NT`, or `SystemRoot` or `windir` is set.
715 * Callers read them in that order and stop at the first that does, so a
716 * later read that fails cannot undo a known answer. Windows is known by its
717 * environment only, never by a file: on Windows an absolute Unix path
718 * resolves under the drive's root, where any local user can plant it. */
719export function windowsEnv(name: 'OS' | 'SystemRoot' | 'windir', value: unknown): boolean {
720 return name === 'OS' ? value === 'Windows_NT' : value !== undefined
721}
722
723/** What one probe's `stat` answer says about the host: its Unix host, `next`
724 * when the probe file is missing so the next probe is asked, or undefined
725 * for no host. A Unix answer needs the probe to be a file whose raw real
726 * path is a Unix one; any other answer, a failed read included, is no host. */
727export function probeHost(os: 'macos' | 'linux', s: StatAnswer): HostOs | 'next' | undefined {
728 if ('missing' in s) return 'next'
729 if ('failed' in s || s.found.kind !== 'file' || s.found.realPath === undefined) return undefined
730 return unixRealPath(s.found.realPath) ? os : undefined
731}
732
733// Open in app through the Desktop app's own tool, which shows a session this
734// lead started beside it. The tool, its server and the target are constants:
735// no roster text names any of them, and only a checked Desktop id is sent.
736export const OPEN_TOOL = 'mcp__ccd_window__open_session_in'
737export const OPEN_SERVER = 'ccd_window'
738export const OPEN_NAME = 'open_session_in'
739export const OPEN_TARGET = 'split'
740export const OPEN_WAIT_MS = 5000
741export const OPENED = 'Opened in the app.'
742export const NOT_OPENED = 'The app did not open it: '
743
744/** The session id a press asks the Desktop app's tool to show, or undefined
745 * when the card takes the link route alone: only a Desktop id of the checked
746 * shape. A background card, a Remote Control link or any other text in the
747 * card never reaches the tool. */
748export function toolSession(c: Card): string | undefined {
749 return c.desktopId !== undefined && DESKTOP_ID.test(c.desktopId) ? c.desktopId : undefined
750}
751
752/** Whether the engine lists the Desktop app's tool by exactly its name. The
753 * owner's rules are matched on that name, so the press asks about no other;
754 * the terminal lists none. The list is read as untrusted. */
755export function listsOpenTool(tools: unknown): boolean {
756 return Array.isArray(tools) && tools.some(t => isRecord(t) && t.name === OPEN_TOOL)
757}
758
759/** Whether the owner's rules let a press call the tool, from the engine's
760 * verdict, read as untrusted: `allow`, or an `ask` that names no rule, which
761 * is a mode's; and an organisation's ceiling, where the engine reports one, of
762 * `allow`. A `deny`, an `ask` naming a rule, a lower ceiling or anything else
763 * keeps the press on the link route. */
764export function rulesAllowTool(verdict: unknown): boolean {
765 if (!isRecord(verdict)) return false
766 if (verdict.ceiling !== undefined && verdict.ceiling !== 'allow') return false
767 if (verdict.decision === 'allow') return true
768 return verdict.decision === 'ask' && verdict.rule === undefined
769}
770
771// The first line of a text block, made safe to draw and cut to the pane's
772// one-line length. The line is taken before cleaning, which folds breaks.
773const firstLine = (text: string) => oneLine(text.split(/\r\n|[\n\r\u{2028}\u{2029}]/u)[0] ?? '', 200)
774
775/** What the Desktop app's answer means, read as untrusted, since another
776 * plugin can answer in the app's place. Exactly one of three outcomes:
777 * opened with the answer's first line to show; opened with no text, shown as
778 * a fixed line; or not opened, with the app's own reason when it gave one as
779 * text. Nothing in it throws. */
780export function readOpenAnswer(answer: unknown): { opened: true; toast: string } | { opened: false; reason?: string } {
781 try {
782 if (!isRecord(answer) || !Array.isArray(answer.content) || typeof answer.isError !== 'boolean') return { opened: false }
783 const first: unknown = answer.content[0]
784 const text = isRecord(first) && first.type === 'text' && typeof first.text === 'string' ? firstLine(first.text) : ''
785 if (answer.isError === false) return { opened: true, toast: text === '' ? OPENED : text }
786 return text === '' ? { opened: false } : { opened: false, reason: `${NOT_OPENED}${text}` }
787 } catch {
788 // A field that throws when read is not an answer.
789 return { opened: false }
790 }
791}
792
793// The wrapper the engine puts round a message from another session. Only a
794// wrapper that opens the delivery counts, so a body quoting one names nobody.
795const WRAPPER = /^\s*<cross-session-message\s+from="([^"]{1,200})"[^>]*>/
796
797/** A report's claimed sender and its first line of text, both made safe to
798 * draw. The sender is the wrapper's claim, never a credential. */
799export function report(raw: string): { from: string; line: string } {
800 const m = WRAPPER.exec(raw)
801 const body = (m === null ? raw : raw.slice(m[0].length)).replace(/<\/cross-session-message>\s*$/, '')
802 const line = body.split('\n').find(l => l.trim() !== '') ?? ''
803 return { from: oneLine(m?.[1] ?? 'a session', MAX_TITLE), line: oneLine(line, 200) }
804}
805
806/** A lookup over pairs that never reaches a prototype: a Map, built per read. */
807export const lookup = (pairs: readonly Pair[]) => new Map(pairs.map(p => [p.name, p.value]))
808
809// --- a head-chef load where the security default is seated (#380) -----------
810//
811// Where a user plugin's skill.prompt hook never runs, a head-chef load is seen
812// through the call around it. These say whether that load ran, and whether
813// the session's local skill listing shows the loaded copy is ours.
814
815/** A typed load ran only when core answered it with its `ref`: a hook that
816 * answers the command in core's place expanded no skill. */
817export function typedLoadRan(answer: unknown): boolean {
818 return isRecord(answer) && !('deny' in answer) && answer.ref !== undefined
819}
820
821/** A model's Skill load ran only when the Skill tool says it succeeded. */
822export function skillLoadRan(answer: unknown): boolean {
823 if (!isRecord(answer) || 'deny' in answer || answer.isError === true) return false
824 return isRecord(answer.result) && answer.result.success === true
825}
826
827type ListedSkill = { name?: unknown; source?: unknown; pluginName?: unknown }
828type SkillListing = { totalSkills?: unknown; includedSkills?: unknown; skillFrontmatter?: readonly ListedSkill[] }
829
830/** Whether the listing shows the loaded copy is ours: for `grimoire:head-chef`,
831 * one copy of the name and it is grimoire's own; for `head-chef`, every copy
832 * of the name is the owner's own. A listing that left skills out, or gives
833 * no counts, confirms nothing. */
834export function listedAsOurs(skills: SkillListing | undefined, name: string): boolean {
835 if (skills === undefined || typeof skills.totalSkills !== 'number' || skills.includedSkills !== skills.totalSkills) return false
836 const copies = (skills.skillFrontmatter ?? []).filter(s => s.name === name)
837 if (copies.length === 0) return false
838 return name === 'grimoire:head-chef'
839 ? copies.length === 1 && copies[0].source === 'plugin' && copies[0].pluginName === 'grimoire'
840 : copies.every(s => s.source === 'userSettings')
841}
842brigade/writer.ts 254 lines1import { atom, read } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { dataPlace, placeSummary, statRejection } from './roster.ts'
5import type { StatAnswer } from './roster.ts'
6import {
7 MAX_SUMMARY_BYTES,
8 askWrite,
9 isSummaryFile,
10 newFlight,
11 newUsageMemory,
12 recordCall,
13 serializeSummary,
14 stepCall,
15 summaryFrom,
16 writeDone,
17} from './view.ts'
18
19// The usage summary writer. Every session with the plugin keeps its own usage
20// numbers as it works and writes them, numbers only, to its own summary file,
21// brigade/usage/<session id>.json in the plugin's data folder, so the lead's
22// pane can draw a member whose transcript is too large to read. No pane, no
23// /brigade and no tool is needed for it to run.
24//
25// A `turn.step` hook starts an unawaited read of the session id, passes the
26// step on, then records it. On the step's
27// path it awaits no engine call: it reads the step's own result, keeps the
28// numbers in module memory, stamps them from the module's own clock and, when
29// a write is due, starts one it does not await. The writes run one at a time,
30// at most every 15 s while a turn runs and at every main-loop turn end. The
31// decisions are view.ts's, under its tests; this file only feeds them, stats
32// and writes.
33//
34// It makes no session usage call, so no cost, rate limit or context breakdown
35// ever enters it. The first refusal of the summary path, before or after a
36// write, stops it until the module reloads, with one toast; a clear does not
37// restart it.
38
39// The engine's record of a session's start, the last one raised, which register.tsx's
40// `classic.SessionStart` hook keeps under the same key.
41const started = atom({ plugin: 'grimoire', key: 'start' } as const, { sessionId: '', transcript: '' })
42
43let memory = newUsageMemory()
44let flight = newFlight()
45let stopped = false
46// The session id the memory belongs to, from the engine's session start and
47// from the id reads below.
48let sessionOf: string | undefined
49// The id reads the step hook starts, numbered in the order started. Only the
50// latest-started read that has answered counts, so a slow older answer cannot
51// put the writer back on a session it has left.
52let readsStarted = 0
53let latestAnswered = 0
54
55// The module's clock: the engine clock's epoch, read once and never awaited
56// on a step's path, carried on by `performance.now()`. Until the epoch
57// arrives, the machine's own clock stands in; both read the same epoch in a
58// live session (probe part 2 on #311). Whole milliseconds.
59let epoch: { engine: number; perf: number } | undefined
60let epochAsked = false
61function readEpoch($: EngineInterface) {
62 if (epochAsked) return
63 epochAsked = true
64 const perf = performance.now()
65 $.clock.now().then(
66 engine => {
67 if (Number.isFinite(engine)) epoch = { engine, perf }
68 },
69 () => undefined,
70 )
71}
72const now = (): number => Math.round(epoch === undefined ? Date.now() : epoch.engine + (performance.now() - epoch.perf))
73
74// The engine follows `$` only into functions declared in the file that holds
75// the hook, so the functions below are written here rather than imported.
76
77// The config folder, the plugin's data id and this session's id, read at
78// each write, so after a clear the file follows the new id; by the rule the
79// roster uses (`dataPlace`). Undefined when no config folder can be named.
80async function locate($: EngineInterface): Promise<{ config: string; plugin: string; id: string } | undefined> {
81 const id = await $.session.id()
82 const { config, plugin } = dataPlace($.plugin.root, $.plugin.name, await read($, started))
83 return config === undefined ? undefined : { config, plugin, id }
84}
85
86// Starts a read of the session id and does not wait for it, so a clear or a
87// resume is seen without `classic.SessionStart`. A rejected read is ignored.
88function followSession($: EngineInterface) {
89 const n = ++readsStarted
90 $.session.id().then(
91 id => {
92 if (n < latestAnswered) return
93 latestAnswered = n
94 writerSession(id)
95 },
96 () => undefined,
97 )
98}
99
100// One resolving `stat` for the path rule, a rejection sorted into missing or
101// failed by its message.
102function statPath($: EngineInterface, path: string): Promise<StatAnswer> {
103 return $.fs.stat(path, { resolve: true }).then(
104 found => ({ found }),
105 err => statRejection(String(err instanceof Error ? err.message : err)),
106 )
107}
108
109// The kinds of refusal, in fixed words: the toast names the kind and never
110// the engine's message or the file's text, either of which can hold a path.
111const REFUSED = {
112 path: 'the summary path failed its check',
113 file: 'the summary path holds a file that is not a summary file, so it is not overwritten',
114 after: 'the summary path failed its check after the write',
115} as const
116
117// The first refusal stops every later write until the module reloads, and
118// its words are toasted once, by the caller; a later refusal has none. A
119// clear does not restart it. The caller makes the toast so `$` reaches no
120// helper here: the directory's checker refuses that.
121function refuse(kind: keyof typeof REFUSED): string | undefined {
122 if (stopped) return undefined
123 stopped = true
124 return `Brigade: the usage summary was not written, and will not be until the plugin reloads (a clear does not restart it): ${REFUSED[kind]}.`
125}
126
127// A write is asked for; one starts when the throttle and the single flight
128// allow. Its run, and any run waiting behind it, is never awaited here.
129function ask($: EngineInterface, turnEnd: boolean) {
130 const r = askWrite(flight, now(), turnEnd)
131 flight = r.flight
132 if (r.start) void run($)
133}
134
135async function run($: EngineInterface) {
136 try {
137 await writeOnce($)
138 } catch {
139 // A write that fails is tried again at the next one due.
140 } finally {
141 const r = writeDone(flight, now())
142 flight = r.flight
143 if (r.start) void run($)
144 }
145}
146
147// One write: place the file under the path rule, overwrite only a summary
148// file, take the newest numbers, write, and run the path rule again after.
149async function writeOnce($: EngineInterface) {
150 if (stopped) return
151 // The session the memory belongs to when the write starts. A clear while
152 // the write waits on its checks moves it, and the write is skipped, so one
153 // session's numbers never land in another's file; the next one due writes.
154 const owner = sessionOf
155 // No config folder named: nothing is written, and nothing was refused.
156 const at = await locate($)
157 if (at === undefined || (owner !== undefined && at.id !== owner)) return
158 const placed = await placeSummary(at.config, at.plugin, at.id, (path: string) => statPath($, path))
159 if ('refused' in placed) {
160 const said = refuse('path')
161 if (said !== undefined) $.ui.toast(said, { timeoutMs: 15000 })
162 return
163 }
164 if (placed.existing !== undefined) {
165 const text = placed.existing.size <= MAX_SUMMARY_BYTES ? String(await $.fs.read(placed.file)) : undefined
166 if (!isSummaryFile(placed.existing.size, text)) {
167 const said = refuse('file')
168 if (said !== undefined) $.ui.toast(said, { timeoutMs: 15000 })
169 return
170 }
171 }
172 // The id again, just before the numbers are taken: a clear while the checks
173 // waited moves it, and this write is skipped; the writer moves to the new
174 // session.
175 const again = await $.session.id()
176 if (again !== at.id) return writerSession(again)
177 const summary = summaryFrom(memory, now())
178 if (summary === undefined || stopped || sessionOf !== owner) return
179 const text = serializeSummary(summary)
180 if ('error' in text) return
181 await $.fs.write(placed.file, text.value)
182 // A link swapped in between the check and the write is caught here, after
183 // the fact. A hard link is not.
184 const after = await placeSummary(at.config, at.plugin, at.id, (path: string) => statPath($, path)).catch(() => ({ refused: 'the check could not run' }))
185 const why = 'refused' in after ? after.refused : after.existing === undefined ? 'the file is not there' : undefined
186 if (why === undefined) return
187 const said = refuse('after')
188 if (said !== undefined) $.ui.toast(said, { timeoutMs: 15000 })
189}
190
191/** For register.tsx's `session.start` hook, which a module load raises: the
192 * engine clock's time and `performance.now()` when it was asked, so the
193 * epoch is known before the first step. Only numbers cross: the engine
194 * follows `$` into no function of another file. The first epoch wins. */
195export function writerEpoch(engine: number, perf: number) {
196 epochAsked = true
197 if (epoch === undefined && Number.isFinite(engine) && Number.isFinite(perf)) epoch = { engine, perf }
198}
199
200/** For register.tsx's `session.start` and `classic.SessionStart` hooks, and
201 * for the id reads the step hook starts: the session id the memory belongs
202 * to. A module load names it first, so a clear or a resume after a reload is
203 * seen as one; a new id starts the series over, the old file left behind.
204 * Never throws. */
205export function writerSession(sessionId: unknown) {
206 if (typeof sessionId !== 'string') return
207 if (sessionOf !== undefined && sessionOf !== sessionId) memory = newUsageMemory()
208 sessionOf = sessionId
209}
210
211/** Registers the writer's two hooks. The engine takes one hook per event from
212 * a module, so the session start's work is register.tsx's to call:
213 * `writerEpoch` and `writerSession`. */
214export function registerWriter(on: On) {
215 // The step starts its id read, then is passed on. Everything after it sits
216 // in one catch, and the registration's own catch passes the step through
217 // unchanged.
218 on('turn.step', async function* ($, e, next) {
219 try {
220 followSession($)
221 } catch {
222 // The step goes on unchanged.
223 }
224 const r = yield* next(e)
225 try {
226 if (!stopped) {
227 readEpoch($)
228 const call = stepCall(e, r)
229 if (call !== undefined) {
230 memory = recordCall(memory, call, now())
231 ask($, false)
232 }
233 }
234 } catch {
235 // The step goes on unchanged.
236 }
237 return r
238 }).catch(async function* ($, e, next) {
239 return yield* next(e)
240 })
241
242 // Every main-loop turn end writes, aborted turns included, once a call was
243 // counted since the module loaded. A subagent's turn end writes nothing.
244 on('turn.complete', async ($, e, next) => {
245 const r = await next(e)
246 try {
247 if (!stopped && e.agentId === undefined && memory.calls > 0) ask($, true)
248 } catch {
249 // The turn ends unchanged.
250 }
251 return r
252 }).catch(($, e, next) => next(e))
253}
254brigade/warning.tsx 125 lines1import { atom, read, update } from 'claude-code'
2import type { On } from 'claude-code'
3
4import { ALSO, RISKS, TITLE, WORDING, isAcknowledged, versionOf } from './warning-text.ts'
5import type { Ack } from './warning-text.ts'
6
7// The permission warning: a band above the prompt in a lead session, saying
8// what the sessions the head chef starts put at risk. The head-chef skill
9// calls the tool before its first launch in a lead. "I understand" hides the
10// band for this session; with "Don't show again" ticked first, it hides it in
11// every later lead too, until the wording changes. The band is for awareness:
12// pressing it accepts no risk.
13//
14// No checkbox element exists on any surface, so "Don't show again" is a
15// button drawn as a box, which a press ticks and unticks.
16
17// register.tsx's own start hooks read the store and offer the tool, from
18// these: `claude plugin validate` refuses `$` handed to an imported function.
19export const TOOL = 'show_permission_warning'
20const TOOL_NAME = 'mcp__grimoire__show_permission_warning'
21export const DESCRIPTION =
22 "Shows the head chef's permission warning above the prompt in this session. The head-chef skill calls it once, before its first launch in a lead. Takes no input."
23export const SCHEMA = { type: 'object', properties: {}, additionalProperties: false }
24export const STORE_KEY = 'permission-warning-ack'
25const VERSION = versionOf(WORDING)
26
27// Shown in this session: set by the tool, and kept across a reload.
28const shown = atom({ plugin: 'grimoire', key: 'warningShown' } as const, false)
29// Hidden by "I understand" for the rest of this session.
30const hidden = atom({ plugin: 'grimoire', key: 'warningHidden' } as const, false)
31// The box's tick, for this session. "I understand" reads it.
32const ticked = atom({ plugin: 'grimoire', key: 'warningTicked' } as const, false)
33// The owner's "Don't show again", read from the store at each start.
34// register.tsx writes it at each start, through its own atom of this key.
35const ack = atom({ plugin: 'grimoire', key: 'warningAck' } as const, null)
36
37/** What the store holds, as an acknowledgement. Any well-formed one is kept,
38 * of this version or an older one, so the band can say the wording changed;
39 * anything else is none. */
40export function ackFrom(value: unknown): Ack | null {
41 if (typeof value !== 'object' || value === null) return null
42 const { at, version } = value as Record<string, unknown>
43 return typeof at === 'string' && typeof version === 'string' ? { at, version } : null
44}
45
46export function registerWarning(on: On) {
47 on('tool.call', { tool: TOOL_NAME }, async ($, e) => {
48 if ((e as unknown as Record<string, unknown>).agentId !== undefined) {
49 return { deny: `${TOOL} refused: only the lead session's own turns show the warning.` }
50 }
51 // The owner's own rules hold for this tool, as for set_roster: a deny,
52 // or an ask rule that names it, refuses the call.
53 const verdict = await $.tool.check({ tool: TOOL_NAME, input: {} })
54 if (verdict.decision === 'deny' || (verdict.decision === 'ask' && verdict.rule !== undefined)) {
55 return { deny: `${TOOL} refused: the owner's rules cover this tool. Say the warning to the owner in chat instead.` }
56 }
57 if (isAcknowledged(await read($, ack), VERSION)) {
58 return { result: "The owner chose Don't show again for this wording, so the warning stays hidden. Go on with the launch." }
59 }
60 await update($, shown, () => true)
61 await update($, hidden, () => false)
62 return { result: 'The permission warning is shown above the prompt. Go on with the launch; it needs no answer.' }
63 }).catch(() => ({ deny: `${TOOL} refused: the tool failed. Say the warning to the owner in chat instead.` }))
64
65 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
66 if (e.props.hasSurvey || !(await read($, shown)) || (await read($, hidden))) return next(e)
67 const kept = await read($, ack)
68 if (isAcknowledged(kept, VERSION)) return next(e)
69
70 const { Box, Button, Text } = $.ui.resolve(e)
71 const box = await read($, ticked)
72 // The stored time is drawn only as a date of that shape; anything else
73 // the store holds is never drawn.
74 const at: unknown = kept !== null ? (kept as Ack).at : null
75 const changed = at === null ? null : typeof at === 'string' && /^\d{4}-\d{2}-\d{2}/.test(at) ? at.slice(0, 10) : ''
76
77 return (
78 <Box key="permission-warning" flexDirection="column" borderStyle="round" paddingX="lg" paddingY="md" gap="md">
79 <Text bold>{TITLE}</Text>
80 <Box flexDirection="column" gap="xs" paddingLeft="sm">
81 {RISKS.map((line, i) => (
82 <Text key={`risk-${i}`}>• {line}</Text>
83 ))}
84 </Box>
85 {changed !== null ? (
86 <Text dimColor>
87 {changed === '' ? "The wording changed since you chose Don't show again." : `The wording changed since you chose Don't show again on ${changed}.`}
88 </Text>
89 ) : null}
90 <Box flexDirection="row" justifyContent="space-between" alignItems="center" gap="md">
91 <Box flexShrink={1}>
92 <Text dimColor>{ALSO}</Text>
93 </Box>
94 <Box flexDirection="row" alignItems="center" gap="sm">
95 <Button
96 key="dont-show"
97 label={box ? "☑ Don't show again" : "☐ Don't show again"}
98 onPress={async () => {
99 await update($, ticked, t => !t)
100 }}
101 />
102 <Button
103 key="understand"
104 variant="primary"
105 label="I understand"
106 onPress={async () => {
107 if (await read($, ticked)) {
108 try {
109 const value: Ack = { at: new Date(await $.clock.now()).toISOString(), version: VERSION }
110 await $.store.set(STORE_KEY, value)
111 await update($, ack, () => value)
112 } catch {
113 // Not kept for later leads; the band still hides for this one.
114 }
115 }
116 await update($, hidden, () => true)
117 }}
118 />
119 </Box>
120 </Box>
121 </Box>
122 )
123 })
124}
125brigade/warning-text.ts 35 lines1// The permission warning's wording, and the test of whether the owner has
2// already chosen "Don't show again" for it. Plain TypeScript with no engine
3// import, so tests/brigade-warning.test.mjs imports it as it is. The band
4// that draws it is warning.tsx.
5//
6// The wording is the head-chef contract's, word for word. Any change to it
7// moves the version, and the band shows again in every lead until the owner
8// ticks "Don't show again" once more.
9
10export const TITLE = 'Head chef is on. Two things to know:'
11export const RISKS = [
12 'Any device signed in to your account can drive the sessions it starts while Remote Control is on.',
13 'Those sessions trust any message that claims to come from it, and any comment on their issue made as you.',
14]
15export const ALSO = 'It also starts sessions, relays between them, and merges or cleans up on your word.'
16export const WORDING: readonly string[] = [TITLE, ...RISKS, ALSO]
17
18/** The owner's "Don't show again": when, and which version of the wording. */
19export type Ack = { at: string; version: string }
20
21/** A short, stable version of the wording: djb2 over the joined lines, in hex. */
22export function versionOf(lines: readonly string[]): string {
23 let h = 5381
24 for (const ch of lines.join('\n')) h = ((h * 33) ^ ch.codePointAt(0)!) >>> 0
25 return h.toString(16).padStart(8, '0')
26}
27
28/** Whether a stored value is an acknowledgement of this version. Anything
29 * else the store holds, of any shape, leaves the warning to show. */
30export function isAcknowledged(stored: unknown, version: string): boolean {
31 if (typeof stored !== 'object' || stored === null) return false
32 const { at, version: v } = stored as Record<string, unknown>
33 return typeof at === 'string' && typeof v === 'string' && v === version
34}
35brigade/types/index.d.ts 149 lines1/** The status the head chef writes on a card, from a fixed set. */
2export type Status = 'working' | 'needs-you' | 'done' | 'stopped'
3
4/** One session the lead started, as its roster card says. */
5export type Card = {
6 title: string
7 work: string
8 phase: string
9 settings: string
10 status: Status
11 /** A Desktop session's local id (local_...). */
12 desktopId?: string
13 /** A background session's id. */
14 bgId?: string
15 /** The session's https link on claude.ai, when the head chef knows it. */
16 url?: string
17 /** The session's PR number as text, 1 to 7 digits. */
18 pr?: string
19 /** The head chef's last-known state of that PR, used when `gh` has no answer. */
20 prState?: PrState
21 /** When the card entered its current status and phase, in milliseconds on
22 * the engine clock. The tool stamps it; the file may hold it. */
23 since?: number
24}
25
26/** A PR's state, as the card keeps it and as `gh`'s answer is read. */
27export type PrState = 'open' | 'merged' | 'closed'
28
29/** Something waiting on the owner that no card already shows. */
30export type Todo = { id: string; text: string; session?: string }
31
32/** A lead session's roster file, after its shape check. */
33export type Roster = { cards: Card[]; todos: Todo[] }
34
35/** A report from another session: its claimed sender and first line. */
36export type Report = { from: string; line: string; at: string }
37
38/** A pair from a lookup, kept as a list so no key reaches a prototype. */
39export type Pair = { name: string; value: string }
40
41/** Where the roster file is, and the one before a clear or a resume. */
42export type Files = { current: string; previous: string }
43
44/** What the engine said at session start: the id and its transcript path. */
45export type Start = { sessionId: string; transcript: string }
46
47/** One rate-limit window: its kind, how much of it is used, when it resets. */
48export type UsageLimit = { kind: string; percent: number; resetsAt?: string }
49
50/** One row of the context breakdown: its name, what it is, its tokens. */
51export type UsageCategory = { name: string; kind: string; tokens: number }
52
53/** This session's usage as the pane last read it: only the fields it draws.
54 * `categories` is absent when no breakdown was asked for. */
55export type UsageSnapshot = {
56 limits: UsageLimit[]
57 context: { percent?: number; tokens?: number; window?: number }
58 categories?: UsageCategory[]
59}
60
61/** One reading of this session's own session limit (`five_hour`): when it
62 * was taken, in epoch ms, and the percent used. */
63export type Sample = { at: number; percent: number }
64
65/** One card's cache warmth, from its session's summary file or its
66 * transcript: the last real model call's time, its context tokens and its
67 * cache window (from a transcript, absent when no call that wrote cache says
68 * it; from a summary file, a fixed hour, absent when no call wrote or read
69 * cache); or unknown, because the transcript is too
70 * large to read or two sessions share the card's name; or not read yet,
71 * because the session has been working since the pane first saw it; or not
72 * found, because no transcript passed the finder's checks. No path is kept. */
73export type Warmth =
74 | { name: string; kind: 'call'; at: number; tokens: number; windowMs?: number }
75 | { name: string; kind: 'too-large' | 'shared' | 'unread' | 'not-found' }
76
77/** One card's call series, from its session's summary file or its
78 * transcript: the time its burn buckets end, the end of the clock minute
79 * of the read or the write that gave it; the context window of its model's
80 * family, in tokens, from a fixed table (absent when the table has none);
81 * the new tokens of each of the 30 clock minutes up to that time, oldest
82 * first; and the context size of each of the last 30 calls, oldest first. Numbers only: no path, model or message
83 * id is kept. */
84export type Meter = { name: string; at: number; window?: number; burn?: number[]; context?: number[] }
85
86declare module 'claude-code' {
87 interface PluginState {
88 grimoire: {
89 /** True while the pane is open. Nothing in the mod gates on it: the
90 * hooks read the open pane from the module's own timers. */
91 armed: boolean
92 start: Start
93 files: Files
94 roster: Roster
95 rosterError: string
96 live: { name: string; value: string; shown?: string; move?: 'waiting' }[]
97 liveError: string
98 links: Pair[]
99 reports: Report[]
100 dismissed: string[]
101 doneTodos: string[]
102 /** Ticked to-dos still inside their grace period: the to-do's id and
103 * the tick's time in epoch ms, as text. A second press removes one;
104 * the roster timer's sweep moves a due one to `doneTodos`. */
105 ticking: Pair[]
106 /** This session's last usage reading, read while the pane is open. */
107 usage: UsageSnapshot
108 /** This session's own session-limit percent, sampled from the usage
109 * readings while the pane is open, for its projection: at most one
110 * every 30 s, at most 120. Checked again before use. */
111 samples: Sample[]
112 /** Each roster member's cache warmth, from the agents poll while the
113 * pane is open. Checked again before it is drawn. */
114 warmth: Warmth[]
115 /** Each roster member's call series, from the same reads as its
116 * warmth. Checked again before it is drawn. */
117 meters: Meter[]
118 /** Each roster member whose summary file the agents poll refused: its
119 * name and a kind word, `path` (the path rule refused it) or `file`
120 * (the same file failed its checks two polls running). Read only
121 * through those two words. */
122 refusals: Pair[]
123 /** Each card's chosen tab: its title and a view word, `cache`, `burn`
124 * or `trend`, kept for the session and not reset when the pane opens.
125 * Read only through the fixed set of view words. */
126 tabs: Pair[]
127 /** The chosen view, `sessions` or `prs`: set to `sessions` each time
128 * /brigade or a skill load that opens the pane does. Read only through the fixed set. */
129 view: string
130 /** The selected cards' titles, at most 50. Cleared when /brigade or a skill load
131 * opens the pane. Checked again before use. */
132 picked: string[]
133 /** The folded groups, from the fixed set of six group keys: set to
134 * the finished group each time the pane opens, and flipped by a press.
135 * Checked again before use. */
136 folded: string[]
137 /** The permission warning is shown in this session: set by its tool. */
138 warningShown: boolean
139 /** "I understand" hid the permission warning for this session. */
140 warningHidden: boolean
141 /** The warning's "Don't show again" box is ticked, for this session. */
142 warningTicked: boolean
143 /** The owner's "Don't show again", as the store holds it: when, and the
144 * version of the wording. Checked again before use. */
145 warningAck: { at: string; version: string } | null
146 }
147 }
148}
149