SLOPSHOPPER

gsd-status-mod

A Claude Code mod for GSD projects: a live pane (roadmap, agent tree with forks, cost and context, work streams, session log, pace and fit forecast, timeline…

panebandspinnerrowsguardcommand
★ 6v0.8.2MITupdated 2026-10-17helenkwok/gsd-status-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · gsd-status-mod
│ ┃ gsd-board ✕ › fix the failing auth test and add an audit log call │ ┃ No GSD project here. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /gsd-status │ ⎿ gsd-status-mod: No GSD project here: .planning/STATE.md is missi │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · gsd-board
No GSD project here.
README

<h1 align="center">gsd-status-mod</h1>

<a href="https://github.com/helenkwok/gsd-status-mod/actions/workflows/test.yml"><img alt="tests" src="https://github.com/helenkwok/gsd-status-mod/actions/workflows/test.yml/badge.svg"></a> <img alt="version 0.8.2" src="https://img.shields.io/badge/version-0.8.2-d97757"> <img alt="Claude Code 2.1.287+" src="https://img.shields.io/badge/Claude%20Code-2.1.287%2B-d97757"> <a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-3fb950"></a>

A live dashboard for GSD projects, as a Claude Code mod: the roadmap with the current phase marked, an agent tree with forks and sub-agents and live clocks, context and cost, blockers and what needs a person, work streams, and a built-in markdown reader for .planning.

[!NOTE] Read-only. It reads .planning/ and the git reflog, writes no files, runs no processes and makes no network calls. It draws nothing outside a GSD project. No runtime dependencies. Details: What it can touch.

📥 Install

Claude Code 2.1.287 or later:

claude plugin marketplace add helenkwok/gsd-status-mod claude plugin install gsd-status-mod@helenkwok-mods

After that it loads in every session, with no flag. Update with claude plugin update gsd-status-mod@helenkwok-mods; remove with claude plugin uninstall gsd-status-mod@helenkwok-mods. Add --scope project to install it for one project only. To try it without installing, see Try it from a clone.

✨ Features

  • Live pane: main box (context, cost, limits, blockers), roadmap, pace, agents, last turn, work streams, session log.
  • Pace and fit: how the phase's plans run in waves, how long the rest should take, and how far it should take the 5-hour window.
  • History, trends and timeline: numbers-only records of past agents, typical times beside running clocks, three trend charts, and a bar per agent over the latest working stretch.
  • Markdown reader for .planning: browse any depth, follow links between plans, contents list, header hidden.
  • Reader links in the transcript: under tool rows and replies that name a .planning markdown file.
  • GSD · line above the prompt, with a drift warning when STATE.md is behind the commits.
  • next: hint and a Tab suggestion from the handoff's next action.
  • /gsd-status: the full resume report on demand. /gsd-board: open or close the pane.
  • Toasts: an agent far over its usual time, a phase that will not fit the window, drift appearing.
  • Workstream mode and git worktrees.

🕹️ Using the pane

Everything with a ▸ is clickable. With the pane focused (ctrl+x, then Tab) these keys work too:

KeyWhereWhat it does
1-6agentsOpen or close that agent row
bdashboardBlockers and what needs a person
breader, trends, timelineBack
rdashboardThe whole roadmap
pdashboardPace details
tdashboardTrends
treaderBack to top
gdashboardTimeline
wdashboardSwitch workstream (when there are several)
odashboardRead .planning
dreaderBack to the dashboard
creader, in a fileContents
fagentsAll agents, finished ones included
lsession logEarlier entries
CommandWhat it does
/gsd-statusThe full resume report, read fresh from disk
/gsd-boardOpen or close the pane

⚙️ Settings

Set with /plugin configure gsd-status-mod@helenkwok-mods.

OptionWhat it doesDefault
openOnStartOpen the pane when a session starts in a GSD project. /gsd-board opens it later either way.true
toastsShort notices: an agent far over its usual time, a phase that will not fit the 5-hour window, STATE.md drift.true

🧠 How each part works

The live pane

Docked on the right of a wide terminal (144+ columns). Bordered boxes that update as events happen, not only per turn.

  • main: context gauge, session cost, 5h and 7d limits, blockers and people-needed from the handoff. The cost is whatever Claude Code reports for the session, shown as is; it is an estimate, not a bill.
  • roadmap: the phase checklist from ROADMAP.md with the current phase marked. The current phase comes from STATE.md (its current_phase, or the label that starts current_phase_name); it is never guessed, so a project whose state names no phase shows the list with no marker. Only - [x] Phase N: name lines are read.
  • pace: how the current phase's plans are laid out to run (plans left, waves, the widest wave) and where this session's agent time went (share by agent type, and how parallel the executors ran, 1.0 being one at a time). It says "serial" only on clear evidence: plans left in single-plan waves, or two or more executors that ran one at a time. Plans come from wave: in the phase's *-PLAN.md frontmatter; a plan with a NN-MM-SUMMARY.md is done. p shows the wave-by-wave list, this phase's time by stage, and the time by type.
  • agents: a tree of running and finished agents, with forks (⑂) and sub-agents under their parent, and a live clock. Finished agents fold away while others run; f opens the whole tree, every agent and its full description.
  • last turn / turn, work streams (counts and newest of phases, spikes, threads, todos, seeds, notes; an open stream lists its five newest, and ▸ all N in the reader opens its folder) and a session log of prompts, spawns, errors and new commits (the last 40, all shown when opened).

The band above the prompt is hidden while the pane is open, so the same line is not drawn twice.

History, fit, trends and timeline

History: each finished agent leaves one small record, kept in the plugin's own store across sessions (the last 300 per project): type, phase, duration, number of model responses, token counts and model. No description, no prompt, no text. With five or more past runs of a kind, a running agent's clock shows typ 0:20 beside it, in amber once it is over twice the typical. History starts from the day you update; it is per project and never read from transcripts.

Fit: with three or more past executor runs, a left line says how long the phase's open waves should take (one typical executor run per wave, so plans that can run together count once), the 5h line gives the window and when it resets, and the quota line adds how far the rest of the phase should take the window. Quota is measured, not guessed: while executors run, the plugin notes how far the 5-hour window rose and divides it by how many ran together, so a single executor and a wave of three both give a per-executor figure. It needs five such measurements, shows a range (the middle half of them), and leaves out any stretch with a reviewer or planner in it or where the window reset. The account is shared with the main conversation and other sessions, so read it as a range. When the next wave runs plans together, a next line shows what that wave alone should add.

Trends (t): executor time per run (a sparkline of the last 30), time by phase split into planning, executing and checking, and agent time per day for 14 days, each with its numbers beside it.

Timeline (g): one bar per agent over the latest working stretch (until a gap of 30 minutes, at most 12 agents, running ones shaded): agents that ran together sit on top of each other and agents that ran one after another form a staircase, with the executors' parallelism underneath.

The markdown reader

o: ▸ read .planning (or any entry under work streams) swaps the dashboard for a browser of .planning, one folder at a time (so any depth), and then for the file itself, drawn by Claude Code's own Markdown element: the same typography as a reply, at the pane's width, scrolled with the wheel or PageDown/End.

  • The YAML header is hidden, - [x] shows as ✓ and - [ ] as ○, and a relative link to another .md file under .planning opens it.
  • A folder lists all its entries. b goes back one level, d: ⌂ dashboard returns to the dashboard from any depth, and t: ↑ back to top ends every file and every folder of more than 30 entries.
  • A file with three or more headings gets c: ▸ contents: a list of its headings (all of them, levels 1 to 3) that jumps to one.
  • Only .planning is readable. A path opens only if its real location, symlinks followed, is still under .planning's own, so a symlink inside .planning cannot lead the reader elsewhere.

Reader links in the transcript (fullscreen terminal only, where clicks reach a mod):

  • A Read, Write or Edit of a .planning markdown file gets a line under its tool row, open in the GSD reader, that opens the pane on that file.
  • A reply that names .planning markdown files gets the same line under it, one link per file: .planning/... paths, paths relative to .planning (phases/04-x/04-01-PLAN.md), absolute and Windows paths into it, and a bare file name when exactly one file has it. Only files that exist are linked; the reply itself is drawn as written. Claude Code 2.1.296 leaves paths in replies as plain text (#79839).

The band, the hint and the suggestion

GSD · stopped: PAUSED 2026-09-09 after the schema review · 9/14 phases ⚠ ~124 commits since STATE.md <- above the prompt ❯ /gsd-execute-phase 2 <- dim suggestion, Tab to take ⏵⏵ auto mode on (shift+tab to cycle) · next: Run /gsd-execute-phase 2 · handoff 5d ago <- end of the line under the prompt

Each shows what the GSD statusline does not.

  • GSD · line (above the prompt): shown only for a GSD project (a .planning/STATE.md whose frontmatter has gsd_state_version). stopped_at cut to its first sentence, plus phases done. It never repeats status or the plan counts, which the GSD statusline already shows, and it shows no age: STATE.md's last_updated is touched without the content changing.
  • ⚠ ~N commits since STATE.md: on that line, when the commit in state_head is 5 or more commits behind this clone's HEAD, so you know STATE.md is stale. Counted from the git reflog, so approximate (it undercounts: 124 against 217 from git rev-list on one repo); hidden when state_head is absent or not in the reflog.
  • next: hint (end of the line under the prompt): next_action from .planning/HANDOFF.json, with the handoff's own age. It is added as a dim tail, so the engine's line and its pills stay, and it is hidden while you type or while a turn runs. GSD deletes the file after a resume, so it goes away when it is no longer needed.
  • Tab suggestion (the empty prompt box, once at session start): only when the text shown in the next: hint names a command. It offers that command, plus a phase number or version if one follows (/gsd-execute-phase 2), so it always matches the hint beside it. Prose-only actions (Nothing is pending) and actions that say to go elsewhere (Open a session in ~/other-project and run ...) get no suggestion. Tab only fills the box; nothing runs until you press Enter. The engine proposes its own suggestion after each turn, so ours shows at session start only.
  • /gsd-status: the full resume report on demand, read fresh from disk, with no terminal-height limit. Phase and status, phase and plan progress, the whole stopped_at, the drift warning, and from HANDOFF.json the next action and its command, blockers, human_actions_pending ("Needs a person"), remaining tasks and how many files were uncommitted at pause. In a project that is not GSD it says so.

The band does not show plan usage (5-hour / weekly limits), since quota-meter and limit-watch already do; the pane's main box does show them, for the one-glance view.

Toasts

Short notices, each said once: an agent that has run more than twice its typical time, the rest of the phase getting tight against the 5-hour window (about 90% or more by the end, or the work outlasting the window when quota is not measured yet), and drift appearing between STATE.md and the commits. Turn them off with the toasts option.

Workstream mode and worktrees

When .planning/STATE.md is missing but .planning/workstreams/<name>/STATE.md exists, the pane reads that workstream's STATE.md, ROADMAP.md and work streams, plus the project-wide folders left at .planning/ (threads, spikes, seeds...), merged into the same counts (and its HANDOFF.json, else the top-level one). GSD's own choice of active workstream is per session and a mod cannot see it, so the plugin uses the name in .planning/active-workstream if there is one, else the workstream whose STATE.md changed most recently. With more than one, a w: ⇄ workstream … button (click, or w) switches to the next. The workstream name shows in the header.

In a linked git worktree with no .planning of its own, .planning is read from the main checkout. Everything follows a .planning symlink and draws nothing when there is nothing to show. The band and hint refresh at session start and after each turn; the pane also refreshes on tool calls and agent events.

📸 Screenshots

All images come from a made-up demo project (acme-portal), captured from a live Claude Code session and drawn to PNG from the terminal text; the window frame and the orange notes are added. The history behind the pace box, trends and timeline is made up; the 5h and 7d figures are the demo session's own.

<sub>The pane: main box, roadmap, pace, agents with a typical time beside each running clock, and the last turn.</sub>

<sub>p opens the pace details: waves, time by agent type, and this phase's time by stage.</sub>

<sub>The reader on a phase plan: header hidden, tasks as ✓ and ○, blue links open the next plan and the roadmap.</sub>

<sub>t opens the trends: executor time per run, time by phase and stage, agent time per day.</sub>

<sub>g opens the timeline: two executors overlapped, the third waited for them.</sub>

<sub>A handoff that names a command: the GSD · line with drift, the Tab suggestion, and the next: hint. (The model, statusline and auto mode text are Claude Code's and GSD's own.)</sub>

<sub>A handoff with no command: the hint shows, and the prompt box keeps Claude Code's own placeholder.</sub>

<sub>Not a GSD project (no gsd_state_version): nothing is added.</sub>

🔒 What it can touch (reach)

Read-only, and nothing leaves the machine:

  • Files ($.fs.read, $.fs.list, $.fs.stat): any .md under .planning/ the reader opens (only when you click it) or a reply names (to check it exists), and .planning/STATE.md, ROADMAP.md, HANDOFF.json, the entry names in .planning/phases, spikes, threads and the other work-stream folders, and the git reflog (.git/logs/HEAD, or the worktree's git dir named in a .git file). Paths resolve from the session root ($.session.root), not the current folder, so a Bash cd does not lose the project.
  • Session data: $.session.usage (context, cost, limits), $.agent.list (the live agents), $.store.get / $.store.set (the history above, in the plugin's own store) and $.clock.now / $.clock.every / $.clock.sleep (a 1-second redraw timer, active only while something runs and the pane is open, and short waits before a scroll).
  • UI: $.ui.open, $.ui.close, $.ui.invalidate, $.ui.scroll, $.ui.resolve and $.ui.toast for the pane, band and toasts, $.command.register for /gsd-status and /gsd-board, and $.prompt.suggest (a dim suggestion in the empty prompt box: it cannot send anything).
  • Hooks it listens to: session.start, turn.start, turn.step, turn.complete, tool.call and agent.spawn (to count edits and errors, count an agent's responses and record how long it ran, and note forks; it never changes or blocks a call), command.run, ui.render and ui.close.

It writes no files, runs no processes and makes no network calls. Check it yourself: claude plugin validate .claude-plugin/plugin.json prints the hooks and the $ calls the module makes.

🧩 Compatibility with other mods

Tested on Claude Code 2.1.288 with quota-meter and limit-watch loaded together with this plugin: all three load without errors and each draws in its own place (they use the pinned status line and a pane; this uses the AbovePrompt band).

The AbovePrompt band and the hint line are shared. This plugin keeps whatever other mods draw there: it draws what is below it in the chain and puts its line on top, and it appends its hint tail after another mod's tail. A mod that answers without calling next hides every mod after it in load order; if such a mod loads before this one, its band is the only one shown, and that is the other mod's behaviour.

🧪 Try it from a clone

Needs Claude Code 2.1.287 or later (claude --version). There is nothing to build: the plugin is TypeScript 7, loaded by Claude Code from its folder as is, for one session.

git clone https://github.com/helenkwok/gsd-status-mod ~/gsd-status-mod cd <a GSD project> # it reads .planning from the folder you start claude in (or its main checkout, in a worktree) claude --plugin-dir ~/gsd-status-mod

To check the plugin itself (Node 24 or later): cd ~/gsd-status-mod, then

npm ci npm test # node:test on tests/*.spec.ts (Node runs the .ts directly) npm run lint # oxlint npm run check # tsc (TypeScript 7) and oxlint's type-aware rules claude plugin validate . # the marketplace file claude plugin validate .claude-plugin/plugin.json # the hooks and $ calls

The tests include a README check: every key, command, option and image the code has must be in this file. npm run check needs .claude-plugin/types/, which Claude Code writes when it loads the mod from this folder; those files are not in git, so CI runs the tests and the plain lint only. ESLint is not used: typescript-eslint does not support TypeScript 7 yet.

❓ FAQ

The pane does not show. It needs a GSD project (.planning/STATE.md with gsd_state_version, or a workstream) and a terminal at least 144 columns wide. /gsd-board opens it.

The GSD · line above the prompt is missing. It is hidden while the pane is open, and the engine drops it in a terminal under about 16 rows. The hint tail and the suggestion are unaffected.

A link under a reply or tool row does nothing. Clicks reach a mod only in Claude Code's fullscreen terminal.

Does it work on Windows? The pane has been used in a workstream project on Windows; the other features have not been tried there.

🚧 Not handled yet

A session in a worktree shows the main checkout's .planning, which is wrong if that worktree is on a different phase. Background: open-gsd/gsd-core#5174 (a maintainer asked to revisit in-tree support in November 2026; this plugin is the out-of-tree route).

📝 Changelog and license

Release notes: CHANGELOG.md. MIT, see LICENSE. Not affiliated with Anthropic.

Source 5 files
hooks/gsd-status.ts 629 lines
1import { frontmatter, isGsdState, resumeLine, handoffInfo, driftNote, statusReport, pickWorkstream } from "./state-line.ts";
2import { addRun, typical, forecast, dur } from "./history.ts";
3import { panelModel, streamInfo, commitCount, commitFeed, shortPath, planShape, clock } from "./panel.ts";
4import type { EngineInterface, On, PluginOptions, PressedLink, TurnCompleteInput } from "claude-code";
5import type { Agent, Expand, Handoff, Line, Live, Reader, Run, Segment, Stream, Usage, Workstream } from "./types.ts";
6
7// The command named by the handoff's next_action (see nextCommand) is offered as a dim suggestion: Tab puts it in the
8// prompt box and nothing runs until the person presses Enter. No command named, no suggestion.
9
10// Module state: the render hooks only read these, never touch the file system.
11let rows: { resume: string | null; drift: string | null; handoff: string | null; command: string | null } = { resume: null, drift: null, handoff: null, command: null };
12let suggested = false;
13let panePlaced = false; // true while our pane is on screen: the band above the prompt would only repeat it
14let openOnStart = true;
15let isGsd = false;
16let live = freshLive(); // what the pane draws: events of this session plus what the last refresh read
17let lastRefreshAt = 0;
18const seen = new Map<string, { since: number; status: string; endedAt: number | null }>(); // agent id -> { since, status, endedAt }: when this module first saw it, and how it last stood
19let hist: Run[] = []; // what finished agents of this project left behind (see history.ts), kept in $.store across sessions
20let histLoaded = false;
21const steps = new Map<string, number>(); // agent id -> how many model responses it has made so far
22const forks = new Set<string>(); // ids of agents started as forks of their parent (only the spawn event says so)
23const PANE = "gsd-board";
24// What the person has opened in the pane by clicking (or pressing a hotkey): agent rows, finished agents, blockers, streams, log.
25let reader: Reader | null = null; // the markdown reader: { path, isFile, entries | text }, or null for the dashboard
26const expand: Required<Expand> = { agents: new Set(), roadmap: false, pace: false, trends: false, timeline: false, toc: false, finished: false, blockers: false, streams: new Set(), log: false };
27let toasts = true; // short notices (an agent far over its usual time, a phase that will not fit the window, drift)
28const told = new Set<string>(); // agent ids already toasted about
29let lastLevel: string | null | undefined; // how the phase fit the 5-hour window at the last look: undefined (not yet seen), null, "amber" or "warn"
30let lastDrift: string | null | undefined; // the drift note at the last look
31let cluster: { p0: number | null; r0: string | null; ids: Set<string>; ok: boolean } | null = null; // the agents that overlapped, for measuring quota: { p0, r0, ids, ok }; it closes when none is running
32const qOf = new Map<string, { q: number; n: number }>(); // agent id -> { q, n } once its cluster has closed
33const runOf = new Map<string, Run>(); // agent id -> its row in `hist`, so a quota measured after the row was written can be filled in
34const PANE_SIZE = { columns: 64, rows: 16 };
35const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
36const STREAMS = ["phases", "spikes", "threads", "quick", "todos", "seeds", "notes"];
37
38// A press on one of the pane's buttons: flip what it names. The key says which: "agent:<id>", "stream:<name>", or a word.
39function flip(key: string): void {
40  if (key === "ws") {
41    const n = wsInfo?.names ?? [];
42    if (n.length > 1) wsChoice = n[(n.indexOf(wsInfo!.name) + 1) % n.length]!; // names come from wsInfo
43    return;
44  }
45  const [kind = "", id] = String(key).split(/:(.*)/s);
46  const set = kind === "agent" ? expand.agents : kind === "stream" ? expand.streams : null;
47  if (set) { if (!set.delete(id!)) set.add(id!); return; } // id: "agent:" and "stream:" keys carry one
48  const flags: Record<string, unknown> = expand; // the on/off switches, by name
49  if (kind in flags && typeof flags[kind] === "boolean") flags[kind] = !flags[kind];
50}
51
52function freshLive(): Live {
53  return { state: null, roadmap: null, plans: [], workstream: null, handoff: null, usage: null, agents: [], streams: [], log: [], isRunning: false, turn: null, receipt: null,
54    commits: 0, newest: null, startCommits: 0, startCost: null };
55}
56
57function note(kind: string, text: string, at: number): void {
58  live.log = [...live.log, { at, kind, text }].slice(-40);
59}
60
61// Paths are read from the session root, not the current directory: Bash can `cd` anywhere, and a cwd-relative
62// ".planning/STATE.md" then goes missing and the pane flips to "No GSD project here".
63let root = "";
64let planRoot = ""; // where .planning lives: the session root, or the main checkout when the session is in a linked worktree
65const at = (path: string): string => {
66  const base = path.startsWith(".planning") ? planRoot || root : root;
67  return base ? `${base}/${path}` : path;
68};
69// Workstream mode: STATE.md, ROADMAP.md and the work streams live under .planning/workstreams/<name>/.
70let wsBase = ""; // "" for a normal project, else ".planning/workstreams/<name>"
71let wsChoice = ""; // the workstream the person picked in the pane
72let wsInfo: Workstream | null = null; // { name, index, total, names }
73const plan = (name: string): string => `${wsBase || ".planning"}/${name}`;
74const read = ($: EngineInterface, path: string): Promise<string | null> => $.fs.read(at(path)).catch(() => null);
75async function resolvePlan($: EngineInterface): Promise<void> {
76  wsBase = ""; wsInfo = null;
77  if ((await read($, ".planning/STATE.md")) != null) return;
78  const dirs = (await $.fs.list(at(".planning/workstreams")).catch(() => [])).filter((e) => e.kind === "dir" && !e.name.startsWith("."));
79  const cands: { name: string; mtimeMs: number }[] = [];
80  for (const d of dirs) {
81    const st = await $.fs.stat(at(`.planning/workstreams/${d.name}/STATE.md`)).catch(() => null);
82    if (st) cands.push({ name: d.name, mtimeMs: st.mtimeMs ?? 0 });
83  }
84  const pick = pickWorkstream(cands, (await read($, ".planning/active-workstream")) ?? "", wsChoice);
85  if (pick) { wsInfo = pick; wsBase = `.planning/workstreams/${pick.name}`; }
86}
87
88async function findRoot($: EngineInterface): Promise<void> {
89  if (root) return;
90  root = String((await $.session.root().catch(() => "")) ?? "").replace(/\/+$/, "");
91  // A linked worktree has no .planning of its own: its .git file points into <main>/.git/worktrees/<name>.
92  if (root && (await read($, ".planning/STATE.md")) == null) {
93    const ptr = await read($, ".git");
94    const main = /^gitdir:\s*(.+?)[\\/]\.git[\\/]worktrees[\\/][^\\/\s]+\s*$/m.exec(ptr ?? "")?.[1];
95    if (main && ((await $.fs.read(`${main}/.planning/STATE.md`).catch(() => null)) != null || (await $.fs.list(`${main}/.planning/workstreams`).catch(() => [])).length)) planRoot = main;
96  }
97}
98
99// The reflog lives in .git/logs/HEAD; in a linked worktree .git is a file pointing at the real git dir.
100async function reflog($: EngineInterface): Promise<string | null> {
101  const direct = await read($, ".git/logs/HEAD");
102  if (direct != null) return direct;
103  const ptr = await read($, ".git");
104  const dir = ptr && /^gitdir:\s*(.+)$/m.exec(ptr)?.[1]?.trim();
105  return dir ? read($, `${dir}/logs/HEAD`) : null;
106}
107
108async function readUsage($: EngineInterface): Promise<Usage | null> {
109  const u = await $.session.usage().catch(() => null);
110  if (!u) return null;
111  return { pct: u.context?.percent ?? null, tokens: u.context?.tokens ?? null, window: u.context?.window ?? null, costUsd: u.cost?.usd ?? null,
112    limits: (u.rateLimits ?? []).map((r) => ({ kind: r.kind, pct: r.percentUsed, resetsAt: r.resetsAt })) };
113}
114
115const five = (u: Usage | null) => (u?.limits ?? []).find((l) => /five|5h/i.test(l.kind) && Number.isFinite(l.pct)) ?? null;
116
117// Quota per executor, measured over the stretch in which executors overlapped: how far the 5-hour window rose, divided by how many
118// ran. One executor alone and a wave of three both give a per-executor figure. Anything but executors in the stretch (or a window
119// reset, or no window) and it is not measured. ponytail: the main conversation and other sessions add to the rise too, so the
120// figure is shown as a range once enough runs agree; per-agent token weighting would need the usage of each run's own rows.
121async function trackCluster($: EngineInterface, agents: Agent[]): Promise<void> {
122  const running = agents.filter((a) => a.status === "running" && a.type);
123  if (running.length && !cluster) {
124    const f = five(live.usage);
125    cluster = { p0: f?.pct ?? null, r0: f?.resetsAt ?? null, ids: new Set(), ok: f != null };
126    qOf.clear(); runOf.clear();
127  }
128  if (cluster) for (const a of running) { cluster.ids.add(a.id); if (String(a.type).replace(/^gsd-/, "") !== "executor") cluster.ok = false; }
129  if (running.length || !cluster) return;
130  const f = five(live.usage), n = cluster.ids.size;
131  const q = cluster.ok && n && f && f.resetsAt === cluster.r0 && f.pct >= cluster.p0! ? Math.round(((f.pct - cluster.p0!) / n) * 100) / 100 : -1;
132  let patched = false;
133  for (const id of cluster.ids) {
134    qOf.set(id, { q, n });
135    const row = runOf.get(id);
136    if (row) { row[8] = q; row[9] = n; patched = true; }
137  }
138  cluster = null;
139  if (patched) await $.store.set(histKey(), { v: 1, runs: hist }).catch(() => {});
140}
141
142// Short notices, each said once: an agent more than twice its usual time, the phase's fit to the window getting worse, drift appearing.
143function toast($: EngineInterface, text: string): void {
144  if (toasts) void Promise.resolve($.ui.toast(String(text).slice(0, 200))).catch(() => {});
145}
146function alerts($: EngineInterface, now: number): void {
147  for (const a of live.agents) {
148    if (a.status !== "running" || !a.since || told.has(a.id)) continue;
149    const typ = typical(hist, a.type);
150    if (typ && now - a.since > 2 * typ && now - a.since > 60000) { told.add(a.id); toast($, `${String(a.type).replace(/^gsd-/, "")} has run ${clock(now - a.since)}, usually ${clock(typ)}`); }
151  }
152  const fc = forecast(planShape(live.plans), hist, live.agents, now, live.usage?.limits);
153  const level = fc?.level ?? null;
154  if (fc && level && level !== lastLevel) { // level is set only when fc is
155    toast($, fc.quota ? `${fc.open} plans left would take the 5h window to about ${Math.round(fc.quota.end)}%${level === "warn" ? ", it may run out" : ""}`
156      : `about ${dur(fc.ms)} of work left, the 5h window resets in ${dur(Math.max(0, fc.resetMs!))}`); // amber without quota: resetMs is known
157  }
158  lastLevel = level;
159  if (lastDrift !== undefined && rows.drift && !lastDrift) toast($, rows.drift);
160  lastDrift = rows.drift;
161}
162
163// Live agents, with when each was first seen and, as they finish, a line in the log.
164async function readAgents($: EngineInterface, now: number): Promise<Agent[]> {
165  const listed = await $.agent.list().catch(() => []);
166  const agents = listed.map((a) => {
167    const before = seen.get(a.id);
168    const rec = before ?? { since: now, status: a.status, endedAt: null };
169    if (before && before.status === "running" && a.status !== "running") {
170      rec.endedAt = now;
171      const bad = a.status === "failed" || a.status === "killed";
172      note(bad ? "fail" : "done", `${String(a.type).replace(/^gsd-/, "")} ${Math.round((now - rec.since) / 1000)}s`, now);
173    }
174    rec.status = a.status;
175    seen.set(a.id, rec);
176    return { ...a, since: rec.since, endedAt: rec.endedAt, isFork: forks.has(a.id) };
177  });
178  return agents;
179}
180
181// The current phase's plans and whether each is done, for the pace box. The phase folder is matched by number (04 is 4,
182// 02.1 is 2.1); a plan is done when its NN-MM-SUMMARY.md exists; a plan with no `wave:` is left out.
183async function readPlans($: EngineInterface, state: string): Promise<Live["plans"]> {
184  const num = String(frontmatter(state)?.current_phase ?? "").replace(/^0+(?=\d)/, "");
185  if (!num) return [];
186  const dirs = await $.fs.list(at(plan("phases"))).catch(() => []);
187  const dir = dirs.find((e) => e.kind === "dir" && (e.name.split("-")[0] ?? "").replace(/^0+(?=\d)/, "") === num);
188  if (!dir) return [];
189  const base = `${plan("phases")}/${dir.name}`;
190  const files = await $.fs.list(at(base)).catch(() => []);
191  const out: Live["plans"] = [];
192  for (const f of files) {
193    const id = /^(.*)-PLAN\.md$/.exec(f.name)?.[1];
194    if (!id) continue;
195    const wave = Number(frontmatter((await read($, `${base}/${f.name}`)) ?? "")?.wave);
196    if (wave) out.push({ id, wave, done: files.some((x) => x.name === `${id}-SUMMARY.md`) });
197  }
198  return out;
199}
200
201const histKey = () => `runs:${root}`;
202
203async function loadHist($: EngineInterface): Promise<void> {
204  if (histLoaded) return;
205  histLoaded = true;
206  const h = (await $.store.get(histKey()).catch(() => null)) as { runs?: Run[] } | null; // what recordRun stored
207  hist = Array.isArray(h?.runs) ? h.runs : [];
208}
209
210// An agent's run ended: keep its numbers (no description, no text). Internal agents have no type and are skipped.
211async function recordRun($: EngineInterface, e: TurnCompleteInput): Promise<void> {
212  const a = live.agents.find((x) => x.id === e.agentId);
213  if (!a?.type || !(e.durationMs > 0)) return;
214  const u: Partial<NonNullable<TurnCompleteInput["usage"]>> = e.usage ?? {};
215  const now = await $.clock.now(); // awaited first: agents that end together must not read `hist` before one another's update lands
216  const m = qOf.get(e.agentId!); // agentId: `a` was found by it. The quota, when this agent's cluster closed before its row was written
217  const row: Run = [now, a.type, String(frontmatter(live.state ?? "")?.current_phase ?? ""), e.durationMs, steps.get(e.agentId!) ?? 0,
218    (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0), u.output_tokens ?? 0, u.model ?? "", m?.q ?? -1, m?.n ?? 0];
219  hist = addRun(hist, row);
220  runOf.set(e.agentId!, row);
221  steps.delete(e.agentId!);
222  await $.store.set(histKey(), { v: 1, runs: hist }).catch(() => {});
223}
224
225async function readStreams($: EngineInterface): Promise<Stream[]> {
226  const out: Stream[] = [];
227  for (const name of STREAMS) {
228    // In workstream mode the project-wide folders (threads, spikes, seeds...) stay at .planning/, beside the workstream's own.
229    const here = await $.fs.list(at(plan(name))).catch(() => []);
230    const top = wsBase ? await $.fs.list(at(`.planning/${name}`)).catch(() => []) : [];
231    const info = streamInfo([...here.map((e) => ({ ...e, from: plan(name) })), ...top.map((e) => ({ ...e, from: `.planning/${name}` }))]);
232    if (info) out.push({ name, ...info });
233  }
234  return out;
235}
236
237// Everything the band, the hint and the pane need. The work streams are listed only when `full` (they change rarely).
238async function refresh($: EngineInterface, full = true): Promise<void> {
239  await findRoot($);
240  await loadHist($);
241  await resolvePlan($);
242  const now = await $.clock.now();
243  lastRefreshAt = now;
244  const state = await read($, plan("STATE.md"));
245  isGsd = state != null && isGsdState(state);
246  const handoffText = isGsd ? (await read($, plan("HANDOFF.json"))) ?? (wsBase ? await read($, ".planning/HANDOFF.json") : null) : null;
247  const handoff = handoffText == null ? null : handoffInfo(handoffText, now);
248  rows = { resume: isGsd ? resumeLine(state!) : null, handoff: handoff?.line ?? null, command: handoff?.command ?? null, drift: null };
249  if (!isGsd) { live = freshLive(); $.ui.invalidate("ui.render"); return; }
250
251  let parsed: Handoff | null = null;
252  try { parsed = handoffText == null ? null : JSON.parse(handoffText); } catch { /* unreadable: no handoff rows */ }
253  const log = await reflog($);
254  if (log != null) {
255    if (rows.resume && /^state_head:/m.test(state!)) rows.drift = driftNote(state!, log); // isGsd: state was read
256    const feed = commitFeed(log, 5);
257    if (live.newest && feed.length && feed[0]!.hash !== live.newest) {
258      const fresh = [];
259      for (const c of feed) { if (c.hash === live.newest) break; fresh.push(c); }
260      for (const c of fresh.reverse()) note("commit", `${c.hash} ${c.msg}`, now);
261    }
262    live.newest = feed[0]?.hash ?? live.newest;
263    live.commits = commitCount(log);
264  }
265  live.state = state;
266  live.workstream = wsInfo;
267  live.handoff = parsed;
268  live.usage = await readUsage($);
269  live.agents = await readAgents($, now);
270  await trackCluster($, live.agents);
271  if (full) { live.streams = await readStreams($); live.roadmap = await read($, plan("ROADMAP.md")); live.plans = await readPlans($, state!); }
272  alerts($, now);
273  $.ui.invalidate("ui.render"); // render output is cached until invalidated
274}
275
276// /gsd-status: the full report, read fresh from disk each time so it is never behind the band.
277async function report($: EngineInterface): Promise<string> {
278  await findRoot($);
279  await resolvePlan($);
280  const state = await read($, plan("STATE.md"));
281  const ok = state != null && isGsdState(state);
282  const handoff = ok ? (await read($, plan("HANDOFF.json"))) ?? (wsBase ? await read($, ".planning/HANDOFF.json") : null) : null;
283  let drift = null;
284  if (ok && /^state_head:/m.test(state)) {
285    const log = await reflog($);
286    if (log != null) drift = driftNote(state, log);
287  }
288  return statusReport(state, handoff, await $.clock.now(), drift).text;
289}
290
291// At most every 2 seconds, and not awaited by the hooks that call it, so it never slows a tool call down.
292async function soon($: EngineInterface): Promise<void> {
293  const now = await $.clock.now();
294  if (!isGsd || now - lastRefreshAt < 2000) return;
295  await refresh($, false).catch(() => {});
296}
297
298// Once a second while the pane is open and something is running: redraw so the clocks move, and every 5 seconds
299// re-read agents and commits, since an agent can end without a hook of ours firing.
300// While idle: a full re-read every 15 seconds, so work done by another session (or by hand) shows up without a prompt.
301// Not a file watch: seeds, workstream switches and files added inside a phase folder would slip past one (issue #1).
302async function tick($: EngineInterface): Promise<void> {
303  if (!isGsd) return;
304  const now = await $.clock.now();
305  if (!live.isRunning && !live.agents.some((a) => a.status === "running")) {
306    if (now - lastRefreshAt >= 15000) await refresh($).catch(() => {});
307    return;
308  }
309  if (!panePlaced) return;
310  if (now - lastRefreshAt >= 5000) await refresh($, false).catch(() => {});
311  else $.ui.invalidate("ui.render");
312}
313
314// The reader opens a folder listing or one file; path is a ".planning/..." path, so it can never leave .planning.
315// A symlink inside .planning may point anywhere, so the reader opens a path only if its real location is still under
316// .planning's own real location (.planning itself is often a symlink to the external store).
317async function insidePlanning($: EngineInterface, p: string): Promise<boolean> {
318  const norm = (s: string | undefined): string => String(s ?? "").replace(/\\/g, "/");
319  const [base, target] = await Promise.all([".planning", p].map((x) => $.fs.stat(at(x), { resolve: true }).catch(() => null)));
320  const b = norm(base?.realPath), r = norm(target?.realPath);
321  return Boolean(b && r && (r === b || r.startsWith(b + "/")));
322}
323
324async function openReader($: EngineInterface, path: string): Promise<void> {
325  const parts = String(path).split("/").filter((x) => x && x !== ".");
326  if (parts[0] !== ".planning" || parts.includes("..")) return;
327  const p = parts.join("/");
328  if (!(await insidePlanning($, p))) return;
329  const entries = await $.fs.list(at(p)).catch(() => null);
330  expand.toc = false;
331  if (entries) reader = { path: p, isFile: false, entries };
332  else {
333    const text = await read($, p);
334    if (text == null) return;
335    reader = { path: p, isFile: true, text };
336  }
337  $.ui.invalidate("ui.render");
338}
339
340// A link inside the open file -> the .planning path it points at, or null (not a relative .md link, or outside .planning).
341// It lives here, not in panel.ts: a press handler runs where only this file's own functions are visible, not imported names.
342export function resolveLink(from: string, href: string | null | undefined): string | null {
343  const h = String(href ?? "").split("#")[0];
344  if (!h || h.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(h) || !/\.md$/i.test(h)) return null;
345  const parts = String(from).split("/").slice(0, -1);
346  for (const seg of h.split("/")) { if (seg === "..") parts.pop(); else if (seg && seg !== ".") parts.push(seg); }
347  return parts[0] === ".planning" ? parts.join("/") : null;
348}
349
350// A click on a link in the open file: a relative .md link opens in the reader; anything else is left alone.
351async function linkPress($: EngineInterface, href: string): Promise<void> {
352  const t = reader && resolveLink(reader.path, href);
353  if (t) await openReader($, t);
354}
355
356// Brings the element with this key into view (null: the top), trying again while a pane that just changed is not drawn yet.
357async function scrollTo($: EngineInterface, key: string | null): Promise<void> {
358  try {
359    await $.clock.sleep(120);
360    for (let n = 0; n < 8; n++) {
361      const r = await $.ui.scroll({ in: PANE, to: key ? { key } : "start", block: "start" }).catch((err) => ({ deny: String(err) }));
362      if (!r?.deny) return;
363      await $.clock.sleep(80);
364    }
365  } catch { /* the module reloaded: the pane stays where it is */ }
366}
367
368// A path inside this project's .planning -> ".planning/..." (what the reader opens), else null.
369// ponytail: a file read through the external store's own path (.planning is usually a symlink to it) gets no link.
370function planRel(file: string | null | undefined): string | null {
371  const f = String(file ?? "").replace(/\\/g, "/"), base = String(planRoot || root).replace(/\\/g, "/");
372  return base && f.startsWith(`${base}/.planning/`) ? f.slice(base.length + 1) : null;
373}
374
375// Markdown file names a reply mentions, as written: `.planning/threads/x.md`, `phases/04-x/04-01-PLAN.md`, a bare
376// `04-01-PLAN.md`, an absolute path or a Windows one; a `:line` after it and web links are left out. -> [string]
377export function docRefs(text: string | null | undefined): string[] {
378  const out = new Set<string>();
379  for (const m of String(text ?? "").matchAll(/(?:https?:\/\/\S*)|((?:[A-Za-z]:)?[\w.~/\\-]*?[\w-]+\.md)(?![\w-])/gi)) if (m[1]) out.add(m[1]);
380  return [...out];
381}
382
383// A name from a reply -> the ".planning/..." path of an existing file it means, or null. Bare names must match one file.
384let docIndex: Map<string, string[]> | null = null, docIndexAt = 0;
385async function docTarget($: EngineInterface, ref: string): Promise<string | null> {
386  const t = ref.replace(/\\/g, "/");
387  const isFile = async (rel: string): Promise<boolean> => (await $.fs.stat(at(rel)).catch(() => null))?.kind === "file";
388  const i = t.lastIndexOf(".planning/");
389  const tries = i >= 0 ? [t.slice(i)] : /^([a-z]:)?\/|^~/i.test(t) ? [] : t.includes("/") ? [`.planning/${t}`, ...(wsBase ? [`${wsBase}/${t}`] : [])] : null;
390  if (tries) { for (const rel of tries) if (!rel.includes("..") && (await isFile(rel))) return rel; return null; }
391  const now = await $.clock.now();
392  if (!docIndex || now - docIndexAt > 60000) { // ponytail: one walk of .planning a minute, 5 deep and 4000 files at most
393    docIndex = new Map(); docIndexAt = now;
394    let n = 0;
395    const walk = async (dir: string, depth: number): Promise<void> => {
396      for (const e of await $.fs.list(at(dir)).catch(() => [])) {
397        if (e.name.startsWith(".") || ++n > 4000) continue;
398        const rel = `${dir}/${e.name}`;
399        if (e.kind === "dir" && depth < 5) await walk(rel, depth + 1);
400        else if (/\.md$/i.test(e.name)) docIndex!.set(e.name, [...(docIndex!.get(e.name) ?? []), rel]); // set just above
401      }
402    };
403    await walk(".planning", 1);
404  }
405  const hits = docIndex.get(t) ?? [];
406  return hits.length === 1 ? hits[0]! : null;
407}
408
409// A click on the "open in the GSD reader" line under a tool row in the transcript: show the pane and open that file.
410async function fromTranscript($: EngineInterface, href: string): Promise<void> {
411  const rel = planRel(decodeURIComponent(String(href).replace(/^file:\/\//, "")));
412  if (!rel) return;
413  await openPane($).catch(() => {});
414  await openReader($, rel);
415}
416
417async function readerPress($: EngineInterface, key: string): Promise<void> {
418  const [, kind, arg = ""] = /^reader:([^:]+):?(.*)$/s.exec(key) ?? [];
419  if (kind === "browse") return openReader($, ".planning");
420  if (kind === "open-path") return openReader($, arg);
421  if (!reader) return;
422  if (kind === "top") return void (await $.ui.scroll({ in: PANE, to: "start" }));
423  if (kind === "toc") { expand.toc = !expand.toc; $.ui.invalidate("ui.render"); return; }
424  if (kind === "goto") { expand.toc = false; $.ui.invalidate("ui.render"); return void (await scrollTo($, `sec${arg}`)); }
425  if (kind === "close") { reader = null; $.ui.invalidate("ui.render"); return; }
426  if (kind === "open") return openReader($, `${reader.path}/${arg}`);
427  if (kind === "up") {
428    if (!reader.isFile && reader.path === ".planning") { reader = null; $.ui.invalidate("ui.render"); return; }
429    return openReader($, reader.path.split("/").slice(0, -1).join("/"));
430  }
431}
432
433async function openPane($: EngineInterface) {
434  const r = await $.ui.open({ id: PANE, title: "GSD", ...PANE_SIZE });
435  panePlaced = r.isPlaced;
436  return r;
437}
438
439export function register(on: On, options: PluginOptions): void {
440  openOnStart = options?.openOnStart !== false;
441  toasts = options?.toasts !== false;
442  on("session.start", async ($, e, next) => {
443    // A host without commands just goes without the report and the toggle; the band and hint do not depend on them.
444    try {
445      await $.command.register({ name: "gsd-status", description: "Where this GSD project stands: phase, progress, handoff, blockers" });
446      await $.command.register({ name: "gsd-board", description: "Show or hide the live GSD pane", argumentHint: "[close]" });
447    } catch { /* no command support here */ }
448    if (e.isInteractive) $.clock.every(1000, () => void tick($));
449    await refresh($);
450    if (isGsd && openOnStart) { try { await openPane($); } catch { /* not placed: /gsd-board opens it */ } }
451    // Once per session, and only when the handoff names a command: propose it in the empty prompt box.
452    if (rows.command && !suggested) {
453      suggested = true;
454      await $.prompt.suggest({ text: rows.command }).catch(() => {});
455    }
456    return next(e);
457  });
458  on("command.run", { command: "gsd-status" }, async ($) => ({ text: await report($) }));
459  on("command.run", { command: "gsd-board" }, async ($, e) => {
460    if ((e.args ?? "").trim() === "close") { await $.ui.close({ id: PANE }); panePlaced = false; return { text: "GSD pane closed." }; }
461    if (!isGsd) return { text: "No GSD project here: nothing to show." };
462    const r = await openPane($);
463    return { text: r.isPlaced ? "GSD pane opened. /gsd-board close hides it." : `The GSD pane is not shown: ${r.reason}` };
464  });
465
466  // The pane is driven by the session's own events.
467  on("turn.start", async ($, e, next) => {
468    const out = await next(e);
469    if (isGsd && !(e as { agentId?: string }).agentId) { // not in the declared event: kept as it was
470      const now = await $.clock.now();
471      live.isRunning = true;
472      live.turn = { startedAt: now, edits: 0, errors: 0 };
473      live.startCommits = live.commits;
474      live.startCost = live.usage?.costUsd ?? null;
475      // A finished background agent reports back as a turn that opens with <agent-message>: the agent's own "done" line says that.
476      if (e.text && !String(e.text).trimStart().startsWith("<")) note("prompt", String(e.text).replace(/\s+/g, " ").trim(), now);
477      void soon($);
478    }
479    return out;
480  });
481  on("tool.call", async ($, e, next) => {
482    const out = await next(e);
483    if (isGsd && e.tool !== "Agent") {
484      const now = await $.clock.now();
485      const failed = out?.isError === true;
486      const isEdit = EDIT_TOOLS.has(e.tool) && !failed && out?.deny === undefined;
487      if (live.turn && !e.agentId) {
488        if (isEdit) live.turn.edits += 1;
489        if (failed) live.turn.errors += 1;
490      }
491      if (isEdit) note("write", shortPath(e.file_path ?? (e.input as { file_path?: unknown } | undefined)?.file_path ?? e.notebook_path ?? ""), now);
492      else if (failed) note("error", String(e.tool), now);
493      void soon($);
494    }
495    return out;
496  });
497  on("agent.spawn", async ($, e, next) => {
498    const out = await next(e);
499    if (isGsd) {
500      if (e.fork && out?.agentId) forks.add(out.agentId);
501      note("spawn", `${e.fork ? "fork " : ""}${String(e.subagentType ?? "agent").replace(/^gsd-/, "")} ${e.description ?? ""}`.trim(), await $.clock.now());
502      void soon($);
503    }
504    return out;
505  });
506  // One response by a subagent = one step; the count is what an agent's "turns" in the history are.
507  on("turn.step", async function* ($, e, next) {
508    if (e.agentId) steps.set(e.agentId, (steps.get(e.agentId) ?? 0) + 1);
509    return yield* next(e);
510  });
511  on("turn.complete", async ($, e, next) => {
512    await refresh($);
513    if (isGsd && e.agentId) await recordRun($, e);
514    if (isGsd && !e.agentId) {
515      const now = await $.clock.now();
516      const t = live.turn;
517      const cost = live.usage?.costUsd ?? null;
518      live.receipt = {
519        durationMs: e.durationMs ?? (t ? now - t.startedAt : 0),
520        edits: t?.edits ?? 0, errors: t?.errors ?? 0,
521        commits: Math.max(0, live.commits - live.startCommits),
522        costDelta: cost != null && live.startCost != null ? cost - live.startCost : null,
523      };
524      live.isRunning = false;
525      live.turn = null;
526      $.ui.invalidate("ui.render");
527    }
528    return next(e);
529  });
530
531  // The person closing the pane with its close mark: the band comes back.
532  on("ui.close", { id: PANE }, async ($, e, next) => { const out = await next(e); panePlaced = false; return out; });
533
534  // The pane: a bordered box per topic, the way the engine's own panes are drawn.
535  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
536    const { Box, Text, Button, Markdown } = $.ui.resolve(e);
537    if (!isGsd) return Text({ dimColor: true, children: "No GSD project here." });
538    const W = Math.max(40, e.props.bodyColumns);
539    const segs = (list: Segment[]) => list.map(([text, color, flags]) => Text({ ...(color ? { color } : {}), ...(flags === "b" ? { bold: true } : {}), children: text }));
540    const press = (key: string) => () => {
541      if (key.startsWith("reader:")) return void readerPress($, key);
542      flip(key);
543      if (key === "ws") void refresh($); else $.ui.invalidate("ui.render");
544    };
545    const link = (k: PressedLink) => void linkPress($, k.href);
546    // A line is plain text, a row with a ▸/▾ button in front, or one whole-line button.
547    const line = (l: Line, i: number) => {
548      if (l.md !== undefined) return Markdown({ key: l.key ?? `md${i}`, text: l.md, onLinkPress: link });
549      if (Array.isArray(l)) return Text({ wrap: "truncate", children: segs(l) });
550      if (l.toggle) {
551        return Box({ flexDirection: "row", children: [
552          Button({ key: l.toggle.key, label: l.toggle.open ? "▾" : "▸", plain: true, ...(l.toggle.hotkey ? { hotkey: l.toggle.hotkey } : {}), onPress: press(l.toggle.key) }),
553          Text({ children: " " }),
554          Text({ wrap: "truncate", children: segs(l.segs ?? []) }),
555        ] });
556      }
557      const b = l.button!; // what is left: a whole-line button
558      return Button({ key: b.key, label: b.label, plain: true, hotkey: b.hotkey, onPress: press(b.key) });
559    };
560    const m = panelModel({ ...live, history: hist, reader, expand, now: await $.clock.now() }, W);
561    return Box({
562      flexDirection: "column", width: W,
563      children: [
564        Box({ justifyContent: "center", children: [Text({ bold: true, wrap: "truncate", children: segs(m.header) })] }),
565        ...m.panels.map((p) => Box({
566          flexDirection: "column", borderStyle: "round", borderColor: p.color, paddingX: 1, width: W,
567          children: [
568            Box({ justifyContent: "space-between", children: [Text({ wrap: "truncate", children: segs(p.title) }), ...(p.right ? [Text({ children: segs(p.right) })] : [])] }),
569            ...p.lines.map(line),
570          ],
571        })),
572      ],
573    });
574  });
575
576  // A tool row that read or wrote a .planning file: the engine's own row, and a line under it that opens the file in the reader.
577  // Clicks reach a mod only in the fullscreen terminal, so elsewhere the row stays as the engine draws it.
578  on("ui.render", { component: "ToolUse" }, async ($, e, next) => {
579    const p = e.props ?? {};
580    const file = (p.input as { file_path?: unknown } | undefined)?.file_path;
581    if (!isGsd || e.surface !== "terminal" || !e.viewport?.isFullscreen || !["Read", "Write", "Edit"].includes(p.tool) || typeof file !== "string" || !/\.md$/i.test(file) || p.isRunning || p.isErrored) return next(e);
582    if (!planRel(file)) return next(e);
583    const { Box, Markdown } = $.ui.resolve(e);
584    const href = "file://" + encodeURI(file).replace(/[#?()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
585    return Box({ flexDirection: "column", children: [
586      await next(e),
587      Box({ paddingLeft: 2, children: [Markdown({ key: "open", dimColor: true, text: `⎿  [open in the GSD reader ↗](${href})`, pressableLinks: [href], onLinkPress: () => void fromTranscript($, href) })] }),
588    ] });
589  });
590
591  // A reply that names .planning documents: the engine's own drawing, and a line under it whose links open them in the reader.
592  on("ui.render", { component: "AssistantMessage" }, async ($, e, next) => {
593    if (!isGsd || e.surface !== "terminal" || !e.viewport?.isFullscreen) return next(e);
594    const rels: string[] = [];
595    for (const ref of docRefs(e.props?.text).slice(0, 12)) { const r = await docTarget($, ref); if (r && !rels.includes(r)) rels.push(r); }
596    if (!rels.length) return next(e);
597    const { Box, Markdown } = $.ui.resolve(e);
598    const href = (rel: string) => "file://" + encodeURI(at(rel).replace(/\\/g, "/")).replace(/[#?()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
599    const hrefs = rels.map(href);
600    const text = `⎿  open in the GSD reader: ${rels.map((r, k) => `[${r.split("/").pop()}](${hrefs[k]})`).join(" · ")}`;
601    return Box({ flexDirection: "column", children: [
602      await next(e),
603      Box({ paddingLeft: 2, children: [Markdown({ key: "docs", dimColor: true, text, pressableLinks: hrefs, onLinkPress: (l) => void fromTranscript($, l.href) })] }),
604    ] });
605  });
606
607  // The band above the prompt: the GSD line, and the drift warning when STATE.md is behind. While the pane is open it
608  // shows the same, so the band stands down.
609  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
610    const below = await next(e); // whatever other mods draw in this band: keep it, add our line on top
611    const { resume, drift } = rows;
612    if (!resume || panePlaced) return below;
613    const { Box, Text } = $.ui.resolve(e);
614    const parts = [Text({ color: "cyan", children: resume })];
615    if (drift) parts.push(Text({ color: "yellow", children: "  " + drift }));
616    const mine = Box({ paddingX: 1, flexDirection: "row", children: parts });
617    return below ? Box({ flexDirection: "column", children: [mine, below] }) : mine;
618  });
619
620  // The line under the prompt: add the handoff's next action to its end, dim. The engine's own line and its pills
621  // stay; another mod's tail is kept and ours follows it. Nothing while typing or while a turn runs.
622  on("ui.render", { component: "PromptHint" }, async ($, e, next) => {
623    const p = e.props ?? {};
624    if (!rows.handoff || p.isDraft || p.isWorking) return next(e);
625    const tail = p.tail ? `${p.tail} · ${rows.handoff}` : rows.handoff;
626    return next({ ...e, props: { ...p, tail } });
627  });
628}
629
hooks/state-line.ts 189 lines
1// Pure: STATE.md text -> one-line summary. No $ access, so it is testable under plain Node.
2import type { Fields, Frontmatter, Handoff, Workstream } from "./types.ts";
3
4export function frontmatter(text: string): Frontmatter | null {
5  const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
6  if (!m) return null;
7  const out: Frontmatter = {};
8  let nested: Fields | null = null;
9  for (const raw of (m[1] ?? "").split(/\r?\n/)) {
10    const line = raw.replace(/\s+$/, "");
11    if (!line || line.trimStart().startsWith("#")) continue;
12    const kv = /^(\s*)([A-Za-z0-9_]+):\s*(.*)$/.exec(line);
13    if (!kv) continue;
14    const [, indent = "", key = "", val = ""] = kv;
15    const v = val.replace(/^["']|["']$/g, "");
16    if (!indent && v === "") { nested = out[key] = {}; continue; }
17    if (indent && nested) nested[key] = v; else { nested = null; out[key] = v; }
18  }
19  return out;
20}
21
22function ago(ms: number): string {
23  const m = Math.floor(ms / 60000);
24  if (m < 1) return "just now";
25  if (m < 60) return `${m}m ago`;
26  const h = Math.floor(m / 60);
27  if (h < 48) return `${h}h ago`;
28  return `${Math.floor(h / 24)}d ago`;
29}
30
31// Free text (stopped_at, next_action) -> something that reads at a glance: the first sentence,
32// else cut at a word boundary. A "." inside a name like PLAN.md or 2026-09-09 is not a sentence end.
33export function summarize(text: unknown, max = 70): string {
34  const s = String(text ?? "").replace(/\s+/g, " ").trim();
35  if (!s) return "";
36  const first = /^(.+?[.!?])(?=\s+[A-Z(]|$)/.exec(s)?.[1] ?? s;
37  const one = first.replace(/[.!?]+$/, "");
38  if (one.length <= max) return one;
39  const cut = one.slice(0, max - 1);
40  const sp = cut.lastIndexOf(" ");
41  return (sp > max * 0.5 ? cut.slice(0, sp) : cut).replace(/[\s,;:–—-]+$/, "") + "…";
42}
43
44// True for a STATE.md that GSD wrote (its frontmatter carries gsd_state_version), not any file with that name.
45export function isGsdState(text: string): boolean {
46  const fm = frontmatter(text);
47  return Boolean(fm && fm.gsd_state_version);
48}
49
50// Where work stopped and how many phases are done. No age: STATE.md's last_updated is touched by tools
51// without the content changing, so "17h ago" can sit beside a stopped_at from weeks earlier.
52// Returns null for a non-GSD file or when there is nothing the GSD statusline lacks.
53export function resumeLine(text: string, max = 70): string | null {
54  const fm = frontmatter(text);
55  if (!fm || !fm.gsd_state_version) return null;
56  const parts: string[] = [];
57  if (fm.stopped_at) parts.push("stopped: " + summarize(fm.stopped_at, max));
58  const p = fm.progress;
59  if (p && p.total_phases) parts.push(`${p.completed_phases ?? 0}/${p.total_phases} phases`);
60  return parts.length ? "GSD · " + parts.join(" · ") : null;
61}
62
63// The command a next_action names, if it names one: the first /gsd-<name>, plus at most one argument that looks like
64// a phase number or version (2, 4.5, v1). Free-text arguments are dropped, so the result is something that can be
65// offered as a suggestion without guessing. null when the text names no command (prose such as "Nothing is pending").
66export function nextCommand(nextAction: string | null | undefined): string | null {
67  const m = /(?<![\w/.~-])(\/gsd-[a-z][a-z0-9-]*)(?:\s+(v?\d+(?:\.\d+)*[a-z]?)(?![\w-]))?/.exec(String(nextAction ?? ""));
68  return m ? m[1] + (m[2] ? " " + m[2] : "") : null;
69}
70
71// HANDOFF.json is the resume note GSD writes on pause. Its next_action is the first thing to read when resuming.
72// The age is the handoff's own timestamp, so unlike STATE.md's it means what it says.
73// Returns { line, command }: the text for the hint line, and the command that text names (or null).
74export function handoffInfo(jsonText: string, now = Date.now(), max = 90): { line: string; command: string | null } | null {
75  let j: Handoff | null;
76  try { j = JSON.parse(jsonText); } catch { return null; }
77  if (!j || typeof j.next_action !== "string" || !j.next_action.trim()) return null;
78  const shown = summarize(j.next_action, max);
79  const parts = ["next: " + shown];
80  const t = j.timestamp ? Date.parse(j.timestamp) : NaN;
81  if (!Number.isNaN(t) && now >= t) parts.push("handoff " + ago(now - t));
82  // The command comes only from the text that is shown, so the Tab suggestion always matches the hint beside it,
83  // and not when the action says to go and do it somewhere else (another session, another directory).
84  const elsewhere = /\b(open|start|launch)\b[^.]*\b(session|terminal|window)\b|~\/|\/Users\//i.test(shown);
85  return { line: parts.join(" · "), command: elsewhere ? null : nextCommand(shown) };
86}
87
88export function handoffLine(jsonText: string, now = Date.now(), max = 90) {
89  return handoffInfo(jsonText, now, max)?.line ?? null;
90}
91
92// Commits made after the one STATE.md was written at, counted from the git reflog text (.git/logs/HEAD),
93// so no git process is needed. null when the reflog does not contain that commit (pruned, rebased, other clone).
94export function commitsSince(reflogText: string, stateHead: unknown): number | null {
95  if (!stateHead || String(stateHead).length < 7) return null; // a short prefix would match unrelated reflog rows
96  const rows = reflogText.split(/\r?\n/).filter(Boolean).map((l) => {
97    const [head = "", msg = ""] = l.split("\t");
98    const [, now] = head.split(" ");
99    return { now, msg };
100  });
101  let at = -1;
102  rows.forEach((r, i) => { if (r.now && r.now.startsWith(String(stateHead))) at = i; });
103  if (at < 0) return null;
104  return rows.slice(at + 1).filter((r) => /^(commit|merge|pull|cherry-pick|revert)/.test(r.msg)).length;
105}
106
107// "⚠ ~217 commits since STATE.md" when STATE.md is well behind the repo, else null. Approximate: the reflog only
108// holds this clone's own HEAD moves, so it undercounts (measured: 124 against 217 from git rev-list).
109export function driftNote(stateText: string, reflogText: string, threshold = 5): string | null {
110  const fm = frontmatter(stateText);
111  if (!fm || !fm.gsd_state_version || !fm.state_head) return null;
112  const n = commitsSince(reflogText, fm.state_head);
113  return n != null && n >= threshold ? `⚠ ~${n} commits since STATE.md` : null;
114}
115
116// Free-form lists in HANDOFF.json (blockers, human_actions_pending, remaining_tasks) come as strings or as objects
117// with some text field. Show each as one line of text; anything unreadable is skipped rather than guessed at.
118export function items(v: unknown): string[] {
119  if (v == null || v === "") return [];
120  const list = Array.isArray(v) ? v : [v];
121  return list
122    .map((x: unknown) => { const o = x as Record<string, unknown>; return typeof x === "string" ? x : x && typeof x === "object" ? (o.description ?? o.text ?? o.title ?? o.task ?? o.name ?? "") : String(x); })
123    .map((s) => summarize(s, 110))
124    .filter(Boolean);
125}
126
127function listBlock(label: string, v: unknown): string[] {
128  const all = items(v);
129  if (!all.length) return [];
130  return [`${label} (${all.length})`, ...all.map((s) => "  - " + s)];
131}
132
133// The full resume report for the /gsd-status command: everything the band and hint compress, in plain lines.
134// Pure. stateText may be null (no STATE.md), handoffText may be null (no HANDOFF.json), driftText is driftNote's output.
135// Returns { text, isGsd }: isGsd is false when there is no GSD STATE.md here, and text then says so.
136export function statusReport(stateText: string | null, handoffText: string | null, now = Date.now(), drift: string | null = null): { text: string; isGsd: boolean } {
137  const fm = stateText == null ? null : frontmatter(stateText);
138  if (!fm || !fm.gsd_state_version) {
139    return { isGsd: false, text: "No GSD project here: .planning/STATE.md is missing or has no gsd_state_version." };
140  }
141  const out = ["GSD status"];
142  const phase = [fm.current_phase && `phase ${fm.current_phase}`, fm.current_phase_name].filter(Boolean).join(" · ");
143  if (phase) out.push("Now: " + phase + (fm.status ? ` (${fm.status})` : ""));
144  else if (fm.status) out.push("Status: " + fm.status);
145  const p = fm.progress;
146  if (p) {
147    const bits = [];
148    if (p.total_phases) bits.push(`${p.completed_phases ?? 0}/${p.total_phases} phases`);
149    if (p.total_plans) bits.push(`${p.completed_plans ?? 0}/${p.total_plans} plans`);
150    if (bits.length) out.push("Progress: " + bits.join(" · "));
151  }
152  if (fm.stopped_at) out.push("Stopped at: " + summarize(fm.stopped_at, 220));
153  if (drift) out.push(drift);
154
155  let j: Handoff | null = null;
156  try { j = handoffText == null ? null : JSON.parse(handoffText); } catch { /* unreadable handoff: say so below */ }
157  if (handoffText != null && !j) out.push("", "HANDOFF.json is present but is not valid JSON.");
158  if (j && typeof j === "object") {
159    const t = j.timestamp ? Date.parse(j.timestamp) : NaN;
160    const age = !Number.isNaN(t) && now >= t ? ` (written ${ago(now - t)})` : "";
161    out.push("", "Handoff" + age);
162    if (typeof j.next_action === "string" && j.next_action.trim()) {
163      out.push("Next: " + summarize(j.next_action, 260));
164      const cmd = nextCommand(summarize(j.next_action, 90));
165      if (cmd) out.push("Command: " + cmd);
166    }
167    out.push(...listBlock("Blockers", j.blockers));
168    out.push(...listBlock("Needs a person", j.human_actions_pending));
169    out.push(...listBlock("Remaining tasks", j.remaining_tasks));
170    const files = items(j.uncommitted_files);
171    if (files.length) out.push(`Uncommitted at pause: ${files.length} file${files.length === 1 ? "" : "s"}`);
172  } else if (handoffText == null) {
173    out.push("", "No HANDOFF.json (nothing was paused with /gsd-pause-work).");
174  }
175  return { isGsd: true, text: out.join("\n") };
176}
177
178// Workstream mode keeps one STATE.md per workstream under .planning/workstreams/<name>/. Which one is "the" project is
179// GSD's own per-session choice, which a mod cannot see, so: the person's pick in the pane, else the name in
180// .planning/active-workstream, else the one that changed most recently.
181// cands: [{ name, mtimeMs }] (only workstreams that have a STATE.md) -> { name, index, total, names } | null
182export function pickWorkstream(cands: { name: string; mtimeMs?: number }[] | null | undefined, marker = "", choice = ""): Workstream | null {
183  const list = [...(cands ?? [])].sort((a, b) => a.name.localeCompare(b.name));
184  if (!list.length) return null;
185  const newest = [...list].sort((a, b) => (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0))[0]!; // list is not empty
186  const hit = list.find((c) => c.name === choice) ?? list.find((c) => c.name === String(marker).trim()) ?? newest;
187  return { name: hit.name, index: list.indexOf(hit) + 1, total: list.length, names: list.map((c) => c.name) };
188}
189
hooks/history.ts 112 lines
1// What a finished agent leaves behind, and what the pace box and the trends view make of it. Pure: no `$`.
2// A run is [endedAtMs, type, phase, durationMs, turns, inTokens, outTokens, model, quota]. Numbers only: no description, no text.
3// `quota` is the points of the 5-hour window one agent used: the window's rise over the stretch in which agents overlapped,
4// divided by how many ran (`width`, the last number). -1: not measurable; both absent in older runs.
5import type { Agent, Limit, PlanShape, Run, Stage } from "./types.ts";
6
7export const KEEP = 300; // runs kept per project, the oldest dropped first
8
9const bare = (t: string | undefined): string => String(t ?? "").replace(/^gsd-/, "");
10const STAGES = {
11  planning: /^(planner|phase-researcher|project-researcher|pattern-mapper|roadmapper)$/,
12  executing: /^(executor|code-fixer)$/,
13  checking: /^(verifier|plan-checker|code-reviewer|ui-checker|security-auditor)$/,
14};
15export const stageOf = (type: string | undefined): Stage => (Object.keys(STAGES) as (keyof typeof STAGES)[]).find((k) => STAGES[k].test(bare(type))) ?? "other";
16
17export const addRun = (runs: Run[] | null | undefined, run: Run): Run[] => [...(runs ?? []), run].slice(-KEEP);
18
19// The median duration of past runs of this agent type, once there are `min` of them, else null.
20export function typical(runs: Run[] | null | undefined, type: string | undefined, min = 5): number | null {
21  const d = (runs ?? []).filter((r) => bare(r[1]) === bare(type)).map((r) => r[3]).sort((a, b) => a - b);
22  return d.length >= min ? (d[(d.length - 1) >> 1]! + d[d.length >> 1]!) / 2 : null;
23}
24
25const pick = (sorted: number[], q: number): number => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]!; // never empty: callers check
26
27// Points of the 5-hour window an agent of this type uses: the median and the middle half of the runs where it was measured
28// cleanly, alone or in a parallel wave. Null under `min` such runs. The account is shared with other sessions and with the
29// main conversation, so this is a range, never one number.
30export type QuotaRange = { n: number; med: number; lo: number; hi: number };
31export function quotaPerRun(runs: Run[] | null | undefined, type = "executor", min = 5): QuotaRange | null {
32  const q = (runs ?? []).filter((r) => bare(r[1]) === bare(type) && (r[8] ?? -1) >= 0).map((r) => r[8]!).sort((a, b) => a - b);
33  return q.length >= min ? { n: q.length, med: pick(q, 0.5), lo: pick(q, 0.25), hi: pick(q, 0.75) } : null;
34}
35
36// What is left of the current phase: executor time (one typical run per open wave, the running executor's time already spent
37// taken off) and, once quota is measured, the points the open plans would add to the 5-hour window.
38// shape: planShape(...); limits: [{ kind, pct, resetsAt }]. Null when nothing is open or executors have no history.
39export type Forecast = {
40  ms: number; waves: number; open: number; nextN: number; runs: number; pct: number | null; resetMs: number | null; level: "warn" | "amber" | null;
41  quota: { add: number; lo: number; hi: number; end: number; endHi: number; n: number; next: { add: number; lo: number; hi: number; end: number } } | null;
42};
43export function forecast(shape: PlanShape | null | undefined, runs: Run[] | null | undefined, agents: Pick<Agent, "type" | "status" | "since">[] | null | undefined, now: number, limits: Limit[] | null | undefined): Forecast | null {
44  const typ = typical(runs, "executor", 3);
45  if (!shape?.open || !typ) return null;
46  const spent = Math.max(0, ...(agents ?? []).filter((a) => a.status === "running" && bare(a.type) === "executor" && a.since).map((a) => now - a.since!)); // since: kept by the filter
47  const five = (limits ?? []).find((l) => /five|5h/i.test(l.kind) && Number.isFinite(l.pct));
48  const resetMs = five?.resetsAt && Number.isFinite(Date.parse(five.resetsAt)) ? Date.parse(five.resetsAt) - now : null;
49  const q = five ? quotaPerRun(runs) : null;
50  const n = (runs ?? []).filter((r) => bare(r[1]) === "executor").length;
51  const next = (shape.byWave ?? []).find(([, l]) => l.some((p) => !p.done));
52  const nextN = next ? next[1].filter((p) => !p.done).length : 0; // executors in the next wave: they run together
53  const out: Forecast = { ms: Math.max(0, shape.waves * typ - spent), waves: shape.waves, open: shape.open, nextN, runs: n, pct: five?.pct ?? null, resetMs, quota: null, level: null };
54  if (q) {
55    const add = shape.open * q.med, lo = shape.open * q.lo, hi = shape.open * q.hi;
56    const pct = five!.pct; // q is set only when five is
57    out.quota = { add, lo, hi, end: pct + add, endHi: pct + hi, n: q.n, next: { add: nextN * q.med, lo: nextN * q.lo, hi: nextN * q.hi, end: pct + nextN * q.med } };
58    out.level = out.quota.endHi >= 100 ? "warn" : out.quota.end >= 90 ? "amber" : null;
59  } else if (resetMs != null && out.ms > resetMs) out.level = "amber";
60  return out;
61}
62
63// The latest working stretch for the timeline: runs that ended and agents running now, going back from the newest until a
64// quiet gap longer than `gap`, at most `max` of them, by start time. -> [{ type, a, b, running }]
65export type Interval = { type: string | undefined; a: number; b: number; running: boolean };
66export function burst(runs: Run[] | null | undefined, running: Pick<Agent, "type" | "status" | "since">[] | null | undefined, now: number, gap = 30 * 60000, max = 12): Interval[] {
67  const iv = (runs ?? []).map((r): Interval => ({ type: r[1], a: r[0] - r[3], b: r[0], running: false }))
68    .concat((running ?? []).filter((x) => x.status === "running" && x.since).map((x) => ({ type: x.type, a: x.since!, b: now, running: true }))) // since: kept by the filter
69    .sort((x, y) => y.a - x.a);
70  const out: Interval[] = [];
71  let floor = Infinity;
72  for (const x of iv) {
73    if (out.length && x.b < floor - gap) break;
74    out.push(x); floor = Math.min(floor, x.a);
75    if (out.length >= max) break;
76  }
77  return out.reverse();
78}
79
80// Time per phase and stage, the last `last` phases by when they last ran. -> [{ phase, total, planning, executing, checking, other }]
81export type PhaseTotal = Record<Stage, number> & { phase: string; end: number; total: number };
82export function phaseTotals(runs: Run[] | null | undefined, last = 8): PhaseTotal[] {
83  const by = new Map<string, PhaseTotal>();
84  for (const r of runs ?? []) {
85    const key = r[2] || "?";
86    const p = by.get(key) ?? { phase: key, end: 0, total: 0, planning: 0, executing: 0, checking: 0, other: 0 };
87    p[stageOf(r[1])] += r[3]; p.total += r[3]; p.end = Math.max(p.end, r[0]);
88    by.set(key, p);
89  }
90  return [...by.values()].sort((a, b) => a.end - b.end).slice(-last);
91}
92
93// Agent time per local day for the last `days` days, oldest first. A run counts on the day it ended.
94export function dailyBuckets(runs: Run[] | null | undefined, now: number, days = 14): { start: number; ms: number }[] {
95  const today = new Date(now); today.setHours(0, 0, 0, 0);
96  const out = Array.from({ length: days }, (_, i) => ({ start: new Date(today.getFullYear(), today.getMonth(), today.getDate() - (days - 1 - i)).getTime(), ms: 0 }));
97  for (const r of runs ?? []) { const b = [...out].reverse().find((d) => r[0] >= d.start); if (b && r[0] < b.start + 864e5) b.ms += r[3]; }
98  return out;
99}
100
101// One block per value, tall for large, "·" for zero: a sparkline.
102export function spark(values: number[]): string {
103  const max = Math.max(0, ...values), ticks = "▁▂▃▄▅▆▇█";
104  return values.map((v) => (v <= 0 ? "·" : ticks[Math.min(7, Math.floor((v / max) * 7.999))])).join("");
105}
106
107export const dur = (ms: number): string => {
108  if (ms < 60000) return `${Math.round(ms / 1000)}s`;
109  const m = Math.round(ms / 60000);
110  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}`;
111};
112
hooks/panel.ts 523 lines
1// Pure: what the GSD pane draws, as data. No $ access, so it is testable under plain Node.
2// A segment is [text, color, flags]: color is a Claude Code theme token or null, flags "b" for bold, "d" for dim.
3import { typical, phaseTotals, dailyBuckets, spark, dur, stageOf, forecast, burst } from "./history.ts";
4import { frontmatter, summarize, items } from "./state-line.ts";
5import type { Agent, DirEntry, Entry, Expand, Frontmatter, Line, Model, PanelInput, Plan, PlanShape, Reader, Segment, Stage, StreamInfo, TreeAgent } from "./types.ts";
6
7// Theme tokens, so the pane follows the person's theme (light, dark, colour-blind) the way the engine's own UI does.
8export const C = { main: "claude", agent: "suggestion", ok: "success", arch: "merged", amber: "warning", warn: "error", dim: "inactive", faint: "subtle" };
9
10export const kTokens = (n: number): string => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(Math.round(n)));
11export const fmtUsd = (x: number): string => `$${x >= 100 ? Math.round(x) : x.toFixed(2)}`;
12export const limitLabel = (kind: unknown): string => String(kind).replace(/five[_ -]?hours?/i, "5h").replace(/seven[_ -]?days?/i, "7d").replace(/[_-]+/g, " ").trim();
13export const gauge = (pct: number, width: number): { on: string; off: string } => {
14  const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)));
15  return { on: "▰".repeat(full), off: "▱".repeat(width - full) };
16};
17export const clock = (ms: number): string => `${Math.floor(ms / 60000)}:${String(Math.floor(ms / 1000) % 60).padStart(2, "0")}`;
18export const cut = (s: string, w: number): string => (s.length <= w ? s : s.slice(0, Math.max(1, w - 1)) + "…");
19const plural = (n: number, w: string): string => `${n} ${w}${n === 1 ? "" : "s"}`;
20const listLen = (v: unknown): number => (v == null || v === "" ? 0 : Array.isArray(v) ? v.length : 1);
21
22// Commits in the reflog text (.git/logs/HEAD), and the newest ones first: { hash, msg }.
23const COMMIT = /^commit(?: \([^)]*\))?: (.*)$/;
24export function commitCount(reflogText: string | null | undefined): number {
25  return String(reflogText ?? "").split(/\r?\n/).filter((l) => COMMIT.test(l.split("\t")[1] ?? "")).length;
26}
27export function commitFeed(reflogText: string | null | undefined, n = 5): { hash: string; msg: string }[] {
28  const out: { hash: string; msg: string }[] = [];
29  const lines = String(reflogText ?? "").split(/\r?\n/).filter(Boolean);
30  for (let i = lines.length - 1; i >= 0 && out.length < n; i--) {
31    const [head = "", msg = ""] = lines[i]!.split("\t");
32    const m = COMMIT.exec(msg);
33    if (m) out.push({ hash: (head.split(" ")[1] ?? "").slice(0, 7), msg: m[1] ?? "" });
34  }
35  return out;
36}
37
38// A directory of the project's work (spikes/, threads/, quick/, ...) -> how many items it holds and the newest one.
39// Sub-directories count when there are any (a spike is a folder), else files. The newest is the latest by modified
40// time when the entries have one, else the last by name with numbers in order (247 after 99).
41export function streamInfo(entries: Entry[] | null | undefined): StreamInfo | null {
42  const live = (entries ?? []).filter((e) => !e.name.startsWith("."));
43  const dirs = live.filter((e) => e.kind === "dir" || (e.isLink && e.kind !== "file"));
44  const kept = dirs.length ? dirs : live.filter((e) => e.kind === "file" && !/^[A-Z][A-Z0-9_-]*\.md$/.test(e.name));
45  if (!kept.length) return null;
46  const timed = kept.filter((e) => e.mtimeMs > 0);
47  const byNewest = timed.length
48    ? [...kept].sort((a, b) => b.mtimeMs - a.mtimeMs)
49    : [...kept].sort((a, b) => b.name.localeCompare(a.name, undefined, { numeric: true }));
50  const names = byNewest.map((e) => e.name.replace(/\.md$/, ""));
51  return { count: kept.length, newest: names[0]!, recent: names.slice(0, 5), ...(kept.some((e) => e.from) ? { paths: byNewest.slice(0, 5).map((e) => `${e.from}/${e.name}`) } : {}) };
52}
53
54// A file path for the log: from ".planning/" on when it is under it, else the last two parts.
55export function shortPath(p: unknown): string {
56  const s = String(p ?? "");
57  const i = s.indexOf(".planning/");
58  if (i >= 0) return s.slice(i);
59  const parts = s.split("/").filter(Boolean);
60  return parts.slice(-2).join("/");
61}
62
63// A line is segments, or a segment list that is also a control: { segs, toggle: { key, open, hotkey } } draws a
64// ▸/▾ button before its segments; { button: { key, label, color, hotkey } } is one whole-line button.
65export const segsOf = (line: Line): Segment[] => (Array.isArray(line) ? line : line.segs ?? [[line.button?.label ?? "", line.button?.color ?? null]]);
66
67const hms = (ms: number): string => new Date(ms).toTimeString().slice(0, 8);
68const shortType = (t: string | undefined): string => String(t ?? "agent").replace(/^gsd-/, "");
69
70// The log's rows: time, a short kind word, the text.
71const KIND: Record<string, [string, string]> = { prompt: ["you", C.dim], spawn: ["spawn", C.agent], done: ["done", C.ok], fail: ["failed", C.warn], commit: ["commit", C.arch], write: ["wrote", C.main], error: ["error", C.warn], turn: ["turn", C.dim] };
72
73// Agents in tree order: each agent's children (forks, sub-agents) follow it, one level deeper. An agent whose parent is
74// not in the list (the main loop, or a parent that has gone) is a root. Roots show running first, then the latest to
75// finish; children in the order they started.
76export function agentTree(agents: Agent[] | null | undefined): TreeAgent[] {
77  const list = agents ?? [];
78  const ids = new Set(list.map((a) => a.id));
79  const kids = new Map<string, Agent[]>();
80  const roots: Agent[] = [];
81  for (const a of list) {
82    if (a.parentId && ids.has(a.parentId) && a.parentId !== a.id) kids.set(a.parentId, [...(kids.get(a.parentId) ?? []), a]);
83    else roots.push(a);
84  }
85  const rank = (a: Agent): number => (a.status === "running" ? 0 : 1);
86  roots.sort((a, b) => rank(a) - rank(b) || (b.endedAt ?? b.since ?? 0) - (a.endedAt ?? a.since ?? 0));
87  const out: TreeAgent[] = [];
88  const seen = new Set<string>();
89  const walk = (a: Agent, depth: number): void => {
90    if (seen.has(a.id)) return;
91    seen.add(a.id);
92    out.push({ ...a, depth });
93    for (const k of [...(kids.get(a.id) ?? [])].sort((x, y) => (x.since ?? 0) - (y.since ?? 0))) walk(k, depth + 1);
94  };
95  for (const r of roots) walk(r, 0);
96  for (const a of list) walk(a, 0); // anything a parent cycle left out
97  return out;
98}
99
100// Which of the tree's agents to draw. Running and failed agents always show, with the agents that started them, so
101// the tree stays readable; finished ones are collapsed: the latest `keep` while something runs (a wave should not push
102// the live agents off the box), up to `budget` lines when nothing does. Returns { shown (tree order), hidden }.
103export function visibleAgents(tree: TreeAgent[], { budget = 8, keep = 2, cap = 12 }: { budget?: number; keep?: number; cap?: number } = {}): { shown: TreeAgent[]; hidden: number } {
104  const byId = new Map<string | undefined, TreeAgent>(tree.map((a) => [a.id, a]));
105  const need = new Set<string>();
106  for (const a of tree) {
107    if (a.status !== "running" && a.status !== "failed" && a.status !== "killed") continue;
108    for (let n: TreeAgent | undefined = a, hops = 0; n && !need.has(n.id) && hops < 20; n = byId.get(n.parentId), hops++) need.add(n.id);
109  }
110  const anyLive = tree.some((a) => a.status === "running");
111  const spare = Math.max(0, Math.min(anyLive ? keep : budget, budget - need.size));
112  const finished = tree.filter((a) => !need.has(a.id)).sort((x, y) => (y.endedAt ?? y.since ?? 0) - (x.endedAt ?? x.since ?? 0));
113  for (const a of finished.slice(0, spare)) need.add(a.id);
114  const shown = tree.filter((a) => need.has(a.id)).slice(0, cap);
115  return { shown, hidden: tree.length - shown.length };
116}
117
118// The phase checklist of a ROADMAP.md: "- [x] **Phase 2.1: name** - blurb". Only that one line shape is read, so a
119// hand-edited roadmap yields fewer rows rather than wrong ones. -> [{ id, name, done }]
120export type RoadmapPhase = { id: string; name: string; done: boolean };
121export function roadmapPhases(text: string | null | undefined): RoadmapPhase[] {
122  const out: RoadmapPhase[] = [];
123  for (const m of String(text ?? "").matchAll(/^\s*[-*]\s*\[( |x|X)\]\s*\*\*Phase\s+([\w.]+?):?\s+(.+?)\*\*/gm)) out.push({ id: m[2] ?? "", name: (m[3] ?? "").trim(), done: m[1] !== " " });
124  return out;
125}
126
127// Which roadmap phase STATE.md says is current: by number, else by the label that leads the phase name. Never a guess.
128function currentIndex(phases: RoadmapPhase[], fm: Frontmatter): number {
129  const num = String(fm.current_phase ?? "").trim();
130  if (num) { const i = phases.findIndex((p) => p.id === num || p.id.replace(/^0+(?=\d)/, "") === num.replace(/^0+(?=\d)/, "")); if (i >= 0) return i; }
131  const lead = (String(fm.current_phase_name ?? "").split(/\s/)[0] ?? "").toLowerCase();
132  if (lead.length > 1) { const hits = phases.map((p, i) => (p.name.toLowerCase().split(/\s/)[0] === lead ? i : -1)).filter((i) => i >= 0); if (hits.length === 1) return hits[0]!; }
133  return -1;
134}
135
136// --- pace: where a GSD run's time goes
137
138// Plans of the current phase -> how they are laid out to run. A wave is a set of plans that may run together, so plans
139// left to run in single-plan waves go one after another. plans: [{ id, wave, done }]
140export function planShape(plans: Plan[] | null | undefined): PlanShape {
141  const byWave = new Map<number, Plan[]>();
142  for (const p of plans ?? []) (byWave.get(p.wave) ?? byWave.set(p.wave, []).get(p.wave)!).push(p);
143  const open = (plans ?? []).filter((p) => !p.done);
144  const openWaves = new Map<number, number>();
145  for (const p of open) openWaves.set(p.wave, (openWaves.get(p.wave) ?? 0) + 1);
146  return {
147    total: (plans ?? []).length, open: open.length, waves: openWaves.size, widest: Math.max(0, ...openWaves.values()),
148    byWave: [...byWave].sort((a, b) => a[0] - b[0]),
149  };
150}
151
152// This session's agents -> share of agent time by type, and how parallel they ran (agent time / wall time, 1.0 = one
153// at a time). agents: [{ type, since, endedAt }]; a running agent counts up to `now`.
154export type Pace = { total: number; byType: [string, number][]; count: number; executors: number; readonly executorParallel: number | null };
155export function agentPace(agents: Pick<Agent, "type" | "since" | "endedAt">[] | null | undefined, now: number): Pace {
156  const iv = (agents ?? []).filter((a) => a.since).map((a) => ({ type: shortType(a.type), a: a.since!, b: Math.max(a.since!, a.endedAt ?? now) })); // since: kept by the filter
157  const spanOf = (list: { a: number; b: number }[]): number => { // wall time covered by the intervals, overlaps counted once
158    let wall = 0, cur: { a: number; b: number } | null = null;
159    for (const x of [...list].sort((p, q) => p.a - q.a)) {
160      if (!cur || x.a > cur.b) { if (cur) wall += cur.b - cur.a; cur = { a: x.a, b: x.b }; } else cur.b = Math.max(cur.b, x.b);
161    }
162    return wall + (cur ? cur.b - cur.a : 0);
163  };
164  const sums = new Map<string, number>();
165  for (const x of iv) sums.set(x.type, (sums.get(x.type) ?? 0) + (x.b - x.a));
166  const total = [...sums.values()].reduce((m, v) => m + v, 0);
167  const ex = iv.filter((x) => x.type === "executor");
168  const exSum = ex.reduce((m, x) => m + x.b - x.a, 0);
169  const exWall = ex.length ? spanOf(ex) : 0;
170  return {
171    total, byType: [...sums].sort((a, b) => b[1] - a[1]), count: iv.length,
172    executors: ex.length, executorParallel: exWall > 0 ? exSum / exWall : null,
173  };
174}
175
176// --- the markdown reader's pure parts
177
178// The YAML block at the top of a GSD file: the dashboard already shows STATE's fields, so the reader hides it.
179export const stripFrontmatter = (t: string | null | undefined): string => String(t ?? "").replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
180
181// Pages of at most `max` characters (the Markdown element draws at most 10000), cut at a line, never inside a code fence.
182// ponytail: a single fenced block over 9500 characters is cut mid-fence, so show it raw if that ever matters.
183export function pages(text: string | null | undefined, max = 8000): string[] {
184  const out: string[] = [];
185  let cur = "", fence = false;
186  for (const line of String(text ?? "").replace(/\r\n/g, "\n").split("\n")) {
187    if (cur.length + line.length + 1 > max && cur.trim() && (!fence || cur.length > 9500)) { out.push(cur.trimEnd()); cur = ""; }
188    cur += line + "\n";
189    if (/^\s*(```|~~~)/.test(line)) fence = !fence;
190  }
191  if (cur.trim()) out.push(cur.trimEnd());
192  return out.length ? out : [""];
193}
194
195// The file as blocks that each begin at a heading (#, ## or ###), one Markdown element apiece, so the contents list can
196// scroll to a heading by its element's key. -> [{ md, heading?: { level, title } }]
197export type Section = { md: string; heading?: { level: number; title: string } };
198export function sections(text: string | null | undefined, max = 8000): Section[] {
199  const out: Section[] = [];
200  let cur: string[] = [], fence = false, head: Section["heading"] | null = null;
201  const flush = () => {
202    const t = cur.join("\n").trimEnd();
203    if (t.trim()) pages(t, max).forEach((md, j) => out.push({ md, ...(j === 0 && head ? { heading: head } : {}) }));
204    cur = [];
205  };
206  for (const line of String(text ?? "").replace(/\r\n/g, "\n").split("\n")) {
207    if (/^\s*(```|~~~)/.test(line)) fence = !fence;
208    const h = !fence && /^(#{1,3})\s+(.+?)\s*#*\s*$/.exec(line);
209    if (h) { flush(); head = { level: (h[1] ?? "").length, title: (h[2] ?? "").replace(/[*_`]/g, "") }; }
210    cur.push(line);
211  }
212  flush();
213  return out;
214}
215
216// GSD files are full of task lists; the renderer draws "[x]" literally, so give them glyphs.
217const tick = (t: string): string => t.replace(/^(\s*[-*] )\[( |x|X)\] /gm, (_: string, lead: string, c: string) => `${lead}${c === " " ? "○" : "✓"} `);
218
219// One folder of .planning for the browser: sub-folders first, then the .md files, numbers in order (phase 2 before 10).
220export function browseList(entries: DirEntry[] | null | undefined): { name: string; dir: boolean }[] {
221  const isDir = (e: DirEntry): boolean => e.kind === "dir" || (e.isLink && e.kind !== "file");
222  return (entries ?? [])
223    .filter((e) => !e.name.startsWith(".") && (isDir(e) || /\.md$/i.test(e.name)))
224    .map((e) => ({ name: e.name, dir: isDir(e) }))
225    .sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name, undefined, { numeric: true }));
226}
227
228// The reader view: replaces the dashboard. rd: { path, isFile, entries?, text? }. A line is a button or { md }.
229function readerModel(rd: Reader, header: Segment[], inner: number, ex: Partial<Expand> = {}): Model {
230  const crumb = String(rd.path).replace(/^\.planning\/?/, "") || ".planning";
231  const lines: Line[] = [{ button: { key: "reader:up", label: rd.path === ".planning" ? "‹ back to the dashboard" : "‹ back", color: C.dim, hotkey: "b" } }];
232  if (rd.path !== ".planning") lines.push({ button: { key: "reader:close", label: "⌂ dashboard", color: C.dim, hotkey: "d" } });
233  let right: Segment[] | null = null;
234  if (rd.isFile) {
235    // The engine refuses the WHOLE pane if one Markdown block passes 10000 characters, so a block is cut at 9900 as a last resort.
236    const secs = sections(tick(stripFrontmatter(rd.text)));
237    const heads = secs.map((x, i) => ({ i, ...x.heading })).filter((x) => x.title);
238    if (heads.length >= 3) {
239      lines.push({ button: { key: "reader:toc", label: `${ex.toc ? "▾" : "▸"} contents (${heads.length})`, color: C.dim, hotkey: "c" } });
240      if (ex.toc) for (const x of heads) lines.push({ button: { key: `reader:goto:${x.i}`, label: cut(`${"  ".repeat(x.level! - 1)}${x.title}`, inner - 2), color: x.level === 1 ? C.arch : null } });
241    }
242    secs.forEach((x, i) => lines.push({ md: x.md.slice(0, 9900), key: `sec${i}` }));
243    lines.push({ button: { key: "reader:top", label: "↑ back to top", color: C.dim, hotkey: "t" } });
244  } else {
245    const list = browseList(rd.entries);
246    if (!list.length) lines.push([["no markdown here", C.dim]]);
247    for (const e of list) lines.push({ button: { key: `reader:open:${e.name}`, label: `${e.dir ? "▸" : " "} ${e.name}${e.dir ? "/" : ""}`, color: e.dir ? C.arch : null } });
248    if (list.length > 30) lines.push({ button: { key: "reader:top", label: "↑ back to top", color: C.dim, hotkey: "t" } });
249    right = [[`${list.length}`, C.dim]];
250  }
251  return { header, panels: [{ id: "reader", color: C.arch, title: [[cut(crumb, inner - 8), C.arch, "b"]], right, lines }] };
252}
253
254// The trends view: replaces the dashboard. Three charts from the recorded runs, each labelled with its numbers.
255function trendsModel(inp: PanelInput, header: Segment[], inner: number, now: number): Model {
256  const runs = inp.history ?? [];
257  const lines: Line[] = [{ button: { key: "trends", label: "‹ back", color: C.dim, hotkey: "b" } }];
258  const ex = runs.filter((r) => shortType(r[1]) === "executor").slice(-30).map((r) => r[3]);
259  lines.push([["executor time per run", null, "b"], [`  last ${ex.length}`, C.dim]]);
260  if (ex.length < 3) lines.push([["not enough executor runs yet (3 needed)", C.dim]]);
261  else {
262    const o = [...ex].sort((a, b) => a - b);
263    lines.push([[spark(ex), C.main]]);
264    lines.push([[`min ${dur(o[0]!)} · median ${dur(o[(o.length - 1) >> 1]!)} · max ${dur(o[o.length - 1]!)} · last ${dur(ex[ex.length - 1]!)}`, C.dim]]); // 3 or more
265  }
266  lines.push([[" ", null]]);
267  const ph = phaseTotals(runs);
268  lines.push([["time by phase and stage", null, "b"]]);
269  lines.push([["█ ", C.agent], ["planning  ", C.dim], ["█ ", C.main], ["executing  ", C.dim], ["█ ", C.ok], ["checking  ", C.dim], ["█ ", C.faint], ["other", C.dim]]);
270  if (!ph.length) lines.push([["no runs recorded yet", C.dim]]);
271  const top = Math.max(1, ...ph.map((x) => x.total)), width = Math.max(8, inner - 14);
272  for (const x of ph) {
273    const bar = ([["planning", C.agent], ["executing", C.main], ["checking", C.ok], ["other", C.faint]] as const).filter(([k]) => x[k] > 0).map(([k, c]): Segment => ["█".repeat(Math.max(1, Math.round((x[k] / top) * width))), c]);
274    lines.push([[`ph ${x.phase}`.padEnd(6), C.dim], ...bar, [` ${dur(x.total)}`, null]]);
275  }
276  lines.push([[" ", null]]);
277  const days = dailyBuckets(runs, now, 14);
278  const day = (ms: number): string => new Date(ms).toLocaleDateString("en", { month: "short", day: "numeric" });
279  const peak = days.reduce((m, d) => (d.ms > m.ms ? d : m), days[0]!); // 14 days
280  lines.push([["agent time per day", null, "b"], ["  last 14 days", C.dim]]);
281  lines.push([[spark(days.map((d) => d.ms)), C.agent]]);
282  lines.push([[`${day(days[0]!.start)} to today` + (peak.ms > 0 ? ` · peak ${dur(peak.ms)} on ${day(peak.start)}` : ""), C.dim]]);
283  lines.push([[" ", null]]);
284  lines.push([[cut("phase = STATE.md's current_phase when the agent started", inner), C.dim]]);
285  return { header, panels: [{ id: "trends", color: C.amber, title: [["trends", C.amber, "b"]], right: [[`${runs.length} agents recorded`, C.dim]], lines }] };
286}
287
288// The timeline view: replaces the dashboard. One bar per agent over the latest working stretch, so agents that ran
289// together sit on top of each other and agents that ran one after another form a staircase.
290function timelineModel(inp: PanelInput, header: Segment[], inner: number, now: number): Model {
291  const rows = burst(inp.history, inp.agents, now);
292  const lines: Line[] = [{ button: { key: "timeline", label: "‹ back", color: C.dim, hotkey: "b" } }];
293  if (!rows.length) lines.push([["no agents recorded yet", C.dim]]);
294  else {
295    const t0 = Math.min(...rows.map((x) => x.a)), t1 = Math.max(...rows.map((x) => x.b));
296    const span = Math.max(t1 - t0, 60000), label = 9, width = Math.max(8, inner - label - 7);
297    const col = (t: number): number => Math.min(width - 1, Math.floor(((t - t0) / span) * width));
298    const hue: Record<Stage, string> = { planning: C.agent, executing: C.main, checking: C.ok, other: C.faint };
299    lines.push([[" ".repeat(label), null], [hms(t0), C.dim], [" ".repeat(Math.max(1, width - 16)), null], [hms(t1), C.dim]]);
300    for (const x of rows) {
301      const c0 = col(x.a), n = Math.max(1, col(x.b) - c0 + (x.b >= t1 ? 1 : 0));
302      lines.push([[shortType(x.type).replace(/-purpose$/, "").slice(0, label - 1).padEnd(label), C.dim], [" ".repeat(c0), null], [(x.running ? "▒" : "█").repeat(Math.min(n, width - c0)), hue[stageOf(x.type)]], [` ${dur(x.b - x.a)}`, C.dim]]);
303    }
304    lines.push([[" ", null]]);
305    const pace = agentPace(rows.map((x) => ({ type: x.type, since: x.a, endedAt: x.b })), t1);
306    const ex = pace.executors >= 2 && pace.executorParallel != null;
307    lines.push([[`${plural(rows.length, "agent")} · ${dur(t1 - t0)} wall`, C.dim], ...(ex ? [[` · executors ×${pace.executorParallel.toFixed(1)}`, pace.executorParallel < 1.15 ? C.amber : C.ok], [pace.executorParallel < 1.15 ? " one at a time" : " overlapped", C.dim]] satisfies Segment[] : [])]);
308    lines.push([["█ ", C.agent], ["planning  ", C.dim], ["█ ", C.main], ["executing  ", C.dim], ["█ ", C.ok], ["checking  ", C.dim], ["▒ ", C.dim], ["running", C.dim]]);
309  }
310  return { header, panels: [{ id: "timeline", color: C.agent, title: [["timeline", C.agent, "b"]], right: [["latest working stretch", C.dim]], lines }] };
311}
312
313// in: {
314//   history: [[endedAt, type, phase, durMs, turns, inTok, outTok, model]],   // finished agents of this project
315//   plans: [{ id, wave, done }],   // the current phase's plans
316//   reader: { path, isFile, entries, text } | null,   // the markdown reader, when open
317//   roadmap: ROADMAP.md text | null,
318//   state: STATE.md text | null,
319//   usage: { pct, tokens, window, costUsd, limits: [{kind, pct}] } | null,
320//   isRunning: boolean,            // a turn is running now
321//   turn: { startedAt, edits, errors } | null,        // the running turn
322//   receipt: { durationMs, edits, errors, commits, costDelta } | null,   // the last finished turn
323//   agents: [{ id, type, description, status, since, endedAt }],
324//   streams: [{ name, count, newest }],
325//   handoff: object | null,
326//   log: [{ at, kind, text }],
327//   now: ms }
328// -> { header: segments, panels: [{ id, color, title: segments, right: segments|null, lines: [segments] }] }
329export function panelModel(inp: PanelInput, width = 62): Model {
330  const ex: Expand = { agents: new Set(), finished: false, blockers: false, log: false, roadmap: false, pace: false, trends: false, timeline: false, toc: false, ...inp.expand };
331  const w = Math.max(36, width);
332  const inner = w - 4; // the border and one column of padding on each side
333  const fm = frontmatter(inp.state ?? "") ?? {};
334  const panels: Model["panels"] = [];
335  const now = inp.now ?? 0;
336
337  const phase = fm.current_phase ? `phase ${fm.current_phase}${fm.current_phase_name ? " " + fm.current_phase_name : ""}` : (fm.milestone as string | undefined) ?? ""; // a top-level key: never nested
338  const ws = inp.workstream ?? null;
339  const header: Segment[] = [["GSD", C.main, "b"], ...(ws ? [[" · ", C.dim], [cut(ws.name, 24), C.amber]] satisfies Segment[] : []), ...(phase ? [[" · ", C.dim], [cut(phase, w - 22), null, "b"]] satisfies Segment[] : []), ...(fm.status ? [[` · ${fm.status}`, C.dim]] satisfies Segment[] : [])];
340
341  if (inp.reader) return readerModel(inp.reader, header, inner, ex);
342  if (ex.trends) return trendsModel(inp, header, inner, now);
343  if (ex.timeline) return timelineModel(inp, header, inner, now);
344
345  // main: the session's vitals, and anything that needs a person
346  const main: Line[] = [];
347  const u = inp.usage;
348  if (u && u.pct != null) {
349    const g = gauge(u.pct, 10);
350    const hot = u.pct >= 80 ? C.warn : u.pct >= 60 ? C.amber : C.main;
351    main.push([["ctx ", C.dim], [g.on, hot], [g.off, C.faint], [` ${Math.round(u.pct)}%`, null, "b"], ...(u.tokens != null && u.window ? [[` ${kTokens(u.tokens)}/${kTokens(u.window)}`, C.dim]] satisfies Segment[] : [])]);
352  }
353  if (u && (u.costUsd != null || (u.limits ?? []).length)) {
354    const row: Segment[] = [];
355    if (u.costUsd != null) row.push([`${fmtUsd(u.costUsd)}   `, null]);
356    for (const l of (u.limits ?? []).slice(0, 2)) {
357      const g = gauge(l.pct, 5);
358      row.push([`${limitLabel(l.kind)} `, C.dim], [g.on, l.pct >= 80 ? C.warn : C.main], [g.off, C.faint], [` ${Math.round(l.pct)}%   `, C.dim]);
359    }
360    main.push(row);
361  }
362  if (ws && ws.total > 1) main.push({ button: { key: "ws", label: `⇄ workstream ${cut(ws.name, inner - 26)} · ${ws.index} of ${ws.total}`, color: C.amber, hotkey: "w" } });
363  const h = inp.handoff;
364  const blockers = h ? listLen(h.blockers) : 0;
365  const people = h ? listLen(h.human_actions_pending) : 0;
366  if (blockers || people) {
367    const label = `${ex.blockers ? "▾" : "▸"} ${[blockers ? `⚠ ${plural(blockers, "blocker")}` : "", people ? `${people} need${people === 1 ? "s" : ""} a person` : ""].filter(Boolean).join(" · ")}`;
368    main.push({ button: { key: "blockers", label, color: blockers ? C.warn : C.amber, hotkey: "b" } });
369    if (ex.blockers) {
370      for (const t of items(h?.blockers)) main.push([["  - ", C.warn], [cut(t, inner - 4), null]]);
371      for (const t of items(h?.human_actions_pending)) main.push([["  - ", C.amber], [cut(t, inner - 4), null]]);
372    }
373  }
374  main.push({ button: { key: "reader:browse", label: "▸ read .planning", color: C.arch, hotkey: "o" } });
375  if (fm.last_activity_desc && !(u && u.pct != null)) main.push([[cut(summarize(fm.last_activity_desc, inner), inner), C.dim]]);
376  panels.push({
377    id: "main", color: C.main,
378    title: [[cut(phase || "GSD project", inner - 12), C.main, "b"]],
379    right: [inp.isRunning ? ["● working", C.main] : (inp.agents ?? []).some((a) => a.status === "running") ? ["◐ agents working", C.agent] : ["○ idle", C.dim]],
380    lines: main,
381  });
382
383  // roadmap: the phases, with the current one marked. Finished phases and far-off ones fold into one button.
384  const road = roadmapPhases(inp.roadmap);
385  if (road.length) {
386    const cur = currentIndex(road, fm);
387    const doneN = road.filter((p) => p.done).length;
388    const first = cur >= 0 ? cur : Math.max(0, road.findIndex((p) => !p.done));
389    const WINDOW = 6;
390    const from = ex.roadmap ? 0 : first;
391    const to = ex.roadmap ? road.length : Math.min(road.length, first + WINDOW);
392    const lines: Line[] = [];
393    const before = ex.roadmap ? 0 : from, after = ex.roadmap ? 0 : road.length - to;
394    if (!ex.roadmap && (before || after)) lines.push({ button: { key: "roadmap", label: `▸ ${[before ? `${before} before` : "", after ? `${after} later` : ""].filter(Boolean).join(" · ")}`, color: C.dim, hotkey: "r" } });
395    road.slice(from, to).forEach((p, i) => {
396      const here = from + i === cur;
397      const glyph = p.done ? "✓" : here ? "▶" : "·";
398      const id = p.id.padEnd(4);
399      lines.push([[`${glyph} `, p.done ? C.ok : here ? C.main : C.faint], [id + " ", here ? C.main : C.dim, here ? "b" : undefined], [cut(p.name, inner - 2 - id.length - 1), p.done ? C.dim : null, here ? "b" : undefined]]);
400    });
401    if (ex.roadmap) lines.push({ button: { key: "roadmap", label: "▾ collapse", color: C.dim, hotkey: "r" } });
402    const sm = String(inp.state ?? "");
403    const pn = Number(/^\s*completed_plans:\s*(\d+)/m.exec(sm)?.[1]), pt = Number(/^\s*total_plans:\s*(\d+)/m.exec(sm)?.[1]);
404    panels.push({ id: "roadmap", color: C.ok, title: [["roadmap", C.ok, "b"]],
405      right: [[`${doneN}/${road.length} phases${pt ? ` · ${pn}/${pt} plans` : ""}`, C.dim]], lines });
406  }
407
408  // pace: how the plans are laid out, and where this session's agent time went. The hint shows only on clear evidence.
409  const shape = planShape(inp.plans);
410  const pace = agentPace(inp.agents, now);
411  const showTime = pace.total >= 60000;
412  const hist = inp.history ?? [];
413  if (shape.total || showTime || hist.length) {
414    const lines: Line[] = [];
415    const serialPlans = shape.open >= 2 && shape.widest === 1;
416    const serialRun = pace.executors >= 2 && pace.executorParallel != null && pace.executorParallel < 1.15 && pace.total >= 120000;
417    if (shape.total) lines.push([["plans ", C.dim], [`${shape.open} to run of ${shape.total} · ${plural(shape.waves, "wave")} · widest ${shape.widest}`, null]]);
418    if (serialPlans) lines.push([["serial: each plan waits for the one before it", C.amber]]);
419    if (showTime) {
420      lines.push([["time  ", C.dim], [pace.byType.slice(0, 3).map(([t, ms]) => `${t} ${Math.round((100 * ms) / pace.total)}%`).join(" · "), null]]);
421      if (serialRun) lines.push([["serial: executors ran one at a time", C.amber], [` ×${pace.executorParallel.toFixed(1)}`, C.dim]]);
422    }
423    const fc = forecast(shape, hist, inp.agents, now, u?.limits);
424    if (fc) {
425      const hue = fc.level === "warn" ? C.warn : fc.level === "amber" ? C.amber : null;
426      lines.push([["left  ", C.dim], [`≈ ${dur(fc.ms)} of executing`, null], [` · ${plural(fc.waves, "wave")} · from ${fc.runs} runs`, C.dim]]);
427      if (fc.pct != null) lines.push([["5h    ", C.dim], [`${Math.round(fc.pct)}%`, null, "b"], [fc.resetMs != null ? ` · resets in ${dur(Math.max(0, fc.resetMs))}` : "", C.dim]]);
428      if (fc.quota) lines.push([["quota ", C.dim], [`+${Math.round(fc.quota.add)}% (${Math.round(fc.quota.lo)}–${Math.round(fc.quota.hi)}) → ${Math.round(fc.quota.end)}%`, hue, hue ? "b" : undefined], [` · ${fc.quota.n} runs`, C.dim]]);
429      if (fc.quota && fc.nextN >= 2) lines.push([["next  ", C.dim], [`wave of ${fc.nextN} together`, null], [` +${Math.round(fc.quota.next.add)}% (${Math.round(fc.quota.next.lo)}–${Math.round(fc.quota.next.hi)}) → ${Math.round(fc.quota.next.end)}%`, C.dim]]);
430      if (!fc.quota && fc.level) lines.push([["longer than the window has left", hue]]);
431    }
432    lines.push({ button: { key: "pace", label: `${ex.pace ? "▾ hide" : "▸"} details`, color: C.dim, hotkey: "p" } });
433    if (ex.pace) {
434      for (const [wave, list] of shape.byWave) lines.push([[`  wave ${wave}  `, C.dim], [list.map((p) => `${p.id} ${p.done ? "✓" : "○"}`).join("  "), null]]);
435      const wid = Math.max(...pace.byType.map(([t]) => t.length)) + 2;
436      for (const [t, ms] of pace.byType) lines.push([[`  ${t.padEnd(wid)}`, C.dim], [clock(ms), null], [`  ${Math.round((100 * ms) / pace.total)}%`, C.dim]]);
437      const here = phaseTotals(hist.filter((r) => String(r[2]) === String(fm.current_phase ?? "")), 1)[0];
438      if (here) lines.push([["  this phase  ", C.dim], [(["planning", "executing", "checking"] as const).filter((k) => here[k] > 0).map((k) => `${k} ${dur(here[k])}`).join(" · "), null]]);
439      if (pace.executors >= 2 && pace.executorParallel != null) lines.push([["  executors in parallel ", C.dim], [`×${pace.executorParallel.toFixed(2)}`, null]]);
440    }
441    if (hist.length) lines.push({ button: { key: "trends", label: "▸ trends", color: C.dim, hotkey: "t" } });
442    if (hist.length || (inp.agents ?? []).some((a) => a.status === "running")) lines.push({ button: { key: "timeline", label: "▸ timeline", color: C.dim, hotkey: "g" } });
443    panels.push({ id: "pace", color: C.amber, title: [["pace", C.amber, "b"]], right: shape.total && serialPlans ? [["serial", C.amber]] : null, lines });
444  }
445
446  // agents: a tree, so a fork or a sub-agent sits under the agent that started it
447  const tree = agentTree(inp.agents);
448  if (tree.length) {
449    const running = tree.filter((a) => a.status === "running").length;
450    const forks = tree.filter((a) => a.isFork).length;
451    const base = visibleAgents(tree);
452    const { shown, hidden } = ex.finished ? visibleAgents(tree, { budget: Infinity, keep: Infinity, cap: Infinity }) : base;
453    const lines: Line[] = [];
454    shown.forEach((a, i) => {
455      const isRun = a.status === "running";
456      const bad = a.status === "failed" || a.status === "killed";
457      const glyph = isRun ? "◐" : bad ? "✗" : "✓";
458      const t = isRun ? now - (a.since ?? now) : (a.endedAt ?? now) - (a.since ?? now);
459      const right = a.since ? clock(Math.max(0, t)) : "";
460      const typ = isRun && a.since ? typical(inp.history, a.type) : null; // what this kind of agent usually takes here
461      const typTxt = typ ? ` · typ ${clock(typ)}` : "";
462      const indent = a.depth ? "  ".repeat(Math.min(a.depth, 3) - 1) + "└ " : "";
463      const label = `${a.isFork ? "⑂ " : ""}${shortType(a.type)} `;
464      const room = Math.max(4, inner - 8 - indent.length - label.length - right.length - typTxt.length - 1);
465      const open = ex.agents.has(a.id);
466      lines.push({
467        toggle: { key: `agent:${a.id}`, open, hotkey: i < 6 ? String(i + 1) : undefined },
468        segs: [[`${glyph} `, isRun ? C.agent : bad ? C.warn : C.ok], [indent, C.faint], [label, null, "b"], [cut(String(a.description ?? "").replace(/\s+/g, " "), room).padEnd(room + 1), C.dim], [right, isRun ? C.agent : C.dim], ...(typTxt ? [[typTxt, t > 2 * typ! ? C.amber : C.dim]] satisfies Segment[] : [])], // typ: set whenever typTxt is
469      });
470      if (open) {
471        const full = String(a.description ?? "").replace(/\s+/g, " ").trim();
472        for (let k = 0; k < full.length; k += inner - 4) lines.push([["    ", null], [full.slice(k, k + inner - 4), null]]);
473        const parent = a.parentId ? tree.find((x) => x.id === a.parentId) : null;
474        lines.push([["    ", null], [`id ${String(a.id).slice(0, 8)} · ${a.type}${a.isFork ? " · fork" : ""}${a.parentId ? ` · under ${parent ? shortType(parent.type) : String(a.parentId).slice(0, 8)}` : ""} · ${a.status}`, C.dim]]);
475      }
476    });
477    const hiddenLive = tree.filter((a) => a.status === "running" && !shown.includes(a)).length;
478    if (hiddenLive) lines.push({ button: { key: "finished", label: `▸ +${hiddenLive} running, ${hidden - hiddenLive} finished not shown`, color: C.agent, hotkey: "f" } });
479    else if (!ex.finished && hidden) lines.push({ button: { key: "finished", label: `▸ ${hidden} more finished`, color: C.ok, hotkey: "f" } });
480    else if (ex.finished && base.hidden) lines.push({ button: { key: "finished", label: "▾ collapse finished", color: C.dim, hotkey: "f" } });
481    const depth = Math.max(...tree.map((a) => a.depth));
482    panels.push({ id: "agents", color: C.agent, title: [[`agents · ${running} running`, C.agent, "b"]],
483      right: [[`${tree.length} total${forks ? ` · ${forks} fork${forks === 1 ? "" : "s"}` : ""}${depth ? ` · ${depth + 1} deep` : ""}`, C.dim]], lines });
484  }
485
486  // turn: the one running now, else the last receipt
487  if (inp.isRunning && inp.turn) {
488    panels.push({ id: "turn", color: C.main, title: [["turn", C.main, "b"]], right: [[clock(Math.max(0, now - inp.turn.startedAt)), C.main]],
489      lines: [[[`${plural(inp.turn.edits, "edit")} · ${plural(inp.turn.errors, "error")}`, C.dim]]] });
490  } else if (inp.receipt) {
491    const r = inp.receipt;
492    const bits = [`${Math.round(r.durationMs / 1000)}s`, plural(r.edits, "edit"), plural(r.commits, "commit"), plural(r.errors, "error")];
493    if (r.costDelta != null && r.costDelta > 0) bits.push(`+${fmtUsd(r.costDelta)}`);
494    panels.push({ id: "turn", color: C.faint, title: [["last turn", C.dim, "b"]], right: [["✓", C.ok]], lines: [[[bits.join(" · "), C.dim]]] });
495  }
496
497  // streams: the kinds of work this project holds, and the newest of each
498  if ((inp.streams ?? []).length) {
499    const lines: Line[] = [];
500    for (const st of inp.streams ?? []) {
501      const open = ex.streams?.has?.(st.name);
502      lines.push({ toggle: { key: `stream:${st.name}`, open }, segs: [[st.name.padEnd(8), C.dim], [String(st.count).padStart(4) + "  ", null, "b"], [cut(st.newest, inner - 16), C.dim]] });
503      if (open) (st.recent ?? [st.newest]).slice(0, 5).forEach((n, i) => lines.push(st.paths?.[i] ? { button: { key: `reader:open-path:${st.paths[i]}`, label: `    ${cut(n, inner - 8)}`, color: C.dim } } : [["      ", null], [cut(n, inner - 8), C.dim]]));
504      if (open && st.count > 5 && st.paths?.[0]) lines.push({ button: { key: `reader:open-path:${st.paths[0].split("/").slice(0, -1).join("/")}`, label: `    ▸ all ${st.count} in the reader`, color: C.arch } });
505    }
506    panels.push({ id: "streams", color: C.arch, title: [["work streams", C.arch, "b"]], right: null, lines });
507  }
508
509  // log: what happened, newest last; the button shows earlier entries
510  const all = inp.log ?? [];
511  const log = ex.log ? all : all.slice(-8);
512  if (log.length) {
513    const lines = log.map((l): Line => {
514      const [word, color] = KIND[l.kind] ?? [l.kind, C.dim];
515      return [[`${hms(l.at)} `, C.dim], [word.padEnd(7), color, "b"], [cut(l.text, inner - 17), null]];
516    });
517    if (!ex.log && all.length > 8) lines.unshift({ button: { key: "log", label: `▸ ${all.length - 8} earlier`, color: C.dim, hotkey: "l" } });
518    else if (ex.log && all.length > 8) lines.unshift({ button: { key: "log", label: "▾ show less", color: C.dim, hotkey: "l" } });
519    panels.push({ id: "log", color: C.faint, title: [["session log", C.dim, "b"]], right: null, lines });
520  }
521  return { header, panels };
522}
523
hooks/types.ts 68 lines
1// The data shapes the hooks pass between them. Types only: nothing here exists at run time.
2import type { FsEntry } from "claude-code";
3
4// A finished agent's numbers, as history.ts keeps them (see there). quota and width are absent in older runs.
5export type Run = [endedAt: number, type: string, phase: string, durationMs: number, turns: number, inTokens: number, outTokens: number, model: string, quota?: number, width?: number];
6
7// An agent as the pane sees it: what $.agent.list() answers, plus when this module first saw it and when it ended.
8export type Agent = { id: string; type?: string; description?: string; status: string; since?: number | null; endedAt?: number | null; parentId?: string; isFork?: boolean };
9export type TreeAgent = Agent & { depth: number };
10
11// One rate-limit window ("five_hour", "seven_day", ...) and the session's figures, as readUsage makes them.
12export type Limit = { kind: string; pct: number; resetsAt?: string | null };
13export type Usage = { pct: number | null; tokens: number | null; window: number | null; costUsd: number | null; limits: Limit[] };
14
15// STATE.md's frontmatter: top-level values, and one level of nested keys (progress:).
16export type Fields = Record<string, string>;
17export type Frontmatter = { [key: string]: string | Fields | undefined; progress?: Fields };
18
19// HANDOFF.json as GSD writes it on pause; the lists come as strings or objects (see items()).
20export type Handoff = { next_action?: string; timestamp?: string; blockers?: unknown; human_actions_pending?: unknown; remaining_tasks?: unknown; uncommitted_files?: unknown };
21
22export type Plan = { id: string; wave: number; done: boolean };
23export type PlanShape = { total: number; open: number; waves: number; widest: number; byWave: [number, Plan[]][] };
24
25export type Stage = "planning" | "executing" | "checking" | "other";
26
27// A work stream's directory listing, each entry tagged with the folder it came from when there are two.
28export type Entry = FsEntry & { from?: string };
29export type StreamInfo = { count: number; newest: string; recent: string[]; paths?: string[] };
30export type Stream = { name: string; count: number; newest: string; recent?: string[]; paths?: string[] };
31
32export type Workstream = { name: string; index: number; total: number; names: string[] };
33
34// The markdown reader: a folder listing or one file.
35export type DirEntry = Pick<FsEntry, "name" | "kind" | "isLink">;
36export type Reader = { path: string; isFile: boolean; entries?: DirEntry[]; text?: string };
37
38// Which of the pane's parts the person has opened.
39export type Expand = { agents: Set<string>; finished: boolean; blockers: boolean; log: boolean; roadmap: boolean; pace: boolean; trends: boolean; timeline: boolean; toc: boolean; streams?: Set<string> };
40
41export type LogRow = { at: number; kind: string; text: string };
42export type Turn = { startedAt: number; edits: number; errors: number };
43export type Receipt = { durationMs: number; edits: number; errors: number; commits: number; costDelta: number | null };
44
45// What the pane draws, as data (see panel.ts). A segment is [text, color, flags].
46export type Segment = [text: string, color: string | null, flags?: string];
47export type Button = { key: string; label: string; color: string | null; hotkey?: string };
48export type Toggle = { key: string; open?: boolean; hotkey?: string };
49export type Control = { segs?: Segment[]; toggle?: Toggle; button?: Button; md?: string; key?: string };
50// A plain line is segments. It has none of a control's keys, so `l.button?.key` reads on any line.
51export type Plain = Segment[] & { [K in keyof Control]?: undefined };
52export type Line = Plain | Control;
53export type Panel = { id: string; color: string; title: Segment[]; right: Segment[] | null; lines: Line[] };
54export type Model = { header: Segment[]; panels: Panel[] };
55
56export type PanelInput = {
57  history?: Run[]; plans?: Plan[]; reader?: Reader | null; roadmap?: string | null; state?: string | null; usage?: Partial<Usage> | null;
58  isRunning?: boolean; turn?: Turn | null; receipt?: Receipt | null; agents?: Agent[]; streams?: Stream[]; handoff?: Handoff | null;
59  log?: LogRow[]; workstream?: Workstream | null; expand?: Partial<Expand>; now?: number;
60};
61
62// What gsd-status.ts keeps for the pane: this session's events plus what the last refresh read.
63export type Live = {
64  state: string | null; roadmap: string | null; plans: Plan[]; workstream: Workstream | null; handoff: Handoff | null; usage: Usage | null;
65  agents: Agent[]; streams: Stream[]; log: LogRow[]; isRunning: boolean; turn: Turn | null; receipt: Receipt | null;
66  commits: number; newest: string | null; startCommits: number; startCost: number | null;
67};
68