Spec Kit progress and usage governance for Claude Code: a phase rail above the prompt, the next command in the prompt hint, the current task on the spinner, a…

A Claude Code mod that shows where your Spec Kit work stands and keeps your session under its usage limits: a phase rail above the prompt, the next command to run, the task in progress, a pane with every feature, toasts when something changes, buttons that install updates, and a status entry with your fullest usage window.
Version 0.140.0. Every image in this README is a capture of the real mod running in Claude Code 2.1.292, made with
scripts/capture/scene.shin the demo project docs/demo/ (see How the images are made).
| Where | What Astrolabe draws | Section |
|---|---|---|
| Above the prompt | The active feature, the six Spec Kit steps, a progress bar, and buttons for updates | The band |
| Under the prompt | ◆ 002 · implement 45% │ 5h 42%: feature, phase, progress, usage window | The status entry |
| The hint line | next: /speckit-implement · 11 tasks left | The prompt hint |
| The spinner | … T011 · Show an empty-cart message · 1s while Claude works on the feature | The spinner |
/astrolabe | A pane with Specs (and their tasks), Session, PRs and Setup tabs | The pane |
| Toasts | A task ticked with no code edited; a phase finished | Toasts |
| Tool calls | New subagents capped or held, the session paused near the limit | Usage governance |
An astrolabe is a handheld instrument that astronomers and navigators used for centuries. You sight a star or the sun through it, read how high the body stands above the horizon, and from that one reading work out the time of day and where you are. Its front plate, the rete, is a rotating map of the sky laid over the fixed coordinates of one place.
The mod does the same job for a coding session. It reads altitude: how full the context window is, and how far the 5-hour and weekly usage windows have climbed. It turns those readings into time: when each window resets and, at the current burn rate, when you would reach 80%. It gives your position: the directory, branch and pull request, and which Spec Kit feature you are in and at which phase (specify, clarify, plan, tasks, implement).
Navigators also steered by the astrolabe, and the mod acts on its readings too. When a usage window gets high it slows down or queues new subagent dispatches, and it resumes them after the reset.
The emoji is 🧭 because Unicode has no astrolabe. The compass is the closest navigation instrument it offers, and the repository, the mod and its messages all use it.
You need Claude Code 2.1.292 or later (claude --version). In a Claude Code terminal session, type:
/plugin install astrolabe --marketplace jonyfs/astrolabe
Claude Code asks Add marketplace?. Answer y, pick the user scope with Enter, and you see Installed astrolabe. Plugin is now active. The status entry appears in that same session, with no restart. To check it from a shell:
The two-step form does the same thing:
/plugin marketplace add jonyfs/astrolabe
/plugin install astrolabe@astrolabe
From a shell it is the same two commands (a real capture, on a machine where Astrolabe was not installed):
The four options start unset, which means their defaults (see Options).
Installing changes no settings file by itself. Claude Code records the plugin and its marketplace in ~/.claude/settings.json (enabledPlugins and extraKnownMarketplaces), the same as for any plugin, and the mod never writes there.
claude plugin update astrolabe@astrolabe
Then type /reload-plugins in a running session, or start a new one. Astrolabe also checks for its own new release once a day and offers a button for it (see Update notices).
claude plugin uninstall astrolabe@astrolabe
claude plugin marketplace remove astrolabe
An install read from a folder runs the code on disk, but a session keeps the module it loaded. With autoReload on (the default), Astrolabe compares the version on disk with its own after each turn and runs /reload-plugins once when they differ, so a pull or a new release loads by itself. The first version with this check needs one /reload-plugins of your own.
To try a working copy, add the folder as a marketplace. Claude Code then reads the plugin from that folder, so edits show after /reload-plugins:
git clone https://github.com/jonyfs/astrolabe ~/src/astrolabe
claude plugin marketplace add ~/src/astrolabe
claude plugin install astrolabe@astrolabe
For a one-off session without installing, run claude --plugin-dir ~/src/astrolabe.
Astrolabe adds one entry to the status line under the prompt. Claude Code puts the mod's name in front of it. With the footer in the pane (footerIn=pane, the default) the entry is the lead and nothing else: the feature, its phase and percentage, and the window that decides.
⚠ astrolabe: ◆ 002 implement 45% │ 7d 81%▴ hold · Mon 07:00
It follows the band's tiers. From 144 columns it is the line above. At 100 columns the phase takes its short form and the reset goes (◆ 002 impl 45% │ 7d 81%▴ hold); below 100 the phase goes too (◆ 002 45% │ 7d 81%▴ hold). The id and the deciding window are never dropped. With footerIn=status or both the whole footer draws here, in the form the table describes, from left to right:
| Part | Example | What it means |
|---|---|---|
⚠ astrolabe: | Drawn by Claude Code, not by the mod. It marks a line that a mod wrote, and it names the mod. | |
◆ | The Spec Kit marker. Every Astrolabe entry starts with it. | |
| Feature id | 001 | The three-digit number of the active feature, from its folder name specs/001-core-state/. The Spec Kit part is at most 68 characters with the ⚠ astrolabe: prefix, and the usage part adds at most 18 more, so it fits whole at 100 columns and wider; Claude Code cuts what does not fit. |
~ before the id | ~002 | The feature was guessed. .specify/feature.json exists but is broken or points at a folder that is not there, so Astrolabe fell back to the git branch or the newest open feature. Fix or delete feature.json and the ~ goes away. |
| Phase | implement | The first Spec Kit step this feature has not finished. See Phases. |
| Percentage | 87% | Ticked tasks out of all tasks in the feature's tasks.md, rounded down. 43 of 49 is 87%. It appears only once tasks.md has tasks. |
| Running step | · plan… | A Spec Kit skill such as /speckit-plan was called during this turn. It disappears when the turn ends. |
| Usage window | │ 7d 81%▴ hold (Mon 14:00) | The window that decides, its mark (▵ from 60%, ▴ from the window's hold level, 80% by default), its band when it is not ok, and when it resets: a countdown such as 2h13m when the reset is less than a day away, else the weekday and time. A window at or past 100% reads full. The other window follows. See Usage governance. |
| Context | │ 61% | How full the context window is. Past 85% it reads 86% compact soon. |
| Model and effort | │ opus 5.5 high | The model and effort of Claude's last request in the main thread. With the 1M context window it reads opus 5.5 1M. |
| Running skill | │ ⟳ implement · sonnet 5.5 | The Spec Kit or gstack skill running now, with the model skillModels picked for it. |
| Git | │ main ↑2 3 | The branch, commits to push and to pull, and changed or untracked files, from one git status at the end of each turn. Without a repository it is left out. |
| Burn rate | │ 🔥 12/h → 96% | Usage points an hour over the session, and where the window that decides will be at its reset at that pace. It shows once the session has two readings that rise. |
| Duration | │ 1h05m | How long the session has run, from its first minute on. |
The band, the status entry, the footer, the spinner, the pane and the toasts share one set of marks, formats and keys, so a value reads the same wherever it appears.
| What | Rule | Example |
|---|---|---|
| Usage level | One ramp for context, 5h, 7d and the spend limit. Below 60% no mark and the done colour; from 60% yellow with ▵; from the window's hold level (80% by default) the blocked colour with ▴; at 100% or more the figure reads full. A threshold set in governThresholds moves the ramp of that window. | 5h 42%, 5h 72%▵, 7d 81%▴ hold, 7d full▴ ceiling |
| Muted text | The faint colour role, at least 4.5:1 on the flavor's base in all five flavors. The dimmer pending role draws only rules, separators and glyphs. | abandoned rows, the legend, loading rows |
| State glyphs | One cell wide in every icon set, so a row never shifts when its state changes: ‖ paused, ◷ time running, ▲ warning. | ▸ T010 Write x.ts ◷ 12m |
| Ids | A task id is shown as written in tasks.md (T011). Feature ids are padded with spaces to the widest id in the project, 3 or 4 digits, and are never cut: the name is cut first. | ◐ 002 band-hint, ◐ 1000 long-name |
| Durations | 40s, 4m12s, 2h09m; whole minutes drop the zero seconds (4m); unknown is ?. A reset under a day counts down; beyond a day it names the weekday and time. | 2h09m, Thu 18:00 |
| Phases, when room is short | spec, clar, plan, tasks, impl. | ◆ 002 · impl 45% |
| Keys | r refresh, q run a queued subagent (the first queued run takes q), ? help (pressed as h), / filter (pressed as f), c clear, o order, p priority, a advisor, space page, Esc close. | ? help (h), / filter (f) |
| Messages | Toasts start with astrolabe ✓ for a state or success and astrolabe ▲ for a warning. | astrolabe ✓ 002 band-hint moved to tasks · next: /speckit-tasks |
| Separators | │ between zones, · inside one, never both in one zone. In the footer each chip is a zone. | ◆ 002 · implement 45% │ 5h 92%▴ ceiling · paused until 14:00 |
Astrolabe bundles the statusline project under vendor/statusline/ and, by default, lets it draw the pane footer. Astrolabe keeps its own lead on the first row (the Spec Kit part, the window that decides, the advisor, the help hint) and statusline's lines go below it, with its segments, ranks, colours, shedding and links:
◆ 002 · implement 45% │ astrolabe 0.140.0 │ /astrolabe help
⌂ astrolabe jonyfs/astrolabe ⎇ 070-statusline-dependency ●3 +7 PR #160 draft ✓ CI
◆ 059 specify ❖ humanizer, dataviz ▸ Fix authentication (1/3) ● working
opus 5.5 · high ctx 41% 5h 72%▵ · 2h09m 7d 84%▴ · Thu 18:00 cache warm · 1m 1h12m
It needs Node 18 or newer. Without it, with a missing copy, with the colorblind flavor (statusline has none) or when the renderer fails, the footer is Astrolabe's own and the Setup tab says why. footerSource picks the source:
| Value | The pane footer is |
|---|---|
statusline (default) | Astrolabe's lead and the bundled statusline's lines |
native | Astrolabe's own chips (specs 041, 064, 068) |
What you give up with statusline: the hover explanation rows, the brighten-on-change rule, the full text of a cut chip and the governor's colour levels (statusline's own are 60 and 85 percent; the governor still acts at 60, 80 and 88). Its links (branch, pull request, repository, CI) stay. The status entry under the prompt is always Astrolabe's own one line.
What it is given. Besides the model, the effort, the context window and the usage windows, Astrolabe sends the path of the session's transcript (where Claude Code writes it, under CLAUDE_CONFIG_DIR or ~/.claude), the session's duration, the lines its tools changed and whether fast mode is on. With them statusline draws the active skills, the activity chip, the duration, +n −n and fast, as it does under Claude Code's own status line. A fact Astrolabe does not have is left out, never zeroed. The cache chip and the vim mode are not drawn: the mod does not hand statusline the prompt cache's own figures or the editor mode.
How the renderer answers. Astrolabe asks for statusline's data form (CLAUDE_STATUSLINE_OUTPUT=runs, statusline spec 056): one JSON object of lines of styled runs, or an error object with exit code 75. It reads that without parsing escapes and tells a failure from a footer by the object, not by comparing text. A copy that predates the form prints ANSI text and is read as before; a copy that answers with a newer contract than Astrolabe reads falls back to the Astrolabe footer, and the Setup tab says so. The Setup tab shows which form the copy answered in.
Updates. There is no download at run time. A workflow refreshes vendor/statusline/ weekly through a pull request, runs a contract test against it, and the copy ships with the next release; the Setup tab shows the version and commit in use.
What it does on your machine. statusline writes its caches under ~/.claude/statusline/ and starts git, gh and rtk probes in detached processes to fill its pull request, CI and savings segments, as it does when it is Claude Code's statusLine. Astrolabe turns its own update check off and sends it only the session figures it has (model, context, usage windows, folder), so segments that read the transcript (skills, todo, working) appear only where the engine hands that path over.
Use it as Claude Code's own statusLine. /astrolabe statusline prints the command for the bundled copy and the line to put in settings.json; Astrolabe never writes it:
> /astrolabe statusline
statusline 1.53.1 (2b565f2) is bundled with Astrolabe.
Command: node "/home/you/.claude/plugins/astrolabe/vendor/statusline/bin/cli.js"
{
"statusLine": {
"type": "command",
"command": "node \"/home/you/.claude/plugins/astrolabe/vendor/statusline/bin/cli.js\""
}
}
By default the bundled statusline runs as it does under Claude Code: its pull request, CI, gate and rtk chips come from a cache that background gh and rtk processes fill, and it writes under ~/.claude/statusline/. Set footerStatuslineMode to passive when you want a footer that starts nothing but read-only git and writes only in a folder of this plugin (statusline-cache inside the plugin's data folder). The git snapshot and the session state persist between redraws there. The pull request, CI, gate and rtk chips are not drawn in that mode, and the Setup tab says so.
footerOmit takes segment keys separated by commas (for example sevenDayReset,model) and leaves them out of the footer; the width goes to the other chips. The Setup tab also shows what the bundled copy resolved for the footer (flavor, glyphs, separator, omitted segments), read from its --print-config at most once a minute, and says when the flavor you asked for is not the one drawn. Both options are empty or live by default, so nothing changes unless you set them.
The footer carries what a statusline under the prompt usually shows, so you can remove a separate statusLine command from your settings. By default it sits at the bottom of the /astrolabe pane, under every tab, and the status entry keeps only the Spec Kit part and the window that decides (◆ 002 · implement 45% │ 5h 42% (2h13m)). Set footerIn to status to put the whole footer back in the status entry, or both for both places. On a tab shorter than the pane the footer holds the last rows; the Dashboard is longer, so its footer follows the charts.
In the pane the footer is drawn the way the statusline project draws its bar: Powerline chips in Catppuccin colours. Spec Kit is mauve, the model red, git lavender, and the usage windows and the context follow statusline's ramp: green below 60%, yellow from 60% to 80% (5h 72%▵), red from 80% (5h 94%▴), where 80% is the window's hold level. The context takes the colour without the mark. The flavor option picks the palette; with ascii icons, the accessible mode or the NO_COLOR environment variable set, the footer is plain text with │ between the parts.
With footerLines set to 3 the footer draws statusline's three lines, each chip its own zone:
⌂ astrolabe │ jonyfs/astrolabe │ git:063-statusline-parity │ ~3 ✖2 ⇡2 ⇣5 │ +156 −23 │ PR #41 draft · ux │ ✓ CI
◆ 059 · specify │ ❖ humanizer, dataviz, mermaid +2 │ ▸ Fix authentication (1/3)
opus 5.5 · high · fast │ ctx 41% │ 5h 72%▵ (2h09m) │ 7d 84%▴ (Thu 18:00) │ cache warm · 1m │ ⇡ 9%/h │ 5h limit ~16:40 │ t 1h12m
Line one is the place and git, line two the work, line three the model and the limits. Each part appears only when it has something to say:
✖2 counts merge conflicts apart from ~3 changed files. ⇡2 and ⇣5 are commits ahead of and behind the upstream, and show only when the branch has one. A detached HEAD shows its short commit id, and a linked worktree shows the branch of the main checkout it came from.⌂ src ⇐ astrolabe after it moved from the folder the session started in.PR #41 draft · ux carries the pull request's draft state and first labels. ✓ CI, ✖ CI or ◷ CI is the last run of the current branch. Both need the pullRequest option and gh.❖ humanizer, dataviz +2 is the skills used in this session, five names and then a count. The todo chip ▸ Fix authentication (1/3) is the todo list's current item and its progress.fast follows the effort while fast mode is on. It shows only when the model request says so (speed: fast); a session whose requests do not name it never shows the chip.⇡ 9%/h is the burn rate, shown after five usage readings over at least a minute. 5h limit ~16:40 is the projection and shows only when the window would fill before it resets.cache warm · 1m in the last two minutes of a five-minute cache, and cache cold · 182k once it expired, with · model changed when a model switch caused it. It rests on the usage of each answer; the engine gives a mod nothing else about the cache, so a cache Astrolabe never saw answer shows no chip.A branch, PR, skills or model chip that changed draws a shade lighter for 30 seconds. Usage chips never do. Point at a chip and a row under the footer explains it in one sentence: ↳ The prompt cache: warm means the next prompt reuses it; cold means .... With the ascii icon set the marks above become dir, <-, ^, v, !, ok, .., * and >.
When the room is too narrow, chips go in this order: the version and help hint, repository name, duration, lines changed, projection, CI, PR, burn rate, advisor, the tree counters and the cache. The context, branch, directory, 5h and 7d windows and the model stay. The Spec Kit part and the window that decides always stay.
| A statusline showed | In Astrolabe |
|---|---|
| Directory, repository, branch, ahead and behind, changed files, conflicts, stashes, worktree | Line one of the footer |
| Model, effort, fast mode, context window | Line three |
| 5-hour and 7-day windows with their resets | Line three, and the governor acts on them |
| Session duration | Line three (Astrolabe shows no cost: on a subscription it means nothing) |
| Burn rate and projection | Line three, and the Dashboard tab |
| Todo progress, Claude working or idle | Line two, the band, the spinner and the tasks under their spec |
| Skills in use | Line two, with the running Spec Kit skill in the band |
| Pull request, draft state and last CI run | Line one with the pullRequest option on |
| Prompt cache timer | The cache chip, and a toast 30 seconds before the cache goes cold (see Toasts) |
| Vim mode, rtk savings | Left out |
The git part reads like this with icons set to ascii:
git:023-git-footer │ ~3 ^2 │ stash:1 │ wt:review │ PR #32 ok
~3 and ^2 are changed files and commits ahead, stash:1 is one stash entry, and wt:review says the checkout is the linked worktree review. PR #32 ok is the branch's open pull request with every check passed; x means one failed and .. that some are still running. The pull request part needs the pullRequest option and the gh command, signed in. Astrolabe asks gh at most once every five minutes per branch, on a timer after the turn, so a slow network never holds the footer. Without gh, or with no pull request for the branch, the part is left out.
Icons follow the icons option: Nerd Font glyphs in the terminal and emoji in the Desktop app by default, or ascii for plain characters everywhere. A Nerd Font cannot be detected, so pick emoji or ascii if the glyphs show as boxes.
The other entries you may see:
| Entry | When |
|---|---|
◆ no Spec Kit | No folder from the session's directory up to the filesystem root holds a .specify/ directory. Nothing else is read. The band only shows update buttons, if any (image below). |
◆ no active feature · next: /speckit-specify | Spec Kit is set up, but every feature is done or abandoned, or there are none yet. The command after next: is the one to run. |
◆ no active feature · next: /speckit-constitution | Same, and the constitution is missing or still the unfilled template. |
◆ 003 · abandoned | feature.json names a feature whose spec says status: abandoned. A percentage follows when it has tasks (◆ 003 · abandoned 40%). |
◆ 001 · done 100% | feature.json names a finished feature. Run /speckit-specify for the next one. |
… │ 5h 42% | The fuller usage window, with its mark and band when it is not ok (5h 83%▴ hold). See Usage governance. |
The phase is read from the files on disk, top to bottom; the first rule that matches wins.
| Rule | Phase | What to run next |
|---|---|---|
spec.md front matter says status: abandoned | abandoned | /speckit-specify for a new feature |
spec.md front matter says status: done | done | /speckit-specify |
No spec.md | specify | /speckit-specify |
Front matter says track: quick | implement | /speckit-implement, until you set status: done |
No plan.md, and spec.md still has [NEEDS CLARIFICATION | clarify | /speckit-clarify |
No plan.md | plan | /speckit-plan |
No tasks.md, or no tasks in it | tasks | /speckit-tasks |
| Some tasks open | implement | /speckit-analyze before the first tick in a session, then /speckit-implement |
All ticked, front matter says status: active | implement (100%) | Set status: done when you agree it is finished |
| All ticked | done | /speckit-specify |
Astrolabe reads every feature once when the session starts. At the end of each turn it re-reads feature.json, the constitution, the specs/ listing, the active feature, and any other feature a tool touched during the turn, so a box you tick in another editor shows up when the next turn ends. While a turn runs, an edit or write by Claude to spec.md, plan.md or tasks.md updates the entry right after that tool call.
A project with 40 features costs one full read per session and a handful of file reads per turn.
The band is one row directly above the
hooks/register.tsx 4858 lines1// Wires engine events to the io layer, the core and the status surface. No business logic.
2// The engine follows $ only into functions declared in this file, so every $ call lives here.
3import { ABOUT, helpText } from './modules/help'
4import { otherFeatureNamed, implementRefusal, canTouchSpecs, mayChangeGit, mayWriteFiles, isUnderSpecify } from './modules/guards'
5import { advisorFindings, advisorPrompt } from './modules/advisor'
6import { featureContext, principlesOf, tickedBy, statusText } from './modules/context'
7import { historyRows, minutes } from './modules/history-rows'
8import { readFeatureDurations } from './modules/durations'
9import { withPr, worktreesById, filtered } from './modules/pane-data'
10import type { ConfigRow, EngineInterface, Hook, Register, RenderNode } from 'claude-code'
11
12import { bandPr, bandSegments, bandText, nextReason, otherFeaturesCard, stepCards, type BandDensity } from './core/band'
13import { hintTail } from './core/hint'
14import { phaseToasts } from './core/phase-toast'
15import { justFinished } from './core/next-command'
16import { DEFAULT_STATUS, filterChips, filterFeatures, helpRows, moveSpecSelection, nextSort, nextStatus, parseSpecFilter, windowUnits, wrappedRows, type PaneRow, sessionRows, specsRows } from './core/pane'
17import { allToggled, breadcrumb, doTaskSuggestion, isOpen, questionSuggestion, questionsIn, spaced, specChildren, tickSuggestion, toggled, withChildren, type Fold, type TreeTask } from './core/pane-tree'
18import { presetOf } from './core/presets'
19import { parseTasks, ticksIn } from './core/tasks-parser'
20import { spinnerSuffix } from './core/spinner'
21import { bandUpdateLabel, astrolabeUpdate, firstLine, isDue, isStoredUpdates, localDay, parseCliVersion, parseGstackCheck, parseSelfCheck, skillsVersusCli, releaseNotesUrl, skillsUpdate, updateLabel } from './core/updates'
22import { fileUrl, joinPath } from './core/paths'
23import { closeAllSuggestion, closeSuggestion, configMark, reconcileSuggestion, nextFor, planFiles, nextPriority, skillsForPhase, specDetail, OPTION_GROUPS, optionDefaults, optionGroup, parallelPrompt, parsePriority, REVIEW_MODEL, reviewPrompt, withPriority, type OptionGroup, type Priority } from './core/spec-actions'
24import { parallelTasks } from './core/extensions'
25import { VERSION } from './core/version'
26import { QUEUE_HOTKEYS } from './core/keys'
27import { duration } from './core/duration'
28import { STATE_GLYPHS } from './core/glyphs'
29import { statusLead } from './core/status-lead'
30import { withThumb } from './core/thumb'
31import { displaySectionOf, isReadyToClose } from './core/sections'
32import { blockLabel, jumpLine, jumpMatches, jumpQuery, nextGroup } from './core/specs-scale'
33import { usageBarRows } from './core/usage-bars'
34import { deciderNote, governorBoxState, nextLevelText, projectHeader, sessionChips, todayCounts, trend24h } from './core/session-usage'
35import { badgesOf, escapeStep, legacyTab, paneTitle, TABS } from './core/pane-tabs'
36import { parseClientOp, type ClientOp } from './core/pane-client'
37import { changedSettingsJson, LOOK_PRESETS, nextOptionValue, optionConflicts, OPTIONS_README, presetMatching } from './core/setup-extras'
38import { usageRamp } from './core/usage-ramp'
39import { ASK_MS, clockOf, decide, dropped, EXTEND_MS, HOLD_LIFT_MS, holdQuestion, labelOf, nextHeld, isPaused, isReadOnlyTool, parseAllow, pauseQuestion, RAISE_MS, refusal, resumePrompt, runPrompt, usageSegment, type Decision, type Question, usageRows } from './core/governor'
40import { ANSI_16, chipForeground, CHIPS, FLAVORS, flavorOf, isThemeKeys, lighten, STATUS_ROLE, themeOf, type ThemeRole } from './core/theme'
41import { capDiff, DIFF_FOLD_MS, foldedDiff, recapLine, recapOf, tasksDiff } from './core/summary'
42import { styleSections } from './core/style'
43import { ageOf, parsePullList, primaryPullAction, prOpened, pullAction, pullsBySpec, specOfBranch, PR_LIST_FIELDS } from './core/pulls'
44import { EFFORTS, familyOf, MODEL_FAMILIES, modelForTask, skillModelFor, skillNameOf, SKILL_MODELS, type SkillOverrides } from './core/skill-models'
45import { featureDirFor, mergedBranches, parseWorktrees, uncommittedCount, withWorktreeProgress, worktreeName, worktreeState } from './core/worktrees'
46import { readFeature } from './io/snapshot'
47import { deriveSpeckitState, snapshotFromMemo } from './core/speckit'
48import { deriveFeature } from './core/phase'
49import { chartImage, dialFrames, imagesFor } from './core/pixels'
50import { emptyMemo, type Feature, type PaneState, type PaneTab, type PaneView, type UpdateId, type UpdateItem, type UpdatesState, type UsageState, type UsageReading, type QueuedAgent, type SessionStats, type SpeckitState, type FooterState } from './core/types'
51import type { Preset } from './core/presets'
52import type { Fs } from './io/fs-port'
53import { findRoot } from './io/root'
54import { nodeStatus, readResolvedConfig, renderFooter, type RunProc } from './io/statusline-run'
55import { buildPayload, chooseSource, cutRuns, flavorMismatch, joinDir, parseOmit, statuslineEnv, SUPPORTED_CONTRACT, transcriptPathFor, type ResolvedConfig, type Run, type SourceReason } from './core/statusline-dep'
56import { activeFilesChanged, applyFileTouch, applyRead, applyShell, applySkill, type Held, reconcileDeferred, reconcileNow, reconcileStart, reconcileTurn } from './io/reconcile'
57import { bandRow, edgeWidth, type BandEdge } from './surfaces/band'
58import { askTree } from './surfaces/ask'
59import { dashboardSections, dashboardTree } from './surfaces/dashboard'
60import { burnRate, dial, kpiChips, kpisMarkdown, phaseBars, sparkline, usageChart, kpiRows, trendRows } from './core/dashboard'
61import { addDay, addWeek, dayKey, lastWeeks, pastReset, slowest, updateFeatureDurations, weekKey, weekdays, type Days, type FeatureDuration, type Weeks } from './core/history'
62import { footerChipLines, footerChips, footerText, linesChanged, type FooterInput } from './core/footer'
63import { detectGates, layoutLive, liveRows, liveTextRows, parseProcesses, type LiveColumn, type LiveRowsOption } from './core/live-table'
64import { liveTable } from './surfaces/live-table'
65import { branchWebUrl, parseCiRun, parseGitStatus, parsePullRequest, plainText, remoteWebUrl } from './core/git-status'
66import { iconSet, iconsFor } from './core/icons'
67import { guessLang, langOf, paneLabelWidth, t, type Lang, type TextKey } from './core/i18n'
68import { paneTree } from './surfaces/pane'
69import { activeMark, formatStatus } from './core/status-text'
70import { formatToast } from './core/toasts'
71import { type FooterOwner, footerOwnerOf, parseFooterOwner, statuslineConfigured } from './modules/footer-owner'
72
73const SPECKIT = { plugin: 'astrolabe', key: 'speckit' } as const
74// The session memo lives apart from what drawings read, so no redraw carries it (spec 009).
75const MEMO = { plugin: 'astrolabe', key: 'memo' } as const
76const PANE_STATE = { plugin: 'astrolabe', key: 'pane' } as const
77const PANE_ID = 'astrolabe'
78const PANE_TITLE = '🧭 Astrolabe'
79const ASK_ID = 'astrolabe-usage'
80// The queued run letters come from core/keys.ts: `q` first, never `b` (it pages back, 043 #29).
81/** `/astrolabe doctor` (048 #79): what Astrolabe needs, each line with the fix when it is missing. */
82/** The doctor's checks, one line each; `doctor` and the Help tab's Health block share them (052 #42). */
83async function doctorLines($: EngineInterface): Promise<string[]> {
84 const probe = (argv: string[]) =>
85 $.process.run(argv, { timeoutMs: 3000 }).catch(() => ({ exitCode: 127, stdout: '', stderr: 'not found' }))
86 const [git, gh, specify] = await Promise.all([probe(['git', '--version']), probe(['gh', '--version']), probe(['specify', 'version'])])
87 const auth = gh.exitCode === 0 ? await probe(['gh', 'auth', 'status']) : undefined
88 const state = (await $.state.get(SPECKIT)).value
89 const lines: string[] = []
90 const check = (isOk: boolean, text: string, fix: string) => lines.push(isOk ? ` ✓ ${text}` : ` ✗ ${text}: ${fix}`)
91 check(git.exitCode === 0, git.exitCode === 0 ? firstLine(git.stdout) : 'git not found', 'install git from https://git-scm.com')
92 check(gh.exitCode === 0, gh.exitCode === 0 ? firstLine(gh.stdout) : 'gh not found', 'install the GitHub CLI from https://cli.github.com for the PRs tab and the pullRequest option')
93 if (auth !== undefined) check(auth.exitCode === 0, auth.exitCode === 0 ? 'gh signed in' : 'gh not signed in', 'run gh auth login')
94 check(specify.exitCode === 0, specify.exitCode === 0 ? `specify ${firstLine(specify.stdout)}` : 'specify not found', 'install Spec Kit: uv tool install specify-cli --from git+https://github.com/github/spec-kit.git')
95 check(state?.present === true, state?.present === true ? `Spec Kit project at ${state.root ?? '?'}` : 'no Spec Kit project here', 'run specify init --here')
96 // The project's skills against the CLI (054 #98), named when they differ.
97 if (state?.root !== undefined && specify.exitCode === 0) {
98 const manifest = await $.fs.read(`${state.root}/.specify/integrations/speckit.manifest.json`).catch(() => undefined)
99 const versions = skillsVersusCli(typeof manifest === 'string' ? manifest : undefined, parseCliVersion(specify.stdout))
100 if (versions !== undefined) {
101 check(
102 versions.behind === 'none',
103 versions.behind === 'none' ? `Spec Kit skills match the CLI (${versions.cli})` : `Spec Kit skills ${versions.skills}, CLI ${versions.cli}`,
104 versions.behind === 'skills' ? `refresh the skills: ${SKILLS_REFRESH.join(' ')}` : 'upgrade the CLI: uv tool upgrade specify-cli',
105 )
106 }
107 }
108 const icons = iconsFor(iconsOption, 'terminal')
109 lines.push(` · icons: ${icons}${icons === 'nerd' ? ' (needs a Nerd Font in the terminal; set icons to emoji or ascii if glyphs show as boxes)' : ''}`)
110 const set = Object.entries(optionsSeen).filter(([, v]) => v !== undefined)
111 lines.push(` · options: ${set.length === 0 ? 'all defaults' : set.map(([k, v]) => `${k}=${String(v)}`).join(', ')} (change them in /config or the Config tab)`)
112 // The hook budget (054 #15): the engine gives each hook 10 s.
113 check(slowestHook === undefined || slowestHook.ms < 5000, slowestHook === undefined ? 'no hook work timed yet' : `slowest hook work: ${slowestHook.name}, ${slowestHook.ms} ms of the 10 s budget`, 'a large project or a slow disk; /astrolabe status still works, and the Specs tab reads the rest later')
114 return lines
115}
116
117async function doctor($: EngineInterface): Promise<string> {
118 return ['🧭 Astrolabe doctor', ...(await doctorLines($))].join('\n')
119}
120
121/** Reads the doctor's checks into the session for the Help tab, at most once a minute (052 #42). */
122async function refreshHealth($: EngineInterface): Promise<void> {
123 const now = await $.clock.now()
124 const held = (await $.state.get(SESSION)).value?.health
125 if (held !== undefined && now - held.at < 60_000) return
126 const lines = await doctorLines($).catch(() => undefined)
127 if (lines !== undefined) await flushStats($, s => ({ ...s, health: { at: now, lines } }))
128}
129
130const WELCOMED = 'welcomed'
131/** How many sessions have started; the footer's help chip shows for the first three (052 #46). It rides in the `welcomed` value (`0.118.0|2`), so the store keeps one key. */
132let sessionNumber = Number.POSITIVE_INFINITY
133const ASK = { plugin: 'astrolabe', key: 'ask' } as const
134const DEFAULT_PANE: PaneState = { tab: 'specs', autoOpened: false }
135
136/** The filters `m` cycles (078 FR-034), and the name each one shows. */
137const PRESET_FILTERS = ['', 'is:active', 'has:questions', 'is:ready'] as const
138const PRESET_OF: Readonly<Record<string, 'all' | 'mine' | 'blocked' | 'ready'>> = { '': 'all', 'is:active': 'mine', 'has:questions': 'blocked', 'is:ready': 'ready' }
139const UPDATES = { plugin: 'astrolabe', key: 'updates' } as const
140const UPDATES_STORE = 'updates'
141const RELEASES_URL = 'https://api.github.com/repos/jonyfs/astrolabe/releases/latest'
142const UPDATES_HIDDEN = 'updates:hidden'
143const SKILLS_REFRESH = ['specify', 'init', '--here', '--integration', 'claude', '--force']
144const USAGE = { plugin: 'astrolabe', key: 'usage' } as const
145const QUEUE_MAX = 20
146const DEFAULT_USAGE: UsageState = { readings: [], history: [], inFlight: 0, queue: [], paused: false }
147const HISTORY_POINTS = 10
148const SESSION = { plugin: 'astrolabe', key: 'session' } as const
149const FOOTER = { plugin: 'astrolabe', key: 'footer' } as const
150const SERIES_POINTS = 60
151const HISTORY = 'history'
152const DAYS = 'days'
153const FEATURE_DURATIONS = 'feature-durations'
154// The disk version the plugins were last reloaded for (034).
155const RELOADED = 'reloaded'
156// Who draws the footer once jonyfs/statusline is installed (050 #97): 'astrolabe' or 'statusline'.
157const FOOTER_OWNER = 'footerOwner'
158let footerOwner: FooterOwner = 'astrolabe'
159const GIT_STATUS = ['git', 'status', '--porcelain=v2', '--branch', '--show-stash']
160// The branch's pull request and its checks (023), opt-in, at most once per five minutes per branch.
161const GH_PR = ['gh', 'pr', 'view', '--json', 'number,url,statusCheckRollup,isDraft,labels']
162// The branch's last CI run (068 #41), read with the pull request: at most once per five minutes.
163const GH_RUN = (branch: string): string[] => ['gh', 'run', 'list', '--branch', branch, '--limit', '1', '--json', 'status,conclusion']
164const PR_TTL_MS = 300_000
165
166// The session's numbers between writes (018): a tool call costs no state write; they are
167// written at the end of each main turn and at each measure. A reload loses one turn's counts.
168const live = { toolCalls: 0, drifts: 0, driftsById: {} as Record<string, number>, agentsRun: 0, agentsById: {} as Record<string, number>, ticksMain: 0, ticksSub: 0, agentsQueued: 0, linesAdded: 0, linesRemoved: 0, model: undefined as string | undefined, effort: undefined as string | undefined, skills: [] as string[], todo: undefined as SessionStats['todo'], cache: undefined as SessionStats['cache'], fast: undefined as boolean | undefined, dirs: undefined as SessionStats['dirs'] }
169// The footer's room: the last width a drawing saw, less the warning mark and "astrolabe: " the terminal adds.
170let columnsSeen = 120
171let surfaceSeen: string | null = 'terminal'
172let iconsOption: unknown = 'auto'
173// The person's language (019): the `language` option, or the guess from their prompts.
174let languageOption: unknown = 'auto'
175let guessedLang: Lang | undefined
176const currentLang = (): Lang => langOf(languageOption, guessedLang)
177
178/** A reading whose window has already reset: the bars skip it (it reads `renewed` elsewhere). */
179const isRenewedReading = (r: UsageReading, now: number): boolean => r.resetsAt !== undefined && Date.parse(r.resetsAt) <= now
180
181const decisionOf = (usage: UsageState, now: number): Decision =>
182 decide(usage.readings, usage.history, usage.override, now, usage.holdLift, usage.held, governThresholds)
183
184const STATUS_COALESCE_MS = 200
185let statusWindowUntil = Number.NEGATIVE_INFINITY
186let statusTimer: ReturnType<EngineInterface['clock']['after']> | undefined
187let pendingStatus: Held['state'] | undefined
188
189/** The window an override is given for: the one binding now (016); none known, every window. */
190type GovernThresholdsMap = Record<string, { hold?: number; stop?: number }>
191// The parsed options, set in register (047 #66, #67).
192let governThresholds: GovernThresholdsMap = {}
193let quietHours: { start: number; end: number } | null = null
194const isQuietHours = (): boolean => {
195 if (quietHours === null) return false
196 const now = new Date()
197 const minutes = now.getHours() * 60 + now.getMinutes()
198 return quietHours.start <= quietHours.end
199 ? minutes >= quietHours.start && minutes < quietHours.end // e.g., 09:00-17:00
200 : minutes >= quietHours.start || minutes < quietHours.end // e.g., overnight 22:00-06:00
201}
202const kindOf = (usage: UsageState, now: number, governThresholds?: GovernThresholdsMap): { kind?: string } => {
203 const kind = decide(usage.readings, usage.history, usage.override, now, usage.holdLift, usage.held, governThresholds).highest?.kind
204 return kind === undefined ? {} : { kind }
205}
206
207/** The status entry: the footer of spec 018, the Spec Kit part first (008, 018). */
208async function drawStatus($: EngineInterface, state: Held['state']): Promise<void> {
209 if (footerOwner === 'statusline') return
210 // With the footer in the pane (035), the status entry keeps only what is never dropped.
211 const [usage, stats] = await Promise.all([$.state.get(USAGE), $.state.get(SESSION)])
212 if (footerIn === 'pane' && columnsSeen < WIDE_STATUS_COLUMNS) {
213 // The lead only (065 #15): feature, phase, percentage and the deciding window. From 140 columns
214 // the status entry shows the whole footer on one line (054 #47).
215 const now = await $.clock.now()
216 const decision = decisionOf(usage.value ?? DEFAULT_USAGE, now)
217 const kind = decision.highest?.kind
218 $.ui.status(statusLead(state, decision.highest === undefined ? undefined : decision, Math.max(20, columnsSeen), now, currentLang(), kind === undefined ? undefined : governThresholds[kind], 14))
219 return
220 }
221 $.ui.status(footerText({ ...(await footerInput($, state, Math.max(20, columnsSeen - 14), { usage: usage.value ?? DEFAULT_USAGE, stats: stats.value })), lead: false }))
222}
223
224async function showStatus($: EngineInterface, state: Held['state']): Promise<void> {
225 currentTaskText = state.currentTask?.text
226 const now = await $.clock.now()
227 if (now >= statusWindowUntil) {
228 statusWindowUntil = now + STATUS_COALESCE_MS
229 await drawStatus($, state)
230 return
231 }
232 pendingStatus = state
233 if (statusTimer !== undefined) return
234 statusTimer = $.clock.after(statusWindowUntil - now, () => {
235 statusTimer = undefined
236 const latest = pendingStatus
237 pendingStatus = undefined
238 if (latest === undefined) return
239 statusWindowUntil += STATUS_COALESCE_MS
240 void drawStatus($, latest).catch(error => {
241 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
242 })
243 })
244}
245
246/** What the footer shows, for the status entry and the pane alike (018, 035). */
247async function footerInput(
248 $: EngineInterface,
249 state: Held['state'],
250 width: number,
251 snapshot: { usage: UsageState; stats?: SessionStats },
252): Promise<FooterInput> {
253 const { usage, stats } = snapshot
254 const now = await $.clock.now()
255 return {
256 speckit: columns => formatStatus(state, columns, currentLang()),
257 lang: currentLang(),
258 readings: usage.readings,
259 decision: decisionOf(usage, now),
260 ...(stats?.context === undefined ? {} : { context: stats.context }),
261 ...(stats?.model === undefined ? {} : { model: stats.model }),
262 ...(stats?.effort === undefined ? {} : { effort: stats.effort }),
263 ...(stats?.git === undefined ? {} : { git: stats.git }),
264 ...(stats?.lines === undefined ? {} : { lines: stats.lines }),
265 ...(stats?.dirs === undefined ? {} : { dir: { path: stats.dirs.cwd, start: stats.dirs.start } }),
266 ...(stats?.git?.remote === undefined ? {} : { repo: stats.git.remote }),
267 ...(stats?.skills === undefined || stats.skills.length === 0 ? {} : { skills: stats.skills }),
268 ...(stats?.todo === undefined || stats.todo.total === 0 ? {} : { todo: stats.todo }),
269 ...(stats?.cache === undefined ? {} : { cache: stats.cache }),
270 ...(stats?.fast === true ? { fast: true } : {}),
271 ...(stats === undefined ? {} : { burnSamples: { count: stats.series.length, spanMs: stats.series.length < 2 ? 0 : stats.series[stats.series.length - 1]!.at - stats.series[0]!.at } }),
272 ...(stats?.advisor === undefined || stats.advisor.runs === 0 ? {} : { advisor: { runs: stats.advisor.runs } }),
273 astrolabe: { version: VERSION },
274 ...(stats === undefined ? {} : { startedAt: stats.startedAt }),
275 ...(sessionNumber <= 3 ? { helpHint: true } : {}),
276 ...((rate => (rate === undefined ? {} : { burn: rate }))(stats === undefined ? undefined : burnRate(stats.series))),
277 ...(state.runningSkill === undefined
278 ? {}
279 : { skill: { name: state.runningSkill.name, ...((m => (m === undefined ? {} : { model: m }))(skillModels === 'auto' ? skillModelFor(state.runningSkill.name, skillOverrides)?.model : undefined)) } }),
280 now,
281 icons: iconSet(iconsFor(iconsOption, surfaceSeen as never)),
282 columns: width,
283 thresholds: governThresholds,
284 }
285}
286
287// The live table (069): which rows it draws, the widths its columns have needed, the gate scan.
288let liveRowsOption: LiveRowsOption = 'both'
289let liveReservation: Partial<Record<LiveColumn, number>> = {}
290let gateScanTimer: ReturnType<EngineInterface['clock']['after']> | undefined
291const GATE_SCAN_MS = 15_000
292// The last time a gate was seen, for the failed-gate toast (069 #44).
293let gateSeenAt: number | undefined
294let agentCounter = 0
295// Commands that may run a gate, running now.
296let gateCommands = 0
297
298// Where the footer goes (035): the pane (the status entry keeps the lead), the status entry, or both.
299let footerIn: 'pane' | 'status' | 'both' = 'pane'
300// The pane footer's rows (041 #1): one, or statusline's three lines.
301let footerLines: '1' | '3' = '1'
302// The rule above the pane footer's chips (041 #8).
303let footerSeparator: 'solid' | 'thin' | 'none' = 'solid'
304// A branch, PR, skills or model chip that just changed draws a shade lighter for 30 seconds
305// (041 #5, 068 #49), then settles; usage chips never brighten.
306const FRESH_MS = 30_000
307const BRIGHTEN_CHIPS: ReadonlySet<string> = new Set(['git', 'pr', 'skills', 'model'])
308const FRESH_SHARE = 0.25
309const chipAges = new Map<string, { text: string; at?: number }>()
310let freshDeadline: number | undefined
311let noColor = false
312
313/** Whether a chip's text just changed, or is still within a few seconds of its last change (041 #5). */
314const freshChip = (key: string, text: string, now: number): boolean => {
315 const entry = chipAges.get(key)
316 const changed = entry !== undefined && entry.text !== text
317 chipAges.set(key, { text, at: changed ? now : entry?.at })
318 return changed || (entry?.at !== undefined && now - entry.at < FRESH_MS)
319}
320
321/** Redraws the pane once the freshest chip settles (041 #5). */
322const scheduleFresh = ($: EngineInterface, now: number): void => {
323 const at = now + FRESH_MS
324 if (freshDeadline !== undefined && freshDeadline <= at) return
325 freshDeadline = at
326 $.clock.after(Math.max(0, at - now), () => {
327 freshDeadline = undefined
328 try {
329 $.ui.invalidate('ui.render')
330 } catch (error) {
331 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
332 }
333 })
334}
335
336// The options' defaults from plugin.json, read once at session start (052 #39).
337let defaultsSeen: Record<string, string | number | boolean> = {}
338let bandDensity: BandDensity = 'full'
339// How roomy the Specs list is (078 FR-096).
340let paneDensity: 'compact' | 'comfortable' = 'compact'
341let gitNeedsRefresh = true
342
343/** Writes what the session counted since the last write, merged with `change`, if anything moved. */
344async function flushStats($: EngineInterface, change: (s: SessionStats) => SessionStats = s => s): Promise<void> {
345 for (let attempt = 0; attempt < 5; attempt += 1) {
346 const { value, version } = await $.state.get(SESSION)
347 const now = await $.clock.now()
348 const before: SessionStats = value ?? { startedAt: now, turns: 0, toolCalls: 0, drifts: 0, agentsRun: 0, agentsQueued: 0, series: [] }
349 const counted: SessionStats = {
350 ...before,
351 toolCalls: before.toolCalls + live.toolCalls,
352 drifts: before.drifts + live.drifts,
353 ...(Object.keys(live.driftsById).length === 0
354 ? {}
355 : { driftsByFeature: Object.fromEntries([...new Set([...Object.keys(before.driftsByFeature ?? {}), ...Object.keys(live.driftsById)])].map(id => [id, (before.driftsByFeature?.[id] ?? 0) + (live.driftsById[id] ?? 0)])) }),
356 agentsRun: before.agentsRun + live.agentsRun,
357 ...(Object.keys(live.agentsById).length === 0
358 ? {}
359 : { agentsByFeature: Object.fromEntries([...new Set([...Object.keys(before.agentsByFeature ?? {}), ...Object.keys(live.agentsById)])].map(id => [id, (before.agentsByFeature?.[id] ?? 0) + (live.agentsById[id] ?? 0)])) }),
360 agentsQueued: before.agentsQueued + live.agentsQueued,
361 ...(live.ticksMain + live.ticksSub === 0
362 ? {}
363 : { ticksBy: { main: (before.ticksBy?.main ?? 0) + live.ticksMain, sub: (before.ticksBy?.sub ?? 0) + live.ticksSub } }),
364 ...(live.linesAdded + live.linesRemoved === 0
365 ? {}
366 : { lines: { added: (before.lines?.added ?? 0) + live.linesAdded, removed: (before.lines?.removed ?? 0) + live.linesRemoved } }),
367 ...(live.model === undefined ? {} : { model: live.model }),
368 ...(live.effort === undefined ? {} : { effort: live.effort }),
369 // Facts the footer reads (068): kept in memory between turns, written with the next flush.
370 ...(live.skills.length === 0 ? {} : { skills: [...new Set([...(before.skills ?? []), ...live.skills])].slice(-12) }),
371 ...(live.todo === undefined ? {} : { todo: live.todo }),
372 ...(live.cache === undefined ? {} : { cache: live.cache }),
373 ...(live.fast === undefined ? {} : { fast: live.fast }),
374 ...(live.dirs === undefined ? {} : { dirs: live.dirs }),
375 }
376 const next = change(counted)
377 if (value !== undefined && JSON.stringify(next) === JSON.stringify(value)) return
378 if ((await $.state.set(SESSION, next, { ifVersion: version })).isSet) {
379 live.toolCalls = 0
380 live.drifts = 0
381 live.driftsById = {}
382 live.agentsRun = 0
383 live.agentsById = {}
384 live.ticksMain = 0
385 live.ticksSub = 0
386 live.agentsQueued = 0
387 live.linesAdded = 0
388 live.linesRemoved = 0
389 return
390 }
391 }
392}
393
394/** Shows a bounded notification and keeps its full text in the Session tab (052 #44). */
395async function showToast($: EngineInterface, text: string, options?: { timeoutMs?: number; kind?: 'ok' | 'warn' | 'update' }): Promise<void> {
396 const formatted = formatToast(text, t(currentLang(), 'toast.details'), options?.kind ?? 'ok')
397 if (formatted.full !== undefined) await flushStats($, stats => ({ ...stats, toastDetails: formatted.full }))
398 $.ui.toast(formatted.text, options?.timeoutMs === undefined ? undefined : { timeoutMs: options.timeoutMs })
399}
400
401/** One `git status` at the end of a main turn (018 FR-003): no shell, 2 s at most. */
402async function readGit($: EngineInterface, root: string | undefined, branch: string | undefined, afterGitCommand = false): Promise<SessionStats['git'] | undefined> {
403 // A branch read from the repository files says there is a repository: no extra check.
404 if (root === undefined || (branch === undefined && !afterGitCommand)) return undefined
405 try {
406 const run = await $.process.run(GIT_STATUS, { cwd: root, timeoutMs: 2000 })
407 if (run.exitCode !== 0) return undefined
408 // The remote's web page, asked once per session (054 #79).
409 if (remoteWeb === undefined) {
410 const remote = await $.process.run(['git', 'remote', 'get-url', 'origin'], { cwd: root, timeoutMs: 2000 }).catch(() => undefined)
411 remoteWeb = remote?.exitCode === 0 ? (remoteWebUrl(remote.stdout) ?? null) : null
412 }
413 const state = parseGitStatus(run.stdout)
414 return remoteWeb === null ? state : { ...state, remote: remoteWeb }
415 } catch {
416 return undefined
417 }
418}
419
420// The remote's web page for this session; null once asked and there is none.
421let remoteWeb: string | null | undefined
422
423let prRunning = false
424
425const DEFER_BATCH = 100
426
427/** Reads the deferred features a batch at a time, one timer each, until none is left (040). */
428async function loadDeferred($: EngineInterface): Promise<void> {
429 try {
430 const held = (await $.state.get(SPECKIT)).value
431 const pending = held?.features.filter(f => f.warnings.includes('loading')).map(f => f.dir) ?? []
432 if (pending.length === 0) return
433 const batch = pending.slice(0, DEFER_BATCH)
434 const now = await $.clock.now()
435 const fs = fsOf($)
436 const next = await guarded($, async previous => (previous === undefined ? undefined : reconcileDeferred(fs, previous, batch, now)))
437 if (next !== undefined) await showStatus($, next.state)
438 await captureFeatureDurations($, next, now)
439 if (pending.length > batch.length) $.clock.after(0, () => void loadDeferred($))
440 } catch (error) {
441 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
442 }
443}
444
445/** Keep project-wide specify-to-done timings in the store, not the bounded session state (054 #32). */
446async function captureFeatureDurations($: EngineInterface, held: Held | undefined, now: number): Promise<void> {
447 if (held === undefined) return
448 const root = held.state.root
449 if (root === undefined) return
450 try {
451 const key = `${FEATURE_DURATIONS}:${root}`
452 const stored = await $.store.get(key)
453 const records = stored === undefined ? {} : readFeatureDurations(stored)
454 if (records === undefined) {
455 featureDurationsByRoot.delete(root)
456 $.ui.log(`astrolabe: invalid saved feature durations for ${root}`, { to: 'debug' })
457 return
458 }
459 const updated = updateFeatureDurations(
460 records,
461 held.state.features.filter(feature => !feature.warnings.includes('loading')),
462 now,
463 )
464 if (updated.changed) await $.store.set(key, updated.records)
465 const finished = Object.values(updated.records)
466 .filter((record): record is FeatureDuration & { completedAt: number; ms: number } => record.completedAt !== undefined && record.ms !== undefined)
467 .sort((a, b) => b.completedAt - a.completedAt)
468 featureDurationsByRoot.set(root, finished)
469 } catch (error) {
470 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
471 }
472}
473
474// skillModels (030): off, or auto to send a skill's requests with the model and effort it does best with.
475let skillModels: unknown = 'off'
476// The skill the main thread last started this turn, cleared when the turn ends (030).
477let skillRunning: string | undefined
478// What the person changed in the Setup table: the model family and effort of a skill (078 FR-079).
479let skillOverrides: SkillOverrides = {}
480
481/** Gets the currently running skill (030). */
482export function getSkillRunning(): string | undefined {
483 return skillRunning
484}
485
486const PULLS_TTL_MS = 120_000
487let pullsRunning = false
488
489/** Reads the open pull requests for the PRs tab (032), at most every two minutes unless forced. */
490async function refreshPulls($: EngineInterface, force = false): Promise<void> {
491 if (pullsRunning) return
492 const root = (await $.state.get(SPECKIT)).value?.root ?? (await $.session.cwd())
493 const at = await $.clock.now()
494 const was = (await $.state.get(SESSION)).value?.pulls
495 if (!force && was !== undefined && at - was.at < PULLS_TTL_MS) return
496 pullsRunning = true
497 try {
498 const run = await $.process.run(['gh', 'pr', 'list', '--state', 'open', '--limit', '20', '--json', PR_LIST_FIELDS], { cwd: root, timeoutMs: 8000 }).catch(() => undefined)
499 // A gh that fails or hangs says so instead of leaving the tab on "Reading…" (054 #14).
500 if (run === undefined || run.exitCode !== 0) {
501 const error = run === undefined ? 'gh did not answer in 8 s' : firstLine(run.stderr || run.stdout) || `gh exited ${run.exitCode}`
502 await flushStats($, s => ({ ...s, pulls: { at, rows: s.pulls?.rows ?? [], error } }))
503 return
504 }
505 const rows = parsePullList(run.stdout)
506 // The release gate (054 #60): plugin.json's version against the tags, where there is a plugin.json.
507 const manifest = await $.fs.read(`${root}/.claude-plugin/plugin.json`).catch(() => undefined)
508 const version = typeof manifest === 'string' ? /"version"\s*:\s*"(\d+\.\d+\.\d+)"/.exec(manifest)?.[1] : undefined
509 let release: SessionStats['release']
510 if (version !== undefined) {
511 const tags = await $.process.run(['git', 'tag', '--list', 'v*', '--sort=-v:refname'], { cwd: root, timeoutMs: 3000 }).catch(() => undefined)
512 const names = tags?.exitCode === 0 ? tags.stdout.split('\n').map(x => x.trim()).filter(x => x !== '') : []
513 // How many commits the latest tag does not have (078 FR-068).
514 const since = names[0] === undefined ? undefined : await $.process.run(['git', 'rev-list', '--count', `${names[0]}..HEAD`], { cwd: root, timeoutMs: 3000 }).catch(() => undefined)
515 const unreleased = since?.exitCode === 0 ? Number(since.stdout.trim()) : undefined
516 release = { version, tagged: names.includes(`v${version}`), ...(names[0] === undefined ? {} : { latest: names[0] }), ...(unreleased === undefined || !Number.isFinite(unreleased) ? {} : { unreleased }) }
517 }
518 await flushStats($, s => ({ ...s, pulls: { at, rows }, ...(release === undefined ? {} : { release }) }))
519 } catch (error) {
520 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
521 } finally {
522 pullsRunning = false
523 }
524}
525
526/** Runs an action on a pull request (032) after its second press, then reads the list again. */
527async function runPullAction($: EngineInterface, action: 'approve' | 'update' | 'merge', n: number, head?: string): Promise<void> {
528 try {
529 const lang = currentLang()
530 // A merge waits for green checks (054 #58): pending or failing checks refuse it here.
531 const checks = (await $.state.get(SESSION)).value?.pulls?.rows.find(r => r.number === n)?.checks
532 if (action === 'merge' && (checks === 'pending' || checks === 'fail')) {
533 await showToast($, t(lang, checks === 'pending' ? 'prs.mergePending' : 'prs.mergeFailing', { n }), { kind: 'warn' })
534 return
535 }
536 const root = (await $.state.get(SPECKIT)).value?.root ?? (await $.session.cwd())
537 const run = await $.process.run(pullAction(action, n, head), { cwd: root, timeoutMs: 30_000 })
538 await showToast($, run.exitCode === 0 ? t(lang, `prs.done.${action}`, { n }) : t(lang, 'prs.failed', { n, error: (run.stderr || run.stdout).trim().split('\n')[0] ?? '', fix: pullAction(action, n).join(' ') }), run.exitCode === 0 ? undefined : { kind: 'warn' })
539 await refreshPulls($, true)
540 } catch (error) {
541 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
542 }
543}
544
545/** The PRs tab (032), led by gstack's /ship for the branch when gstack is installed (054 #96). */
546function pullsBody(
547 $: Parameters<Hook<'ui.render'>>[0],
548 e: Parameters<Hook<'ui.render'>>[1],
549 pane: PaneState,
550 stats: SessionStats | undefined,
551 speckit?: SpeckitState,
552): Array<{ node: RenderNode; rows: number; select?: string }> {
553 const elements = $.ui.resolve(e)
554 const branch = stats?.git?.branch
555 const ship =
556 stats?.gstack === true && branch !== undefined && branch !== 'main' && branch !== 'master' && 'Button' in elements
557 ? [{ rows: 1, node: <elements.Button key="gstack-ship" label={t(currentLang(), 'prs.ship', { branch })} plain onPress={() => void $.clock.after(0, () => void runSkill($, 'ship', `branch ${branch}`))} /> }]
558 : []
559 const release = stats?.release
560 const gate =
561 release === undefined
562 ? []
563 : [
564 {
565 rows: 1,
566 node: (
567 <elements.Text key="astrolabe-release-gate" color={release.tagged ? tokens0[STATUS_ROLE.warning] : tokens0[STATUS_ROLE.success]} wrap="truncate-end">
568 {`${t(currentLang(), release.tagged ? 'prs.release.tagged' : 'prs.release.ready', { version: release.version, latest: release.latest ?? '—' })}${release.unreleased === undefined || release.latest === undefined ? '' : ` · ${t(currentLang(), 'prs.release.since', { n: release.unreleased, tag: release.latest })}`}`}
569 </elements.Text>
570 ),
571 },
572 ]
573 return [...ship, ...gate, ...pullsRows($, e, pane, stats, speckit)]
574}
575
576/** The PRs tab's rows (032): a link per pull request, its state, and the buttons GitHub allows. */
577function pullsRows(
578 $: Parameters<Hook<'ui.render'>>[0],
579 e: Parameters<Hook<'ui.render'>>[1],
580 pane: PaneState,
581 stats: SessionStats | undefined,
582 speckit?: SpeckitState,
583): Array<{ node: RenderNode; rows: number; select?: string }> {
584 const elements = $.ui.resolve(e)
585 const { Box, Text, Button } = elements
586 const Link = 'Link' in elements ? elements.Link : undefined
587 const lang = currentLang()
588 const rows = stats?.pulls?.rows
589 if (rows === undefined) return [{ rows: 1, node: <Text color={tokens0.muted}>{t(lang, 'prs.loading')}</Text> }]
590 if (stats?.pulls?.error !== undefined && rows.length === 0) return [{ rows: 1, node: <Text color={tokens0[STATUS_ROLE.error]}>{t(lang, 'prs.listFailed', { error: stats.pulls.error })}</Text> }]
591 if (rows.length === 0) return [{ rows: 1, node: <Text color={tokens0.muted}>{t(lang, 'prs.none')}</Text> }]
592 const press = (key: string, run: () => void) => async () => {
593 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
594 if (held.confirm === key) {
595 const { confirm: _gone, ...rest } = held
596 await $.state.set(PANE_STATE, rest)
597 $.clock.after(0, run)
598 } else {
599 await $.state.set(PANE_STATE, { ...held, confirm: key })
600 // The second press must come within 10 s; after that the row asks again from scratch (052 #41).
601 $.clock.after(10_000, () => void (async () => {
602 const now = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
603 if (now.confirm !== key) return
604 const { confirm: _late, ...rest } = now
605 await $.state.set(PANE_STATE, rest)
606 })().catch(error => $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })))
607 }
608 }
609 // Checks as cells: ✓ passed, ✖ failed, ◷ pending (066 #28).
610 const mark = (c: string) => (c === 'pass' ? '✓' : c === 'fail' ? '✖' : c === 'pending' ? STATE_GLYPHS.elapsed : '·')
611 const colour = (c: string) => (c === 'pass' ? tokens0[STATUS_ROLE.success] : c === 'fail' ? tokens0[STATUS_ROLE.error] : c === 'pending' ? tokens0[STATUS_ROLE.warning] : tokens0.muted)
612 const columns = (e.props as { bodyColumns?: number }).bodyColumns ?? 80
613 // The filter of the tab: `is:failing`, `is:draft`, `is:approved`, `is:behind`, `is:mine` (the branch you are on), words (078 FR-070).
614 const tokens = (pane.filter ?? '').trim().toLowerCase().split(/\s+/).filter(x => x !== '')
615 const words = tokens.filter(x => !x.startsWith('is:')).join(' ')
616 const is = new Set(tokens.filter(x => x.startsWith('is:')).map(x => x.slice(3)))
617 const mine = stats?.git?.branch
618 const wanted = rows.filter(pr =>
619 (words === '' || `#${pr.number} ${pr.title} ${pr.branch}`.toLowerCase().includes(words)) &&
620 (!is.has('failing') || pr.checks === 'fail') &&
621 (!is.has('draft') || pr.isDraft) &&
622 (!is.has('approved') || pr.review === 'approved') &&
623 (!is.has('behind') || pr.merge === 'BEHIND') &&
624 (!is.has('mine') || (mine !== undefined && pr.branch === mine)),
625 )
626 // The ones that need the person lead: failing checks, then requested changes, then the rest (078 FR-066).
627 const need = (pr: (typeof rows)[number]): number => (pr.checks === 'fail' ? 0 : pr.review === 'changes' ? 1 : pr.merge === 'BEHIND' ? 2 : pr.checks === 'pending' ? 3 : 4)
628 const ordered = [...wanted].sort((a, b) => need(a) - need(b) || b.number - a.number)
629 // The table's columns: the title takes what the checks, the review and the age leave (078 FR-061).
630 const reviewWidth = Math.max(...Object.values({ a: 'approved', b: 'changes requested', c: 'review required', d: 'no review' }).map(w => w.length))
631 const titleRoom = Math.max(12, columns - 4 - 8 - reviewWidth - 4 - 6)
632 const spec = (pr: (typeof rows)[number]) => specOfBranch(pr.branch, speckit?.features ?? [])
633 const header = { rows: 1, node: <Text key="prs-header" color={tokens0.faint} wrap="truncate-end">{t(lang, 'prs.header')}</Text> }
634 const noPr =
635 mine === undefined || mine === 'main' || mine === 'master' || rows.some(pr => pr.branch === mine) || is.size > 0 || words !== ''
636 ? []
637 : [
638 {
639 rows: 1,
640 node: (
641 <Box key="prs-no-pr" flexDirection="row">
642 <Text color={tokens0.muted}>{`${t(lang, 'prs.noPr', { branch: mine })} `}</Text>
643 <Button key="prs-open-pr" label={t(lang, 'prs.openPr')} plain onPress={() => void $.prompt.suggest({ text: `Open a pull request for branch ${mine} with: gh pr create --fill` }).catch(() => undefined)} />
644 </Box>
645 ),
646 },
647 ]
648 const standing = pane.selectedPr !== undefined && ordered.some(pr => `pr-${pr.number}` === pane.selectedPr) ? pane.selectedPr : ordered[0] === undefined ? undefined : `pr-${ordered[0].number}`
649 if (ordered.length === 0) return [header, ...noPr, { rows: 1, node: <Text color={tokens0.muted}>{t(lang, 'pane.noMatch', { filter: (pane.filter ?? '').trim() })}</Text> }]
650 return [header, ...noPr, ...ordered.flatMap(pr => {
651 const title = `#${pr.number} ${pr.title}`
652 const shownTitle = [...title].length > titleRoom ? `${[...title].slice(0, titleRoom - 1).join('')}…` : title
653 const cells = pr.runs === undefined || pr.runs.length === 0 ? mark(pr.checks) : pr.runs.slice(0, 6).map(run => mark(run.result)).join('')
654 // Who opened it and how long ago, as of the last read (052 #40).
655 const age = pr.createdAt === undefined || stats?.pulls === undefined ? '' : ageOf(pr.createdAt, stats.pulls.at)
656 const opened = [pr.author === undefined ? '' : `@${pr.author}`, age].filter(x => x !== '').join(' ')
657 const facts = [opened, pr.branch].filter(x => x !== '').join(' ')
658 // Draft and labels are small chips, dim for a draft (078 FR-065).
659 const chips = [pr.isDraft ? `[${t(lang, 'prs.draft')}]` : '', ...pr.labels.map(l => `[${l}]`)].filter(x => x !== '').join(' ')
660 const buttons: RenderNode[] = []
661 const add = (action: 'approve' | 'update' | 'merge') => {
662 const key = `pr-${action}-${pr.number}`
663 buttons.push(<Button key={key} label={pane.confirm === key ? t(lang, 'prs.confirmAction', { action: t(lang, `prs.${action}`).toLowerCase(), n: pr.number }) : t(lang, `prs.${action}`)} onPress={press(key, () => void runPullAction($, action, pr.number, pr.head))} />, <Text> </Text>)
664 }
665 if (pr.review !== 'approved' && !pr.isDraft) add('approve')
666 if (pr.merge === 'BEHIND') add('update')
667 if (pr.merge === 'CLEAN' && !pr.isDraft) add('merge')
668 const dir = spec(pr)
669 const feature = speckit?.features.find(f => f.dir === dir)
670 return [
671 {
672 rows: 1,
673 select: `pr-${pr.number}`,
674 node: (
675 <Box flexDirection="row">
676 <Text color={tokens0.accent} bold>{standing === `pr-${pr.number}` ? '❯ ' : ' '}</Text>
677 {Link !== undefined && pr.url !== '' ? <Link href={pr.url} label={shownTitle} /> : <Text color={colour(pr.checks)}>{shownTitle}</Text>}
678 <Text>{' '.repeat(Math.max(2, titleRoom - [...shownTitle].length + 2))}</Text>
679 <Text color={colour(pr.checks)}>{cells.padEnd(8)}</Text>
680 <Text color={pr.isDraft ? tokens0.faint : tokens0.text} wrap="truncate-end">{`${t(lang, `prs.review.${pr.review}`).padEnd(reviewWidth)} ${age}`}</Text>
681 </Box>
682 ),
683 },
684 {
685 rows: 1,
686 node: (
687 <Box flexDirection="row">
688 <Text color={pr.isDraft ? tokens0.faint : tokens0.muted}>{` ${chips === '' ? '' : `${chips} `}${facts} `}</Text>
689 {feature === undefined ? null : <Button key={`pr-spec-${pr.number}`} label={`→ ${feature.id}`} plain onPress={async () => {
690 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
691 const { help: _h, tasksOnly: _t, selectedTask: _s, ...rest } = held
692 await $.state.set(PANE_STATE, { ...rest, tab: 'specs', selectedFeature: feature.id })
693 }} />}
694 {feature === undefined ? null : <Text> </Text>}
695 {buttons}
696 </Box>
697 ),
698 },
699 // Each check, linked to its run (054 #80), at most 6.
700 ...(Link === undefined || pr.runs === undefined
701 ? []
702 : [
703 {
704 rows: 1,
705 node: (
706 <Box flexDirection="row">
707 <Text color={tokens0.muted}>{' '}</Text>
708 {pr.runs.slice(0, 6).map(run => (
709 <Link key={`pr-run-${pr.number}-${run.name}`} href={run.url} label={`${mark(run.result)} ${run.name} `} />
710 ))}
711 </Box>
712 ),
713 },
714 ]),
715 ]
716 })]
717}
718
719// Astrolabe's own /config rows (028), read at session start and after a save.
720let configRows: ConfigRow[] = []
721
722/** The Config tab's rows (028): a heading per group that folds, an option per row, its control and card. */
723function configBody(
724 $: Parameters<Hook<'ui.render'>>[0],
725 e: Parameters<Hook<'ui.render'>>[1],
726 pane: PaneState,
727 speckit?: SpeckitState,
728): Array<{ node: RenderNode; rows: number; /** The key the arrow keys stand on when the unit is an option (079). */ select?: string; /** Drawn over the rows below the option while it is hovered, out of the flow (079). */ card?: { scope: string; node: RenderNode } }> {
729 const elements = $.ui.resolve(e)
730 const { Box, Text, Button } = elements
731 const Select = 'Select' in elements ? elements.Select : undefined
732 const Input = 'Input' in elements ? elements.Input : undefined
733 const Link = 'Link' in elements && e.surface === 'terminal' ? elements.Link : undefined
734 const lang = currentLang()
735 const draft = pane.draft ?? {}
736 const setDraft = async (key: string, value: string | number | boolean) => {
737 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
738 await $.state.set(PANE_STATE, { ...held, draft: { ...(held.draft ?? {}), [key]: value } })
739 }
740 const rows: Array<{ node: RenderNode; rows: number; select?: string; card?: { scope: string; node: RenderNode } }> = []
741 if (configRows.length === 0) return [{ rows: 1, node: <Text color={tokens0.muted}>{t(lang, 'config.none')}</Text> }]
742 // The values as they would be with the draft, for the conflicts between options (078 FR-082).
743 const values: Record<string, unknown> = {}
744 for (const row of configRows) values[row.key.replace(/^astrolabe\./, '')] = row.key in draft ? draft[row.key] : row.value
745 const conflicts = optionConflicts(values, lang)
746 // `/` finds an option by its name and by what it says (board 4, 075 FR-017, 078 FR-074).
747 const needle = (pane.filter ?? '').trim().toLowerCase()
748 const wanted = (row: ConfigRow) => needle === '' || `${row.key} ${row.label} ${row.description ?? ''}`.toLowerCase().includes(needle)
749 const groups = Object.keys(OPTION_GROUPS) as OptionGroup[]
750 const ordered = groups.flatMap(group => configRows.filter(row => optionGroup(row.key) === group && wanted(row)).map((row, i) => ({ row, group, heading: i === 0 ? group : undefined })))
751 if (needle !== '' && ordered.length === 0) return [{ rows: 1, node: <Text color={tokens0.muted}>{t(lang, 'pane.noMatch', { filter: needle })}</Text> }]
752 const changedGroups = new Set(configRows.filter(r => r.key in draft && draft[r.key] !== r.value).map(r => optionGroup(r.key)))
753 // Only the group with a change is open, and the first one; a search opens every group it finds (078 FR-071).
754 const isOpen = (group: OptionGroup): boolean => needle !== '' || changedGroups.has(group) || (pane.groupsOpen === undefined ? group === groups[0] : pane.groupsOpen.includes(group))
755 const toggle = (group: OptionGroup) => async () => {
756 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
757 const openNow = new Set(groups.filter(g => (held.groupsOpen === undefined ? g === groups[0] : held.groupsOpen.includes(g))))
758 if (openNow.has(group)) openNow.delete(group)
759 else openNow.add(group)
760 await $.state.set(PANE_STATE, { ...held, groupsOpen: [...openNow] })
761 }
762 // The look presets: one key each, set as a draft that Save applies (078 FR-075).
763 if (needle === '') {
764 const matching = presetMatching(values)
765 rows.push({
766 rows: 1,
767 node: (
768 <Box key="setup-presets" flexDirection="row">
769 <Text color={tokens0.muted}>{`${t(lang, 'setup.presets')} `}</Text>
770 {(['minimal', 'balanced', 'full'] as const).map(name => (
771 <Button
772 key={`setup-preset-${name}`}
773 label={t(lang, `setup.preset.${name}` as TextKey)}
774 {...(matching === name ? { variant: 'primary' as const } : {})}
775 onPress={async () => {
776 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
777 const next: Record<string, string | number | boolean> = { ...(held.draft ?? {}) }
778 for (const [field, value] of Object.entries(LOOK_PRESETS[name])) {
779 const row = configRows.find(r => r.key === `astrolabe.${field}`)
780 if (row !== undefined && !row.isLocked) next[row.key] = value
781 }
782 await $.state.set(PANE_STATE, { ...held, draft: next })
783 }}
784 />
785 ))}
786 </Box>
787 ),
788 })
789 }
790 // The band as the drafted density would draw it, under the presets (078 FR-076).
791 if (needle === '' && speckit !== undefined) {
792 const density = values['bandDensity'] === 'compact' || values['bandDensity'] === 'minimal' ? values['bandDensity'] : 'full'
793 const line = bandText(bandSegments(speckit, Math.min(100, (e.props as { bodyColumns?: number }).bodyColumns ?? 80), { density }))
794 if (line.trim() !== '') rows.push({ rows: 1, node: <Text key="setup-preview" color={tokens0.muted} wrap="truncate-end">{`${t(lang, 'setup.preview')} ${line}`}</Text> })
795 }
796 for (const { row, group, heading } of ordered) {
797 if (heading !== undefined) {
798 const n = configRows.filter(r => optionGroup(r.key) === group).length
799 rows.push({
800 rows: 1,
801 node: <Button key={`config-group-${heading}`} label={`${isOpen(group) ? '▾' : '▸'} ${t(lang, `config.group.${heading}` as TextKey)} ${n}`} plain onPress={toggle(group)} />,
802 })
803 }
804 if (!isOpen(group)) continue
805 const shown = row.key in draft ? draft[row.key] : row.value
806 const changed = row.key in draft && draft[row.key] !== row.value
807 // ● a change not saved yet; • a saved value that differs from the option's default (052 #39).
808 // The option the arrow keys stand on has `❯` in a gutter every row keeps (079).
809 const stood = (pane.selectedOption ?? ordered.find(o => isOpen(o.group))?.row.key) === row.key
810 const label = `${stood ? '❯ ' : ' '}${configMark(changed, row.value, defaultsSeen, row.key)}${row.label}`.padEnd(32)
811 const key = `config-${row.key}`
812 let control: RenderNode
813 if (row.isLocked) control = <Text color={tokens0.muted}>{`${String(shown)} (${t(lang, 'config.locked')})`}</Text>
814 else if (row.kind === 'boolean') control = <Button key={key} label={shown === true ? '[x] on' : '[ ] off'} onPress={() => setDraft(row.key, shown !== true)} />
815 else if (row.kind === 'choice' && row.options !== undefined && Select !== undefined)
816 control = <Select key={key} options={row.options.map(value => ({ value }))} value={String(shown)} onSelect={(value: string) => setDraft(row.key, value)} />
817 else if (row.kind === 'choice' && row.options !== undefined) {
818 const options = row.options
819 const next = options[(options.indexOf(String(shown)) + 1) % options.length] ?? String(shown)
820 // `‹ value ›` with the other choices after it (board 4); a press moves to the next one.
821 control = (
822 <Box key={key} flexDirection="row">
823 <Button label={`‹ ${String(shown)} ›`} onPress={() => setDraft(row.key, next)} />
824 <Text color={tokens0.faint}>{` ${options.filter(o => o !== String(shown)).join(' · ')}`}</Text>
825 </Box>
826 )
827 } else if (Input !== undefined) {
828 const save = (value: string) => setDraft(row.key, row.kind === 'number' ? Number(value) : value)
829 control = <Input key={key} value={String(shown)} onInput={save} onSubmit={save} />
830 } else control = <Text>{String(shown)}</Text>
831 const defaultValue = defaultsSeen[row.key]
832 const field = row.key.replace(/^astrolabe\./, '')
833 const named = conflicts.filter(c => c.field === field)
834 // One option back to its default, as a draft (078 FR-077).
835 const offDefault = !row.isLocked && defaultValue !== undefined && shown !== defaultValue
836 rows.push({
837 // The option and the conflicts named under it; the card is not part of the height (079).
838 rows: 1 + named.length,
839 select: row.key,
840 // The card is an absolute box drawn after every row, so it paints over them and moves none: in
841 // the flow it pushed the settings below down on every hover (079).
842 card: {
843 scope: `config-row-${row.key}`,
844 node: (
845 <Box flexDirection="column" paddingX={1} backgroundColor={tokens0.barEmpty}>
846 <Text color={tokens0.accent}>{`${t(lang, 'config.default')}: ${defaultValue === undefined ? t(lang, 'word.unknown') : String(defaultValue)}`}</Text>
847 <Text color={tokens0.text} wrap="wrap">{row.description ?? t(lang, 'config.noDescription')}</Text>
848 {Link === undefined ? null : <Link href={OPTIONS_README} label={`${t(lang, 'setup.readme')} ↗`} />}
849 </Box>
850 ),
851 },
852 node: (
853 <Box key={`config-row-${row.key}`} flexDirection="column" hover={{ scope: `config-row-${row.key}` }}>
854 <Box flexDirection="row">
855 <Text color={stood ? tokens0.accent : changed ? tokens0.current : tokens0.text} bold={stood}>{label}</Text>
856 {control}
857 {offDefault ? <Button key={`config-reset-${row.key}`} label={t(lang, 'setup.resetOne')} plain onPress={() => setDraft(row.key, defaultValue)} /> : null}
858 {row.key === 'astrolabe.icons' && String(shown) === 'auto' ? <Text color={tokens0.faint}>{` (${t(lang, iconsFor('auto', e.surface) === 'nerd' ? 'config.iconsNerd' : iconsFor('auto', e.surface) === 'ascii' ? 'config.iconsAscii' : 'config.iconsEmoji')})`}</Text> : null}
859 </Box>
860 {named.map((c, i) => (
861 <Text key={`config-conflict-${row.key}-${i}`} color={tokens0.current} wrap="truncate-end">{` ▲ ${c.text}`}</Text>
862 ))}
863 </Box>
864 ),
865 })
866 }
867 return rows
868}
869
870/** Save, Reset, Cancel and the copy button: one bar that stays in view above the options (078 FR-073). */
871function configBar(
872 $: Parameters<Hook<'ui.render'>>[0],
873 e: Parameters<Hook<'ui.render'>>[1],
874 pane: PaneState,
875): RenderNode[] {
876 const { Box, Text, Button } = $.ui.resolve(e)
877 const lang = currentLang()
878 const draft = pane.draft ?? {}
879 if (configRows.length === 0) return []
880 const pending = Object.keys(draft).filter(k => draft[k] !== configRows.find(r => r.key === k)?.value)
881 return [
882 <Box key="config-bar" flexDirection="row">
883 <Button key="config-save" label={pending.length === 0 ? t(lang, 'config.saved') : t(lang, 'config.save', { n: pending.length })} variant="primary" onPress={() => saveConfig($)} />
884 <Text> </Text>
885 {/* Every option back to its default, as a draft Save applies (054 #63). */}
886 <Button key="config-reset" label={t(lang, 'config.reset')} onPress={() => draftDefaults($)} />
887 <Text> </Text>
888 <Button key="config-cancel" label={t(lang, 'config.cancel')} onPress={async () => {
889 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
890 const { draft: _gone, ...rest } = held
891 await $.state.set(PANE_STATE, rest)
892 }} />
893 {pending.length === 0 ? null : <Text> </Text>}
894 {pending.length === 0 ? null : <Button key="config-copy" label={t(lang, 'setup.copy')} plain onPress={() => void copyNext($, changedSettingsJson(Object.fromEntries(pending.map(k => [k, draft[k]!]))), e.surface)} />}
895 </Box>,
896 ]
897}
898
899/**
900 * The model table of Setup (030, 078 FR-079): each skill with the model family and effort auto mode
901 * sends it with, as two buttons that cycle; `▸` marks the skill running now. A choice is kept in the
902 * mod's store and laid over the built-in table.
903 */
904function modelSkillTabBody(
905 $: Parameters<Hook<'ui.render'>>[0],
906 e: Parameters<Hook<'ui.render'>>[1],
907 _pane: PaneState,
908): Array<{ node: RenderNode; rows: number }> {
909 const { Box, Text, Button } = $.ui.resolve(e)
910 const lang = currentLang()
911 const auto = skillModels === 'auto'
912 const active = getSkillRunning()
913 const rows: Array<{ node: RenderNode; rows: number }> = []
914 const change = (name: string, patch: { model?: (typeof MODEL_FAMILIES)[number]; effort?: (typeof EFFORTS)[number] }) => async () => {
915 skillOverrides = { ...skillOverrides, [name]: { ...(skillOverrides[name] ?? {}), ...patch } }
916 await $.store.set('skillOverrides', skillOverrides).catch(() => undefined)
917 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
918 await $.state.set(PANE_STATE, { ...held })
919 }
920 const names = Object.keys(SKILL_MODELS)
921 for (const category of ['speckit', 'gstack'] as const) {
922 rows.push({ rows: 1, node: <Text key={`models-${category}`} color={tokens0.accent} bold>{t(lang, `models.category.${category}`)}</Text> })
923 for (const name of names.filter(n => (category === 'speckit') === n.startsWith('speckit-'))) {
924 const entry = skillModelFor(name, skillOverrides)!
925 const running = auto && active !== undefined && skillNameOf(active) === name
926 const family = familyOf(entry.model)
927 const nextFamily = MODEL_FAMILIES[(MODEL_FAMILIES.indexOf(family) + 1) % MODEL_FAMILIES.length]!
928 const nextEffort = EFFORTS[(EFFORTS.indexOf(entry.effort) + 1) % EFFORTS.length]!
929 rows.push({
930 rows: 1,
931 node: (
932 <Box key={`skill-${name}`} flexDirection="row">
933 <Text color={running ? tokens0.current : tokens0.text}>{`${running ? '▸' : ' '} ${name.padEnd(22)}`}</Text>
934 <Button key={`model-${name}`} label={`‹ ${family} ›`} plain onPress={change(name, { model: nextFamily })} />
935 <Text> </Text>
936 <Button key={`effort-${name}`} label={`‹ ${entry.effort} ›`} plain onPress={change(name, { effort: nextEffort })} />
937 <Text color={tokens0.faint}>{` ${entry.why}${running ? ` ← ${t(lang, 'models.running')}` : ''}`}</Text>
938 </Box>
939 ),
940 })
941 }
942 }
943 rows.push({ rows: 1, node: <Text color={tokens0.muted}>{auto ? t(lang, 'models.autoModeActive', { active: active ?? t(lang, 'models.idle') }) : t(lang, 'models.autoModeOff')}</Text> })
944 return rows
945}
946
947/** Applies the Config tab's changes through $.config.set (028); options reload the mod. */
948/** The options' defaults from our own plugin.json (054 #63). */
949async function defaults($: EngineInterface): Promise<Record<string, string | number | boolean>> {
950 const text = await fsOf($).read(`${$.plugin.root}/.claude-plugin/plugin.json`).catch(() => '')
951 return optionDefaults(text)
952}
953
954/** Puts every option that differs from its default in the draft, for Save to apply (054 #63). */
955async function draftDefaults($: EngineInterface): Promise<void> {
956 const wanted = await defaults($)
957 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
958 const draft = { ...(held.draft ?? {}) }
959 for (const row of configRows) if (!row.isLocked && row.key in wanted && wanted[row.key] !== row.value) draft[row.key] = wanted[row.key]!
960 await $.state.set(PANE_STATE, { ...held, draft })
961}
962
963/** `/astrolabe config reset`: every option back to its default now (054 #63). */
964async function resetConfig($: EngineInterface): Promise<string> {
965 const wanted = await defaults($)
966 const rows = (await $.config.list().catch(() => [] as ConfigRow[])).filter(row => row.key.startsWith('astrolabe.'))
967 const changed: string[] = []
968 for (const row of rows) {
969 if (row.isLocked || !(row.key in wanted) || wanted[row.key] === row.value) continue
970 const result = await $.config.set({ key: row.key, value: wanted[row.key]! }).catch(() => ({ deny: 'refused' }))
971 if (!('deny' in result && result.deny !== undefined)) changed.push(row.key.replace(/^astrolabe\./, ''))
972 }
973 configRows = (await $.config.list().catch(() => [] as ConfigRow[])).filter(row => row.key.startsWith('astrolabe.'))
974 return t(currentLang(), changed.length === 0 ? 'config.resetNone' : 'config.resetDone', { list: changed.join(', ') })
975}
976
977async function saveConfig($: EngineInterface): Promise<void> {
978 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
979 const draft = held.draft ?? {}
980 const refused: string[] = []
981 let saved = 0
982 for (const [key, value] of Object.entries(draft)) {
983 if (configRows.find(r => r.key === key)?.value === value) continue
984 const result = await $.config.set({ key, value }).catch((error: unknown) => ({ deny: error instanceof Error ? error.message : String(error) }))
985 if ('deny' in result && result.deny !== undefined) refused.push(`${key}: ${result.deny}`)
986 else saved += 1
987 }
988 const { draft: _gone, ...rest } = held
989 await $.state.set(PANE_STATE, rest)
990 configRows = (await $.config.list().catch(() => [] as ConfigRow[])).filter(row => row.key.startsWith('astrolabe.'))
991 const lang = currentLang()
992 await showToast($, refused.length === 0 ? t(lang, 'config.applied', { n: saved }) : t(lang, 'config.refused', { list: refused.join('; ') }), refused.length === 0 ? undefined : { kind: 'warn' })
993}
994
995// The options as loaded, for drawings that need more than one (039).
996let optionsSeen: Readonly<Record<string, unknown>> = {}
997
998// How many units each pane tab drew last (038), to clamp a scroll that arrives between draws.
999const unitsShown: Partial<Record<string, number>> = {}
1000/** What the pane body shows: the help overlay above the tab, or the tab (066 #21). */
1001const viewOf = (pane: Pick<PaneState, 'tab' | 'help'>): PaneView => (pane.help === true ? 'help' : pane.tab)
1002const featureDurationsByRoot = new Map<string, FeatureDuration[]>()
1003let specSelectionRows: Array<{ key: string; index: number }> = []
1004// The rows the arrow keys stand on in Setup and PRs, with the window drawn (079).
1005let listSelection: { tab: 'setup' | 'prs'; rows: Array<{ key: string; index: number }>; window: { start: number; end: number }; selected: string | undefined } | undefined
1006let selectedSpecRow: string | undefined
1007let specSelectionWindow = { start: 0, end: 0 }
1008let specLinksEnabled = false
1009// The roadmap read once per session and root (044 #40); a turn's work may redraw the Specs tab
1010// many times, and each redraw must not read the file again (054 #1).
1011const roadmapCache = new Map<string, string | undefined>()
1012
1013// Whether a finished feature gets a summary from a small model (026 #53), off by default.
1014let featureSummary = false
1015const SUMMARIES = 'summaries'
1016
1017/** Five lines on a finished feature, from `haiku`, kept in $.store and shown in the Session tab (026 #53). */
1018async function summarizeFeature($: EngineInterface, feature: { dir: string; id: string; name: string }): Promise<void> {
1019 try {
1020 const root = (await $.state.get(SPECKIT)).value?.root
1021 if (root === undefined) return
1022 const fs = fsOf($)
1023 const spec = await fs.read(`${root}/specs/${feature.dir}/spec.md`).catch(() => '')
1024 const tasks = await fs.read(`${root}/specs/${feature.dir}/tasks.md`).catch(() => '')
1025 const reply = await $.model.complete({
1026 model: 'haiku',
1027 maxTokens: 300,
1028 prompt: `Summarize this finished Spec Kit feature in at most five short lines, plain text, no headings: what it delivers and anything left open.\n\n${spec.slice(0, 8000)}\n\n${tasks.slice(0, 4000)}`,
1029 })
1030 if (!reply.isAnswered) return
1031 const stored = await $.store.get(SUMMARIES).catch(() => undefined)
1032 const all = typeof stored === 'object' && stored !== null && !Array.isArray(stored) ? (stored as Record<string, string>) : {}
1033 await $.store.set(SUMMARIES, { ...all, [feature.dir]: reply.text.trim().split('\n').slice(0, 5).join('\n') })
1034 await flushStats($, s => ({ ...s, lastSummary: { dir: feature.dir, text: reply.text.trim().split('\n').slice(0, 5).join('\n') } }))
1035 await showToast($, t(currentLang(), 'summary.ready', { feature: `${feature.id} ${feature.name}` }))
1036 } catch (error) {
1037 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
1038 }
1039}
1040
1041const GIT_WORKTREES = ['git', 'worktree', 'list', '--porcelain']
1042let worktreesRunning = false
1043
1044/** Reads what the repository's other worktrees work on (037): one git call, then their spec files. */
1045async function refreshWorktrees($: EngineInterface, root: string): Promise<void> {
1046 if (worktreesRunning) return
1047 worktreesRunning = true
1048 try {
1049 const run = await $.process.run(GIT_WORKTREES, { cwd: root, timeoutMs: 2000 }).catch(() => undefined)
1050 const list = run?.exitCode === 0 ? parseWorktrees(run.stdout) : []
1051 const main = list[0]
1052 const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '')
1053 const rel = main === undefined ? '' : norm(root).startsWith(norm(main.path)) ? norm(root).slice(norm(main.path).length) : ''
1054 const fs = fsOf($)
1055 const found: NonNullable<SessionStats['worktrees']> = []
1056 const previous = (await $.state.get(SESSION)).value?.worktrees ?? []
1057 // Branches already merged into the main checkout's branch (054 #50), one git call.
1058 const merged = main?.branch === undefined ? new Set<string>() : await $.process.run(['git', 'branch', '--merged', main.branch], { cwd: root, timeoutMs: 2000 }).then(r => (r.exitCode === 0 ? mergedBranches(r.stdout) : new Set<string>())).catch(() => new Set<string>())
1059 for (const wt of list.slice(1, 9)) {
1060 const old = previous.find(item => item.path !== undefined && norm(item.path) === norm(wt.path) && item.head === wt.head && item.branch === wt.branch)
1061 if (old !== undefined && wt.head !== undefined) {
1062 const status = await $.process.run(['git', 'status', '--porcelain'], { cwd: wt.path, timeoutMs: 2000 }).catch(() => undefined)
1063 const { changed: _changed, merged: _merged, ...kept } = old
1064 found.push({
1065 ...kept,
1066 name: worktreeName(wt.path),
1067 ...(wt.branch === undefined ? {} : { branch: wt.branch }),
1068 head: wt.head,
1069 path: wt.path,
1070 ...(status?.exitCode === 0 ? { changed: uncommittedCount(status.stdout) } : {}),
1071 ...(wt.branch !== undefined && merged.has(wt.branch) ? { merged: true } : {}),
1072 })
1073 continue
1074 }
1075 const specRoot = `${norm(wt.path)}${rel}`
1076 if (norm(specRoot) === norm(root)) continue
1077 const dirs = (await fs.list(`${specRoot}/specs`).catch(() => [])).filter(d => d.kind === 'dir').map(d => d.name)
1078 const dir = featureDirFor(wt.branch, dirs)
1079 if (dir === undefined) continue
1080 const feature = deriveFeature(await readFeature(fs, specRoot, dir))
1081 // Its uncommitted files (054 #51).
1082 const status = await $.process.run(['git', 'status', '--porcelain'], { cwd: wt.path, timeoutMs: 2000 }).catch(() => undefined)
1083 const changed = status?.exitCode === 0 ? uncommittedCount(status.stdout) : undefined
1084 found.push({
1085 name: worktreeName(wt.path),
1086 ...(wt.branch === undefined ? {} : { branch: wt.branch }),
1087 ...(wt.head === undefined ? {} : { head: wt.head }),
1088 dir,
1089 id: feature.id,
1090 featureName: feature.name,
1091 phase: feature.phase,
1092 done: feature.done,
1093 total: feature.total,
1094 path: wt.path,
1095 ...(changed === undefined ? {} : { changed }),
1096 ...(wt.branch !== undefined && merged.has(wt.branch) ? { merged: true as const } : {}),
1097 })
1098 }
1099 // A linked worktree names the main checkout's branch (068 #41).
1100 const origin = main?.branch !== undefined && norm(root) !== norm(main.path) ? main.branch : undefined
1101 await flushStats($, ({ worktrees: _old, ...s }) => {
1102 const kept = found.length === 0 ? s : { ...s, worktrees: found }
1103 if (kept.git === undefined) return kept
1104 const { origin: _origin, ...git } = kept.git
1105 return { ...kept, git: origin === undefined ? git : { ...git, origin } }
1106 })
1107 } catch (error) {
1108 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
1109 } finally {
1110 worktreesRunning = false
1111 }
1112}
1113
1114// Whether Claude is told of the Spec Kit work (026), and what it was last told.
1115let claudeContext = true
1116let lastTold: string | undefined
1117// Focus mode (054 #88), kept in the session's state across a reload.
1118let focusMode = false
1119
1120// Features whose implement step was refused once this session (054 #57): a repeat call goes through.
1121const implementWaived = new Set<string>()
1122
1123/** The constitution's Core Principles, by heading, as a reminder (026 #51). */
1124async function constitutionReminder($: EngineInterface): Promise<string | undefined> {
1125 const root = (await $.state.get(SPECKIT)).value?.root
1126 if (root === undefined) return undefined
1127 const text = await fsOf($).read(`${root}/.specify/memory/constitution.md`).catch(() => undefined)
1128 const principles = text === undefined ? [] : principlesOf(text)
1129 return principles.length === 0 ? undefined : `Astrolabe: check this step against the constitution (.specify/memory/constitution.md): ${principles.join('; ')}.`
1130}
1131
1132/** `/astrolabe ask` (026 #54): one question over the session's own transcript, answered in a toast. */
1133/** The Dashboard's numbers as a Markdown table (054 #99, 046 #59), or undefined before the first turn. */
1134async function kpisText($: EngineInterface): Promise<string | undefined> {
1135 const stats = (await $.state.get(SESSION)).value
1136 if (stats === undefined) return undefined
1137 const state = (await $.state.get(SPECKIT)).value
1138 const feature = state === undefined ? undefined : state.features.find(f => f.dir === state.active?.dir)
1139 const now = await $.clock.now()
1140 const binding = decisionOf((await $.state.get(USAGE)).value ?? DEFAULT_USAGE, now).highest
1141 const rows = [
1142 ...(feature === undefined || feature.total === 0 ? [] : [[t(currentLang(), 'kpis.tasks'), `${feature.done}/${feature.total}`] as [string, string]]),
1143 ...kpiRows(stats, binding, now, currentLang()),
1144 ...historyRows(stats, feature, state === undefined || state.root === undefined ? [] : featureDurationsByRoot.get(state.root) ?? [], currentLang()),
1145 ]
1146 return kpisMarkdown(t(currentLang(), 'kpis.title', { feature: feature === undefined ? '—' : `${feature.id} ${feature.name}` }), rows)
1147}
1148
1149/** Tokens as `182k` or `1.2M`. */
1150const tokensText = (n: number): string => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
1151
1152/** A press that needs a second one within ten seconds (052 #41), for actions that cost a turn (061). */
1153async function confirmPress($: EngineInterface, key: string, run: () => void): Promise<void> {
1154 const held = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
1155 if (held.confirm === key) {
1156 const { confirm: _gone, ...rest } = held
1157 await $.state.set(PANE_STATE, rest)
1158 run()
1159 return
1160 }
1161 await $.state.set(PANE_STATE, { ...held, confirm: key })
1162 $.clock.after(10_000, () => void (async () => {
1163 const now = (await $.state.get(PANE_STATE)).value ?? DEFAULT_PANE
1164 if (now.confirm !== key) return
1165 const { confirm: _late, ...rest } = now
1166 await $.state.set(PANE_STATE, rest)
1167 })().catch(error => $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })))
1168}
1169
1170/** Runs one of gstack's skills on a feature (051), from a timer: a command does not run inside a render. */
1171async function runSkill($: EngineInterface, skill: string, about: string): Promise<void> {
1172 await $.command.run({ command: skill, args: `Spec Kit feature ${about}` }).catch(async (error: unknown) => {
1173 await showToast($, t(currentLang(), 'gstack.failed', { skill }), { kind: 'warn' })
1174 $.ui.log(`astrolabe: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
1175 })
1176}
1177
1178/** Sets a spec's priority in this project's store and the session (051). */
1179async function setPriority($: EngineInterface, id: string, level: Priority): Promise<string> {
1180 const state = (await $.state.get(SPECKIT)).value
1181 const feature = state?.features.find(f => f.id === id)
1182 if (state?.root === undefined || feature === undefined) return t(currentLang(), 'priority.none', { id })
1183 const map = withPriority((await $.state.get(SESSION)).value?.priorities ?? {}, id, level)
1184 await $.store.set(`priority:${state.root}`, map).catch(() => undefined)
1185 await flushStats($, st => ({ ...st, priorities: map }))
1186 return t(currentLang(), 'priority.set', { feature: `${feature.id} ${feature.name}`, level })
1187}
1188
1189/** The deep review (051): spec, plan and tasks to a stronger model; the findings to the Session tab. */
1190async function deepReview($: EngineInterface, feature: { dir: string; id: string; name: string }): Promise<void> {
1191 try {
1192 const root = (await $.state.get(SPECKIT)).value?.root
1193 if (root === undefined) return
1194 const fs = fsOf($)
1195 const read = (file: string) => fs.read(`${root}/specs/${feature.dir}/${file}`).catch(() => '')
1196 const [spec, plan, tasks] = await Promise.all([read('spec.md'), read('plan.md'), read('tasks.md')])
1197 const constitution = await fs.read(`${root}/.specify/memory/constitution.md`).catch(() => '')
1198 const reply = await $.model.complete({ ...REVIEW_MODEL, prompt: reviewPrompt(feature, { spec, plan, tasks }, principlesOf(constitution)) })
1199 const text = reply.isAnswered ? reply.text.trim() : t(currentLang(), 'ask.failed', { reason: reply.reason })
1200 const at = await $.clock.now()hooks/modules/help.ts 141 lines1import { CHANGES, VERSION } from '../core/version'
2import { SKILL_MODELS } from '../core/skill-models'
3import { type PaneView } from '../core/types'
4import { CHIP_TABLE, footerText } from '../core/footer'
5import { iconSet } from '../core/icons'
6import { paneLabelWidth, t, type Lang, type TextKey } from '../core/i18n'
7
8/** The options whose values the Help tab lists. */
9export const OPTION_NAMES = ['preset', 'flavor', 'icons', 'language', 'bandDensity', 'checkUpdates', 'governUsage', 'observeUsage', 'askOnLimit', 'pullRequest', 'images', 'autoReload', 'footerIn', 'footerLines', 'footerSeparator', 'accessible', 'claudeContext', 'featureSummary', 'humanize', 'terse', 'skillModels'] as const
10
11// /astrolabe help (025, roadmap #39): the commands, the pane's tabs and their keys, in the
12// person's language (019).
13export const helpFooterPreview = (name: 'nerd' | 'emoji' | 'ascii', lang: Lang): string => {
14 const now = Date.UTC(2026, 0, 1)
15 return ` ${name.padEnd(6)} ${footerText({
16 speckit: () => '◆ 002 · implement 45%',
17 readings: [{ kind: 'five_hour', percentUsed: 42, resetsAt: new Date(now + 2 * 3_600_000).toISOString() }],
18 context: { percent: 43 },
19 model: 'claude-sonnet-4-5',
20 git: { branch: 'main', ahead: 1, behind: 0, changed: 2, conflicts: 0 },
21 startedAt: now - 60_000,
22 now,
23 icons: iconSet(name),
24 columns: 200,
25 lang,
26 })}`
27}
28
29export const buildHelp = (lang: Lang, optionsSeen: Readonly<Record<string, unknown>>, health: readonly string[] = []): string => {
30 const labelWidth = paneLabelWidth(lang)
31 return [
32 t(lang, 'help.title'),
33 // What this version changed (048 #80).
34 t(lang, 'help.changes', { version: VERSION, changes: CHANGES }),
35 t(lang, 'help.block.commands'),
36 ` /astrolabe ${t(lang, 'help.open')}`,
37 ` /astrolabe help ${t(lang, 'help.help')}`,
38 ` /astrolabe next ${t(lang, 'help.next')}`,
39 ` /astrolabe status ${t(lang, 'help.status')}`,
40 ` /astrolabe ask <question> ${t(lang, 'help.ask')}`,
41 ` /astrolabe root <folder> ${t(lang, 'help.root')}`,
42 ` /astrolabe allow <90-99> <30m-12h> ${t(lang, 'help.allow')}`,
43 ` /astrolabe revoke ${t(lang, 'help.revoke')}`,
44 ` /astrolabe run <id> ${t(lang, 'help.run')}`,
45 ` /astrolabe footer <owner> ${t(lang, 'help.footerOwner')}`,
46 ` /astrolabe doctor ${t(lang, 'help.doctor')}`,
47 ` /astrolabe priority <id> <high|normal|low> ${t(lang, 'help.priority')}`,
48 ` /astrolabe review [id] ${t(lang, 'help.review')}`,
49 ` /astrolabe advisor [id] ${t(lang, 'help.advisor')}`,
50 ` /astrolabe config reset ${t(lang, 'help.configReset')}`,
51 ` /astrolabe worktrees ${t(lang, 'help.worktrees')}`,
52 ` /astrolabe recap [id] ${t(lang, 'help.recap')}`,
53 ` /astrolabe kpis ${t(lang, 'help.kpis')}`,
54 ` /astrolabe focus [on|off] ${t(lang, 'help.focus')}`,
55 t(lang, 'help.block.options'),
56 // Each option with its value now (048 #75).
57 ` ${t(lang, 'help.options')}: ${OPTION_NAMES.map(name => `${name}=${optionsSeen[name] === undefined ? 'default' : String(optionsSeen[name])}`).join(', ')}.`,
58 t(lang, 'help.block.keys'),
59 ` ${t(lang, 'help.tabs')}`,
60 ` ${t(lang, 'help.filterSyntax')}`,
61 ` 1 ${t(lang, 'tab.specs').padEnd(labelWidth)} ${t(lang, 'help.specs')}`,
62 ` 2 ${t(lang, 'tab.session').padEnd(labelWidth)} ${t(lang, 'help.sessionTab')} · ${t(lang, 'help.dashboardTab')}`,
63 ` 3 ${t(lang, 'tab.prs').padEnd(labelWidth)} ${t(lang, 'help.prsTab')}`,
64 ` 4 ${t(lang, 'tab.setup').padEnd(labelWidth)} ${t(lang, 'help.configTab')} · ${t(lang, 'help.modelsTab')}`,
65 ` ? ${t(lang, 'tab.help').padEnd(labelWidth)} ${t(lang, 'help.helpTab')}`,
66 // The keys grouped by tab, and one example per filter of the Specs filter language (066 #29).
67 ...(['pane', 'specs', 'tasks', 'session', 'prs', 'setup', 'examples'] as const).map(group => ` ${t(lang, `help.keys.${group}` as TextKey)}`),
68 ` ${t(lang, 'help.keys')}`,
69 t(lang, 'help.block.models'),
70 ` ${t(lang, 'help.models')}`,
71 ` ${t(lang, 'help.modelsByTask')}`,
72 ...Object.entries(SKILL_MODELS).map(([skill, m]) => ` ${skill.padEnd(22)} ${m.model.replace(/^claude-/, '').padEnd(12)} ${m.effort.padEnd(7)} ${m.why}`),
73 t(lang, 'help.marks'),
74 ` ${t(lang, 'help.footer')}`,
75 ...t(lang, 'help.marksList').split('\n').map(line => ` ${line}`),
76 // The chips' order and colours, from the table the footer reads (054 #48).
77 t(lang, 'help.chipTable'),
78 ...CHIP_TABLE.map(chip => ` ${String(chip.rank).padEnd(4)} ${chip.name.padEnd(labelWidth)} ${chip.colour}`),
79 t(lang, 'help.block.footer'),
80 ...(['nerd', 'emoji', 'ascii'] as const).map(name => helpFooterPreview(name, lang)),
81 t(lang, 'help.glossary'),
82 ...(['constitution', 'specify', 'clarify', 'plan', 'tasks', 'implement'] as const).map(step => ` ${step.padEnd(labelWidth)} ${t(lang, `card.${step}`)}`),
83 // The gates row under the active feature, each one explained (054 #61).
84 t(lang, 'help.gates'),
85 ...(['constitution', 'clarify', 'checklist', 'tasks', 'analyze'] as const).map(gate => ` ${t(lang, `gate.${gate}`).padEnd(labelWidth)} ${t(lang, `help.gate.${gate}`)}`),
86 // What doctor found (052 #42): read when the tab opens, never on the draw path.
87 t(lang, 'help.block.health'),
88 ...(health.length === 0 ? [' …'] : health),
89 // Where to read more (054 #81): each line ends with its link, which the Help tab makes clickable.
90 t(lang, 'help.docs'),
91 ...DOC_LINKS.map(d => ` ${d.name.padEnd(labelWidth)} ${d.url}`),
92 ].join('\n')
93}
94
95export const DOC_LINKS = [
96 { name: 'Spec Kit', url: 'https://github.github.com/spec-kit/' },
97 { name: 'gstack', url: 'https://github.com/garrytan/gstack' },
98 { name: 'Astrolabe', url: 'https://github.com/jonyfs/astrolabe#readme' },
99] as const
100
101export const ABOUT: Readonly<Record<PaneView, TextKey>> = {
102 specs: 'help.specs',
103 session: 'help.sessionTab',
104 prs: 'help.prsTab',
105 setup: 'help.configTab',
106 help: 'help.helpTab',
107}
108
109// The help text built once per language and option set, not on every render (054 #2).
110export let helpCache: { key: string; text: string } | undefined
111
112export const helpText = (lang: Lang, optionsSeen: Readonly<Record<string, unknown>>, health: readonly string[] = []): string => {
113 const key = `${lang}|${JSON.stringify(optionsSeen)}|${health.join('\n')}`
114 if (helpCache?.key !== key) helpCache = { key, text: buildHelp(lang, optionsSeen, health) }
115 return helpCache.text
116}
117
118// Command palette for when the pane cannot open (preset.pane === 'command', 048 #76).
119export const commandPaletteText = (lang: Lang): string => {
120 return [
121 t(lang, 'help.commandPalette'),
122 ` help ${t(lang, 'help.palette.help')}`,
123 ` next ${t(lang, 'help.palette.next')}`,
124 ` status ${t(lang, 'help.palette.status')}`,
125 ` ask <q> ${t(lang, 'help.palette.ask')}`,
126 ` root <dir> ${t(lang, 'help.palette.root')}`,
127 ` allow <pct> <dur> ${t(lang, 'help.palette.allow')}`,
128 ` revoke ${t(lang, 'help.palette.revoke')}`,
129 ` run <id> ${t(lang, 'help.palette.run')}`,
130 ` doctor ${t(lang, 'help.palette.doctor')}`,
131 ` priority <id> <h|l> ${t(lang, 'help.palette.priority')}`,
132 ` review [id] ${t(lang, 'help.palette.review')}`,
133 ` advisor [id] ${t(lang, 'help.palette.advisor')}`,
134 ` config reset ${t(lang, 'help.palette.config')}`,
135 ` worktrees ${t(lang, 'help.palette.worktrees')}`,
136 ` recap [id] ${t(lang, 'help.palette.recap')}`,
137 ` kpis ${t(lang, 'help.palette.kpis')}`,
138 ` focus [on|off] ${t(lang, 'help.palette.focus')}`,
139 ].join('\n')
140}
141hooks/modules/guards.ts 38 lines1import { type SpeckitState } from '../core/types'
2
3/** One line on the active feature for Claude (026 #50); undefined without one. */
4/** The note for a prompt that names a feature other than the active one, by its 3-digit id (054 #91). */
5export const otherFeatureNamed = (text: string, state: SpeckitState): string | undefined => {
6 const active = state.features.find(f => f.dir === state.active?.dir)
7 if (active === undefined) return undefined
8 const ids = [...text.matchAll(/(?:^|[^\d])(\d{3})(?![\d])/g)].map(m => m[1]!)
9 const named = state.features.find(f => f.id !== active.id && ids.includes(f.id))
10 return named === undefined ? undefined : `Astrolabe: this prompt names feature ${named.id} ${named.name}, but the active one is ${active.id} ${active.name}; .specify/feature.json decides which one Spec Kit skills work on.`
11}
12
13/** Why `/speckit-implement` is refused while the active spec has open clarifications (054 #57); undefined to let it run. */
14export const implementRefusal = (skill: string, state: SpeckitState | undefined, waived: ReadonlySet<string>): string | undefined => {
15 if (!/^speckit[-.]implement$/.test(skill) || state === undefined) return undefined
16 const feature = state.features.find(f => f.dir === state.active?.dir)
17 if (feature === undefined || waived.has(feature.dir)) return undefined
18 const open = feature.clarifications ?? 0
19 if (open === 0 && !feature.warnings.includes('clarification-after-plan')) return undefined
20 const count = open === 0 ? 'open [NEEDS CLARIFICATION] markers' : `${open} open [NEEDS CLARIFICATION] marker${open === 1 ? '' : 's'}`
21 return `Astrolabe: feature ${feature.id} ${feature.name} still has ${count} in spec.md. Run /speckit-clarify first. To implement anyway, call /speckit-implement again.`
22}
23
24/** A shell command that can make a spec, move feature.json or switch the branch (054 #5). */
25export const canTouchSpecs = (command: string): boolean =>
26 /\b(git|mv|cp|rm|mkdir|touch|specify|tee|sed|python3?|node|bun|sh|bash|zsh)\b|\.specify|specs\/|>/.test(command)
27
28export const mayChangeGit = (command: string): boolean =>
29 /\bgit\b/.test(command) &&
30 !/\bgit\s+(?:status|log|diff|show|rev-parse|ls-files|check-ignore|version|remote\s+get-url|branch\s+(?:--show-current|--list|-l)|worktree\s+list|config\s+--get)\b/.test(command)
31
32export const mayWriteFiles = (command: string): boolean =>
33 /\b(?:mv|cp|rm|mkdir|rmdir|touch|tee|install|truncate)\b|(?:sed|perl)\s+-i\b|(?:^|[^>])>{1,2}\s*[^=&|]/.test(command) ||
34 (!/\bgit\b/.test(command) && canTouchSpecs(command))
35
36/** A path under a `.specify/` folder: feature.json, the constitution, extensions.yml (053). */
37export const isUnderSpecify = (path: string): boolean => /(^|[\\/])\.specify[\\/]/.test(path)
38hooks/modules/advisor.ts 20 lines1
2
3/** The answer kept for the Session tab: its non-blank lines, at most 12 (055 T004). */
4export const advisorFindings = (answer: string): string =>
5 answer
6 .split(/\r?\n/)
7 .map(line => line.trimEnd())
8 .filter(line => line.trim() !== '')
9 .slice(0, 12)
10 .join('\n')
11
12/** The prompt that asks Claude to have the advisor review a spec (055); the advisor is Claude's own tool. */
13export const advisorPrompt = (feature: { id: string; name: string; dir: string }): string =>
14 [
15 `Review the Spec Kit feature ${feature.id} ${feature.name} with the advisor.`,
16 `Read specs/${feature.dir}/spec.md, and plan.md and tasks.md if they exist, then call the advisor tool.`,
17 'Report what it finds that is missing, ambiguous, inconsistent between the files, untestable or risky, most serious first.',
18 'Do not edit any file; end by proposing the changes for me to approve.',
19 ].join(' ')
20hooks/modules/context.ts 49 lines1import { principleHeadings } from '../core/constitution'
2import { focusNote } from '../core/spec-actions'
3import { parseTasks } from '../core/tasks-parser'
4import { type SpeckitState } from '../core/types'
5import { t, type Lang } from '../core/i18n'
6
7export const featureContext = (state: SpeckitState, driftWarning?: { dir: string; task: string }, focusOn = false): string | undefined => {
8 const feature = state.features.find(f => f.dir === state.active?.dir)
9 if (!state.present || feature === undefined) return undefined
10 const parts = [
11 `the active Spec Kit feature is ${feature.id} ${feature.name}, phase ${feature.phase}${feature.total === 0 ? '' : `, ${feature.done} of ${feature.total} tasks done`}`,
12 ...(state.currentTask === undefined ? [] : [`the current task is ${state.currentTask.id === undefined ? '' : `${state.currentTask.id} `}${state.currentTask.text}`]),
13 ...(state.nextCommand === undefined ? [] : [`the next command is ${state.nextCommand}`]),
14 // What still blocks the feature (054 #84, #86): open questions, open checklist items, analyze not run.
15 ...((feature.clarifications ?? 0) > 0 || feature.warnings.includes('clarification-after-plan') ? ['the spec still has [NEEDS CLARIFICATION] markers'] : []),
16 ...((feature.checklist?.open ?? 0) > 0 ? [`${feature.checklist!.open} checklist items are open`] : []),
17 ...(feature.phase === 'implement' && !state.isAnalyzed && feature.done === 0 ? ['/speckit-analyze has not run on these tasks'] : []),
18 ...(driftWarning === undefined
19 ? []
20 : [`tasks.md and code may have drifted: ${driftWarning.task} in ${driftWarning.dir} was marked done without matching code edits; reconcile before continuing`]),
21 ...(focusOn ? [focusNote(state.currentTask)] : []),
22 ]
23 return `Astrolabe: ${parts.join('; ')}.`
24}
25
26/** The `###` headings under `## Core Principles`, at most 22. */
27export const principlesOf = (text: string): string[] => principleHeadings(text).map(p => p.name)
28
29/** `/astrolabe status` (025 #42): the active feature, the next command and the footer, as text. */
30/** The tasks an edit ticks: unticked in the old text, ticked in the new (025 #43). */
31export const tickedBy = (before: string, after: string): string[] => {
32 const was = new Map(parseTasks(before).map(task => [task.id ?? task.text, task.isDone]))
33 return parseTasks(after)
34 .filter(task => task.isDone && was.get(task.id ?? task.text) === false)
35 .map(task => `${task.id === undefined ? '' : `${task.id} `}${task.text}`)
36}
37
38export const statusText = (state: SpeckitState, footer: string, lang: Lang): string => {
39 const feature = state.features.find(f => f.dir === state.active?.dir)
40 const lines = [
41 feature === undefined
42 ? t(lang, 'status.noActive')
43 : `◆ ${feature.id} ${feature.name}: ${feature.phase}${feature.total === 0 ? '' : `, ${feature.done}/${feature.total} tasks (${Math.floor((feature.done * 100) / feature.total)}%)`}`,
44 ...(state.nextCommand === undefined ? [] : [`${t(lang, 'status.next')}: ${state.nextCommand}`]),
45 footer,
46 ]
47 return lines.join('\n\n')
48}
49hooks/modules/history-rows.ts 47 lines1import { type SessionStats } from '../core/types'
2import { sparkline } from '../core/dashboard'
3import { estimateLeft, slowest, type FeatureDuration } from '../core/history'
4import { t, type Lang } from '../core/i18n'
5
6/** The Dashboard's rows from 021: task history, feature durations, this week. */
7export function historyRows(
8 stats: SessionStats,
9 feature: { dir: string; id: string; done: number; total: number } | undefined,
10 featureDurations: readonly FeatureDuration[] = [],
11 lang: Lang = 'en',
12): Array<[string, string]> {
13 const rows: Array<[string, string]> = []
14 for (const duration of featureDurations) {
15 if (duration.ms !== undefined) rows.push([t(lang, 'kpi.specToDone'), `${duration.id} ${duration.name} · ${minutes(duration.ms)}`])
16 }
17 const times = stats.taskTimes ?? []
18 if (feature !== undefined) {
19 const slow = slowest(times, feature.dir, 1)[0]
20 if (slow !== undefined) rows.push([t(lang, 'kpi.slowest'), `${slow.id} · ${minutes(slow.ms)}`])
21 const open = feature.total - feature.done
22 const left = estimateLeft(times, feature.dir, open)
23 if (left !== undefined) rows.push([t(lang, 'kpi.estimate'), t(lang, 'kpi.estimateValue', { time: minutes(left), n: open })])
24 }
25 if (stats.week !== undefined) rows.push([t(lang, 'kpi.week'), t(lang, 'kpi.weekValue', { tasks: stats.week.tasks, features: stats.week.features })])
26 // Time per feature this week (046 #55): sum each feature's task times.
27 if (feature !== undefined && feature.total > 0) {
28 const featureTime = (stats.taskTimes ?? []).filter(t => t.dir === feature.dir).reduce((sum, t) => sum + t.ms, 0)
29 if (featureTime > 0) rows.push([t(lang, 'kpi.featureTime', { id: feature.id }), t(lang, 'kpi.featureTimeValue', { time: minutes(featureTime) })])
30 }
31 if (stats.weekdays !== undefined && stats.weekdays.some(n => n > 0)) {
32 const top = Math.max(...stats.weekdays)
33 rows.push([t(lang, 'kpi.weekdays'), `${sparkline(stats.weekdays.map(n => (n * 100) / top))} M T W T F S S`])
34 }
35 // Tasks done over the last 8 weeks (054 #40), once more than one week has any.
36 if (stats.weeksTrend !== undefined && stats.weeksTrend.filter(n => n > 0).length > 1) {
37 const top = Math.max(...stats.weeksTrend)
38 rows.push([t(lang, 'kpi.weeks'), t(lang, 'kpi.weeksValue', { line: sparkline(stats.weeksTrend.map(n => (n * 100) / top)), n: stats.weeksTrend.at(-1) ?? 0 })])
39 }
40 return rows
41}
42
43export const minutes = (ms: number) => {
44 const m = Math.max(1, Math.round(ms / 60_000))
45 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
46}
47hooks/modules/durations.ts 21 lines1import { type FeatureDuration, type FeatureDurations } from '../core/history'
2
3export const isRecord = (value: unknown): value is Record<string, unknown> =>
4 typeof value === 'object' && value !== null && !Array.isArray(value)
5
6export const isFeatureDuration = (value: unknown): value is FeatureDuration => {
7 if (!isRecord(value)) return false
8 if (typeof value.dir !== 'string' || typeof value.id !== 'string' || typeof value.name !== 'string') return false
9 if (typeof value.startedAt !== 'number' || !Number.isFinite(value.startedAt)) return false
10 if (value.ms === undefined && value.completedAt === undefined) return true
11 return typeof value.ms === 'number' && Number.isFinite(value.ms) && value.ms >= 0 &&
12 typeof value.completedAt === 'number' && Number.isFinite(value.completedAt)
13}
14
15export const readFeatureDurations = (value: unknown): FeatureDurations | undefined => {
16 if (!isRecord(value)) return undefined
17 return Object.entries(value).every(([dir, item]) => isFeatureDuration(item) && item.dir === dir)
18 ? value as FeatureDurations
19 : undefined
20}
21hooks/modules/pane-data.ts 34 lines1import { filterFeatures } from '../core/pane'
2import { type PaneState, type SessionStats, type GitState, type PullRequest, type SpeckitState } from '../core/types'
3
4export const withPr = (git: GitState, pr: PullRequest | undefined): GitState => {
5 const { pr: _old, ...rest } = git
6 return pr === undefined ? rest : { ...rest, pr }
7}
8
9/** Feature id to the worktrees working on it (054 #49). */
10export const worktreesById = (list: SessionStats['worktrees']): Record<string, string[]> => {
11 const out: Record<string, string[]> = {}
12 for (const w of list ?? []) (out[w.id] ??= []).push(w.name)
13 return out
14}
15
16/** Keeps the features whose id or name holds the filter (024 #49). */
17export const filtered = (
18 state: SpeckitState,
19 filter: string | undefined,
20 status: PaneState['status'] = 'all',
21 context: { priorities?: Record<string, 'high' | 'normal' | 'low'>; worktrees?: Record<string, string[]>; taskDirs?: ReadonlySet<string> } = {},
22): SpeckitState =>
23 (filter ?? '').trim() === '' && status === 'all' ? state : { ...state, features: filterFeatures(state.features, filter, state.active?.dir, status, context) }
24
25/** Whether a colour is light enough to carry dark text (039), by its relative luminance. */
26export const isLight = (hex: string): boolean => {
27 const n = Number.parseInt(hex.slice(1), 16)
28 const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map(c => {
29 const v = c / 255
30 return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
31 })
32 return 0.2126 * r! + 0.7152 * g! + 0.0722 * b! > 0.3
33}
34hooks/core/band.ts 276 lines1// Lays out the band above the prompt: one row (065, board 1 and 2). Pure: no $.
2// Returns segments, each with the theme role that colors it; the surface turns them into
3// elements. The widest form that fits the columns left of the right-edge buttons wins, and
4// the id, the current step and n/m are never dropped.
5import { activeMark } from './status-text'
6import { t, type Lang } from './i18n'
7import { phaseShort } from './phase'
8import { byPriority, type Priorities } from './spec-actions'
9import { sectionOf } from './pane'
10import type { ThemeRole } from './theme'
11import { STATE_GLYPHS } from './glyphs'
12import type { Feature, Phase, PullRequest, SpeckitState, Step } from './types'
13
14export type Segment = {
15 key: string
16 text: string
17 role: ThemeRole
18 /** Drawn with a background of the role and the stronger-contrast foreground. */
19 chip?: true
20 bold?: true
21 /** Drawn a shade lighter: the step finished in the last 30 seconds (065 #18). */
22 bright?: true
23 /** A path under the project root; the surface makes the segment a link. */
24 href?: string
25 /** The surface draws a button for it: `lift` lifts the hold for one hour, `task` opens the pane at that task (078). */
26 action?: 'lift' | 'task'
27}
28
29const STEPS: readonly Step[] = ['constitution', 'specify', 'clarify', 'plan', 'tasks', 'implement']
30const FEATURE_STEPS: readonly Phase[] = ['specify', 'clarify', 'plan', 'tasks', 'implement']
31
32// A segment that is a button draws as `[ text ]`: four cells beyond its text.
33const width = (segments: readonly Segment[]): number => segments.reduce((n, s) => n + [...s.text].length + (s.action === undefined ? 0 : 4), 0)
34
35export const bandText = (segments: readonly Segment[]): string => segments.map(s => s.text).join('')
36
37const gap = (key: string, text = ' '): Segment => ({ key: `gap-${key}`, text, role: 'muted' })
38
39export type BandDensity = 'full' | 'compact' | 'minimal'
40export type BandExtras = {
41 /** How much the band shows (042 #20). */
42 density?: BandDensity
43 /** The worktree the active feature runs in, when it is another one (042 #18). */
44 worktree?: string
45 /** Cells the right-edge buttons take: the left side fits what is left. */
46 reserved?: number
47 /** The governor's state: at stop or ceiling the band says paused, at hold it says holding. */
48 governor?: { band: 'ok' | 'throttle' | 'hold' | 'stop' | 'ceiling'; until?: string }
49 /** How many agents and gates are live: counts only, the names are the live table's (065 #16). */
50 live?: { agents: number; gates: number }
51 /** The deciding window's text, kept by the idle and minimal bands (065 #20). */
52 deciding?: { text: string; role: ThemeRole }
53 /** The time the current task has run, from 200 columns. */
54 taskElapsed?: string
55 /** A phase finished in the last 30 seconds: the step chip brightens instead of a toast. */
56 bright?: boolean
57}
58
59const inProgressOthers = (state: SpeckitState): Feature[] =>
60 state.features.filter(f => f.dir !== state.active?.dir && f.phase !== 'done' && f.phase !== 'abandoned')
61
62/** Names the features counted by the band's +N badge (052 #43). */
63export const otherFeaturesCard = (state: SpeckitState, lang: Lang = 'en'): string | undefined => {
64 const features = inProgressOthers(state)
65 return features.length === 0 ? undefined : t(lang, 'band.otherFeatures', { features: features.map(f => `${f.id} ${f.name}`).join(', ') })
66}
67
68type Rail = { step: Step; name: string; file: string }
69
70/** The steps of a track, in order, each with the file a click opens. */
71const railOf = (feature: Feature, constitutionRatified: boolean): { done: Rail[]; current: Rail | undefined } => {
72 const dir = feature.dir
73 const file = (name: string) => `specs/${dir}/${name}`
74 if (feature.track === 'quick') {
75 // spec → tasks → impl (065 #11): the tasks live in spec.md.
76 const hasTasks = feature.total > 0
77 const done: Rail[] = [{ step: 'specify', name: 'spec', file: file('spec.md') }]
78 if (hasTasks) done.push({ step: 'tasks', name: 'tasks', file: file('spec.md') })
79 const current: Rail | undefined = feature.phase === 'done' ? undefined : hasTasks ? { step: 'implement', name: 'impl', file: file('spec.md') } : { step: 'tasks', name: 'tasks', file: file('spec.md') }
80 return { done: feature.phase === 'done' ? [...done, { step: 'implement', name: 'impl', file: file('spec.md') }] : done, current }
81 }
82 const files: Record<string, string> = { specify: 'spec.md', clarify: 'spec.md', plan: 'plan.md', tasks: 'tasks.md', implement: 'tasks.md' }
83 const index = feature.phase === 'done' ? FEATURE_STEPS.length : FEATURE_STEPS.indexOf(feature.phase)
84 const done: Rail[] = FEATURE_STEPS.slice(0, Math.max(0, index)).map(p => ({ step: p as Step, name: p, file: file(files[p]!) }))
85 const phase = FEATURE_STEPS[index]
86 const current: Rail | undefined = phase === undefined || !constitutionRatified && false ? undefined : { step: phase as Step, name: phase, file: file(files[phase]!) }
87 return { done, current }
88}
89
90type Options = {
91 /** The finished steps' marks; the last thing but the id and the step to go. */
92 marks: boolean
93 /** The `n/m` in the step chip; shed only when even the chip does not fit. */
94 count: boolean
95 names: boolean
96 name: boolean
97 bar: number
98 percent: boolean
99 title: 'full' | 'cut' | 'none'
100 live: boolean
101 task: boolean
102 elapsed: boolean
103}
104
105const BAR_ROLE_EMPTY: ThemeRole = 'barEmpty'
106
107const chipText = (feature: Feature, rail: Rail | undefined, blocked: boolean, running: boolean, withCount: boolean): { text: string; role: ThemeRole } => {
108 if (feature.phase === 'done' || rail === undefined) return { text: ' ✓ done ', role: 'done' }
109 if (blocked) return { text: ` ? clarify ${feature.clarifications ?? 0} `, role: 'blocked' }
110 const count = withCount && feature.total > 0 && rail.step === 'implement' ? ` ${feature.done}/${feature.total}` : ''
111 return { text: ` ▶ ${rail.name}${count}${running ? ' …' : ''} `, role: 'current' }
112}
113
114/** One form of the band for the options, or the pieces it would show. */
115const build = (state: SpeckitState, feature: Feature, extras: BandExtras, o: Options, titleRoom: number): Segment[] => {
116 const active = state.active!
117 const ratified = state.constitution === 'ratified'
118 const { done, current } = railOf(feature, ratified)
119 const blocked = feature.warnings.includes('clarification-after-plan') && (feature.clarifications ?? 0) > 0
120 const running = state.runningSkill?.step !== undefined && current !== undefined && state.runningSkill.step === current.step
121 const idText = activeMark(state).replace(/^◆ /, '')
122 const out: Segment[] = [{ key: 'id', text: ` ${idText} `, role: 'accent', chip: true, href: `specs/${feature.dir}/spec.md` }]
123 if (o.name) {
124 out.push(gap('name', ' '), { key: 'name', text: active.name, role: 'text', bold: true })
125 const others = inProgressOthers(state).length
126 if (others > 0) out.push(gap('others'), { key: 'others', text: `+${others}`, role: 'muted' })
127 if (extras.worktree !== undefined) out.push(gap('worktree'), { key: 'worktree', text: `⎇ ${extras.worktree}`, role: 'muted' })
128 }
129 out.push(gap('rail', o.name ? (o.marks ? ' ' : ' ') : o.marks ? ' ' : ''))
130 if (o.marks && !ratified) out.push({ key: 'mark-constitution', text: o.names ? '◐ constitution' : '◐', role: 'current', href: '.specify/memory/constitution.md' }, gap('constitution', o.names ? ' ' : ''))
131 if (o.marks) done.forEach((r, i) => {
132 if (i > 0 && o.names) out.push(gap(`step-${r.step}`))
133 out.push({ key: `mark-${r.step}`, text: '✓', role: 'done', href: r.file })
134 if (o.names) out.push(gap(`label-${r.step}`, ' '), { key: `label-${r.step}`, text: r.name, role: 'muted', href: r.file })
135 })
136 const chip = chipText(feature, current, blocked, running, o.count)
137 if (o.marks && (done.length > 0 || !ratified)) out.push(gap('chip', ' '))
138 out.push({ key: 'chip-step', text: chip.text, role: chip.role, chip: true, ...(extras.bright === true ? { bright: true as const } : {}) })
139 if (running && current !== undefined) out.push({ key: `running-${current.step}`, text: '', role: 'accent' })
140 if (o.bar > 0 && feature.total > 0) {
141 // One heavy line: blue where done, dim where left (board 1, 2).
142 const filled = Math.floor((feature.done * o.bar) / feature.total)
143 out.push(gap('bar', ' '), { key: 'bar-fill', text: '━'.repeat(filled), role: 'barFill' }, { key: 'bar-empty', text: '━'.repeat(o.bar - filled), role: BAR_ROLE_EMPTY })
144 if (o.percent) out.push(gap('percent'), { key: 'percent', text: `${Math.floor((feature.done * 100) / feature.total)}%`, role: 'muted' })
145 }
146 const governor = extras.governor
147 const taskGap = o.percent && o.bar > 0 && feature.total > 0 ? ' ' : ' '
148 if (o.task && governor !== undefined && (governor.band === 'stop' || governor.band === 'ceiling')) {
149 out.push(gap('task', taskGap), { key: 'bar-sep', text: '│', role: 'pending' }, gap('paused'), { key: 'paused', text: `‖ paused until ${governor.until ?? '?'}`, role: 'blocked' }, gap('lift'), { key: 'lift', text: 'lift 1h', role: 'blocked', action: 'lift' })
150 } else if (o.task && governor !== undefined && governor.band === 'hold') {
151 out.push(gap('task', taskGap), { key: 'bar-sep', text: '│', role: 'pending' }, gap('paused'), { key: 'paused', text: '‖ holding new subagents', role: 'blocked' })
152 } else if (o.task && state.currentTask?.id !== undefined && feature.phase !== 'done') {
153 out.push(gap('task', taskGap), { key: 'bar-sep', text: '│', role: 'pending' }, gap('task-id'), { key: 'task-id', text: `▸ ${state.currentTask.id}`, role: 'current', action: 'task' })
154 if (o.title !== 'none' && state.currentTask.text !== '') {
155 const full = ` ${state.currentTask.text}`
156 const title = o.title === 'full' ? full : titleRoom >= 4 ? (full.length > titleRoom ? `${full.slice(0, Math.max(1, titleRoom - 1)).trimEnd()}…` : full) : ''
157 if (title !== '') out.push({ key: 'task-title', text: title, role: 'muted' })
158 if (o.elapsed && extras.taskElapsed !== undefined) out.push({ key: 'task-elapsed', text: ` · ${extras.taskElapsed}`, role: 'muted' })
159 }
160 }
161 if (o.live && extras.live !== undefined && (extras.live.agents > 0 || extras.live.gates > 0)) {
162 const parts = [extras.live.agents > 0 ? `${extras.live.agents} agents` : '', extras.live.gates > 0 ? `${extras.live.gates} gates` : ''].filter(x => x !== '')
163 out.push(gap('live', ' '), { key: 'live', text: parts.join(' · '), role: 'muted' })
164 }
165 if (extras.deciding !== undefined && extras.density === 'minimal') out.push(gap('deciding', ' '), { key: 'deciding', text: extras.deciding.text, role: extras.deciding.role })
166 return out
167}
168
169/** The layout tier of a width: what the full form shows at 200, 144, 100 and below (board 2). */
170const tierOf = (columns: number, density: BandDensity | undefined): Options => {
171 const effective = density === 'minimal' ? 80 : density === 'compact' ? Math.min(columns, 100) : columns
172 if (effective >= 200) return { marks: true, count: true, names: true, name: true, bar: 20, percent: true, title: 'full', live: true, task: true, elapsed: true }
173 if (effective >= 144) return { marks: true, count: true, names: true, name: true, bar: 13, percent: false, title: 'cut', live: true, task: true, elapsed: false }
174 if (effective >= 100) return { marks: true, count: true, names: false, name: true, bar: 9, percent: false, title: 'none', live: false, task: true, elapsed: false }
175 return { marks: true, count: true, names: false, name: false, bar: 0, percent: false, title: 'none', live: false, task: true, elapsed: false }
176}
177
178/** The branch's pull request at the band's right edge, from 200 columns of a full band (board 2). */
179export const bandPr = (
180 pr: Pick<PullRequest, 'number' | 'checks'> | undefined,
181 columns: number,
182 density?: BandDensity,
183): { label: string; mark: string; role: ThemeRole } | undefined => {
184 if (pr === undefined || columns < 200 || density === 'compact' || density === 'minimal') return undefined
185 const mark = pr.checks === 'pass' ? '✓' : pr.checks === 'fail' ? '✖' : pr.checks === 'pending' ? STATE_GLYPHS.elapsed : ''
186 const role: ThemeRole = pr.checks === 'pass' ? 'done' : pr.checks === 'fail' ? 'blocked' : 'current'
187 return { label: `PR #${pr.number}`, mark, role }
188}
189
190export const bandSegments = (state: SpeckitState, columns: number, extras: BandExtras = {}): Segment[] => {
191 const active = state.active
192 if (!state.present || active === undefined) return []
193 const feature = state.features.find(f => f.dir === active.dir)
194 const room = Math.max(0, columns - (extras.reserved ?? 0))
195 if (feature === undefined) return [{ key: 'id', text: ` ${activeMark(state).replace(/^◆ /, '')} `, role: 'accent', chip: true }]
196 if (feature.phase === 'abandoned') {
197 const id: Segment = { key: 'id', text: ` ${activeMark(state).replace(/^◆ /, '')} `, role: 'accent', chip: true, href: `specs/${feature.dir}/spec.md` }
198 const label: Segment[] = [gap('abandoned', ' '), { key: 'abandoned', text: 'abandoned', role: 'muted' }]
199 const name: Segment[] = [gap('name', ' '), { key: 'name', text: active.name, role: 'text', bold: true }]
200 return ([[id, ...name, ...label], [id, ...label], [id]] as Segment[][]).find(form => width(form) <= room) ?? []
201 }
202 const start = tierOf(columns, extras.density)
203 // Further shedding, in the board's drop order: title, live counts, step names, name, bar.
204 const steps: Array<(o: Options) => Options> = [
205 o => ({ ...o, elapsed: false }),
206 o => ({ ...o, title: o.title === 'full' ? 'cut' : 'none' }),
207 o => ({ ...o, title: 'none' }),
208 o => ({ ...o, live: false }),
209 o => ({ ...o, names: false }),
210 o => ({ ...o, name: false }),
211 o => ({ ...o, percent: false }),
212 o => ({ ...o, bar: 0 }),
213 o => ({ ...o, task: false }),
214 o => ({ ...o, marks: false }),
215 o => ({ ...o, count: false }),
216 ]
217 let o = start
218 const tryFit = (opts: Options): Segment[] | undefined => {
219 const bare = build(state, feature, extras, { ...opts, title: opts.title === 'cut' ? 'none' : opts.title }, 0)
220 if (opts.title === 'cut') {
221 const without = width(bare)
222 const roomForTitle = room - without - 1
223 if (roomForTitle >= 4) {
224 const form = build(state, feature, extras, opts, roomForTitle)
225 if (width(form) <= room) return form
226 }
227 return width(bare) <= room ? bare : undefined
228 }
229 const form = build(state, feature, extras, opts, 0)
230 return width(form) <= room ? form : undefined
231 }
232 let form = tryFit(o)
233 for (const step of steps) {
234 if (form !== undefined) break
235 o = step(o)
236 form = tryFit(o)
237 }
238 if (form !== undefined) return form
239 // Nothing fits: the id, then the id alone is cut by the caller's row.
240 const idOnly: Segment[] = [{ key: 'id', text: ` ${activeMark(state).replace(/^◆ /, '')} `, role: 'accent', chip: true, href: `specs/${feature.dir}/spec.md` }]
241 return width(idOnly) <= room ? idOnly : []
242}
243
244/** The hover card of each rail step (024 #10): what the step is for and how many features are in it. */
245export const stepCards = (features: readonly Feature[], lang: Lang = 'en'): Array<{ step: Step; text: string }> =>
246 STEPS.map(step => {
247 const n = features.filter(f => f.phase === step).length
248 const about = t(lang, `card.${step}`)
249 if (step === 'constitution') return { step, text: `${step}: ${about}` }
250 const count = n === 0 ? t(lang, 'card.none') : n === 1 ? t(lang, 'card.one') : t(lang, 'card.many', { n })
251 return { step, text: `${step}: ${about} · ${count}` }
252 })
253
254/** The rail step a segment belongs to, by its key (`label-plan`, `mark-plan`, `running-plan`). */
255export const stepOf = (segment: Segment): Step | undefined => {
256 const m = /^(?:label|mark|running)-(.+)$/.exec(segment.key)
257 return m !== null && (STEPS as readonly string[]).includes(m[1]!) ? (m[1] as Step) : undefined
258}
259
260/** Why the next command is next (042 #14), shown while the pointer is on its button. */
261export const nextReason = (state: SpeckitState, lang: Lang = 'en', priorities: Priorities = {}): string | undefined => {
262 const command = state.nextCommand
263 if (command === undefined) return undefined
264 const feature = state.features.find(f => f.dir === state.active?.dir)
265 const step = command.replace(/^\/speckit-/, '')
266 if (step === 'implement' && feature !== undefined) return t(lang, 'reason.implement', { n: feature.total - feature.done })
267 if (step === 'specify' && feature !== undefined && feature.phase !== 'specify') {
268 if (feature.phase === 'done') {
269 const next = byPriority(state.features.filter(f => sectionOf(f, feature.dir) === 'next'), priorities)[0]
270 if (next !== undefined) return t(lang, 'reason.specifyNextPriority', { feature: `${next.id} ${next.name}`, priority: priorities[next.id] ?? 'normal' })
271 }
272 return t(lang, 'reason.specifyNext')
273 }
274 return (['constitution', 'specify', 'clarify', 'plan', 'tasks', 'analyze'] as const).includes(step as never) ? t(lang, `reason.${step}` as never) : undefined
275}
276hooks/core/hint.ts 15 lines1// The text Astrolabe adds after the engine's prompt hint (FR-007). Pure: no $.
2// The next command lives in one place (065 #14): the prompt suggestion while the prompt is
3// empty, this hint only while it has text, never both.
4import type { SpeckitState } from './types'
5
6export const hintTail = (state: SpeckitState, isDraft: boolean): string | undefined => {
7 if (!isDraft || !state.present || state.nextCommand === undefined) return undefined
8 const active = state.active
9 const feature = active === undefined ? undefined : state.features.find(f => f.dir === active.dir)
10 const next = `next: ${state.nextCommand}`
11 if (feature?.phase !== 'implement' || feature.total === 0) return next
12 const left = feature.total - feature.done
13 return left > 0 ? `${next} · ${left} ${left === 1 ? 'task' : 'tasks'} left` : next
14}
15hooks/core/phase-toast.ts 50 lines1// Decides which phase toasts a reconcile raises (FR-001). Pure: no $.
2import { t, type Lang } from './i18n'
3import type { Feature, Phase } from './types'
4
5export type Toast = { key: string; text: string }
6
7const ORDER: readonly Phase[] = ['specify', 'clarify', 'plan', 'tasks', 'implement', 'done']
8const NEXT: Readonly<Record<string, string>> = {
9 specify: '/speckit-specify',
10 clarify: '/speckit-clarify',
11 plan: '/speckit-plan',
12 tasks: '/speckit-tasks',
13 implement: '/speckit-implement',
14 done: '/speckit-specify',
15}
16
17/**
18 * Compares derived phases with the stored baseline. The first reconcile of a session
19 * (`isBaselined` false) only records; later ones toast each move to a later phase once
20 * per session. The returned baseline always holds the current phases.
21 */
22export const phaseToasts = (
23 features: readonly Feature[],
24 baseline: Readonly<Record<string, Phase>>,
25 toasted: readonly string[],
26 isBaselined: boolean,
27 /** The real next command for a feature (the active one's may be /speckit-analyze). */
28 nextOf: Readonly<Record<string, string>> = {},
29 lang: Lang = 'en',
30): { toasts: Toast[]; baseline: Record<string, Phase>; toasted: string[] } => {
31 // Only listed features stay, so the stored baseline never grows with deleted ones.
32 const next: Record<string, Phase> = {}
33 const toasts: Toast[] = []
34 const seen = [...toasted]
35 for (const f of features) {
36 const before = baseline[f.dir]
37 next[f.dir] = f.phase
38 if (!isBaselined || before === undefined || before === 'abandoned' || f.phase === 'abandoned') continue
39 const key = `${f.dir}:${f.phase}`
40 if (ORDER.indexOf(f.phase) <= ORDER.indexOf(before) || seen.includes(key)) continue
41 seen.push(key)
42 const text =
43 f.phase === 'done'
44 ? t(lang, 'toast.done', { id: f.id, name: f.name, next: NEXT.done! })
45 : t(lang, 'toast.moved', { id: f.id, name: f.name, phase: f.phase, next: nextOf[f.dir] ?? NEXT[f.phase]! })
46 toasts.push({ key, text })
47 }
48 return { toasts, baseline: next, toasted: seen }
49}
50hooks/core/next-command.ts 31 lines1// The Spec Kit command that moves the active feature forward (FR-021). Pure: no $.
2import type { ConstitutionState, Feature, Phase } from './types'
3
4export type NextCommandInput = {
5 present: boolean
6 constitution: ConstitutionState
7 active?: Pick<Feature, 'phase' | 'done'>
8 isAnalyzed: boolean
9}
10
11const BY_PHASE: Partial<Record<Phase, string>> = {
12 specify: '/speckit-specify',
13 clarify: '/speckit-clarify',
14 plan: '/speckit-plan',
15 tasks: '/speckit-tasks',
16}
17
18export const nextCommand = (input: NextCommandInput): string | undefined => {
19 if (!input.present) return undefined
20 if (input.constitution !== 'ratified') return '/speckit-constitution'
21 const active = input.active
22 if (active === undefined || active.phase === 'done' || active.phase === 'abandoned') return '/speckit-specify'
23 const byPhase = BY_PHASE[active.phase]
24 if (byPhase !== undefined) return byPhase
25 return active.done === 0 && !input.isAnalyzed ? '/speckit-analyze' : '/speckit-implement'
26}
27
28/** The feature that moved to done between two reads (054 #90), for the retro suggestion. */
29export const justFinished = <F extends Pick<Feature, 'dir' | 'phase'>>(before: readonly F[], after: readonly F[]): F | undefined =>
30 after.find(f => f.phase === 'done' && before.some(b => b.dir === f.dir && b.phase !== 'done'))
31