Development autopilot — 30 lifecycle skills + 3 methodology agents + 40 hooks (26 default-on, 14 opt-in) enforcing Three Red Lines discipline…

<table border="0" cellspacing="0" cellpadding="0"> <tr> <td valign="middle"><img src="docs/assets/icon.svg" alt="Autopilot" height="180"></td> <td width="24"></td> <td valign="middle"><img src="docs/assets/hero.svg" alt="Autopilot — Claude Code-first lifecycle orchestration with portable paths for Codex, OpenCode, and agy" height="180"></td> </tr> </table>
<img src="https://img.shields.io/badge/Claude_Code-plugin-5A67D8?style=flat-square&logo=anthropic&logoColor=white" alt="Claude Code Plugin"> <img src="https://img.shields.io/badge/version-3.0.0--alpha.6-E8A838?style=flat-square" alt="v3.0.0-alpha.6"> <img src="https://img.shields.io/badge/skills-30-4A90D9?style=flat-square" alt="30 Skills"> <img src="https://img.shields.io/badge/agents-3-7C9E8C?style=flat-square" alt="3 Methodology Agents"> <img src="https://img.shields.io/badge/hooks-40-6B8E6B?style=flat-square" alt="40 Hooks"> <img src="https://img.shields.io/badge/dependencies-zero-A8B5A0?style=flat-square" alt="Zero Dependencies"> <img src="https://img.shields.io/badge/license-MIT-D4A5A5?style=flat-square" alt="MIT License">
<b>English</b> | <a href="README.zh-TW.md">正體中文</a>
<b>The AI project lead for your terminal.</b><br> Claude Code is the full home base. Autopilot plans, delegates, reviews with a second engine, and remembers what it learned — with portable paths for Codex, OpenCode, and agy where their harnesses support them.
<sub>Distilled from 100+ completed AI-development projects.</sub>
# autopilot's optional pre-push hook:
❯ git push
[autopilot] completeness scan … ✗ TODO stub in auth.py:42
[autopilot] tests … ✗ 1 skipped (payment flow)
[autopilot] review … ⚠ unhandled error path
push blocked — fix it, or override with a reason
Claude Code is still the most complete host. Autopilot makes AI coding agents finish the job — the planning, checking, deciding, and remembering you'd otherwise do by hand:
/l3 /l4 /l5 /l6 and ceo-agent can take a task end-to-end (sized, planned, built, reviewed, closed) and only stop to ask at the decisions that actually matter..claude/.It ships first as a Claude Code plugin — 30 skills, 3 methodology agents, 40 hooks (26 default-on, 14 opt-in), zero dependencies — and keeps the same methodology portable where other harnesses expose compatible skill, agent, or plugin surfaces. It works fully on its own, and also plays nicely with the superpowers plugin if you have it.
This README was written by Claude and adversarially reviewed by GPT-5.5 and Gemini through Autopilot's own second-engine review flow.
New here? This page is the 5-minute tour. Everything deeper lives in Learn More.
dev-flow is the front door. It sizes the task and routes it — small things go straight through the gate, large things become a tracked project:
<img alt="A day with Autopilot: dev-flow sizes the task and routes it — small tasks go straight through the quality gate to commit; large tasks become a tracked project with a quality gate each phase, then finish-flow closes cleanly. Without Autopilot, the AI greps the codebase immediately — no plan, no phases, no quality gates." src="docs/assets/flow.svg" width="100%">
Without Autopilot, Claude starts grep-ing the codebase immediately — no plan, no phases, no quality gates. With it, the discipline is automatic.
/plugin marketplace add cookys/autopilot
/plugin install autopilot@autopilot
That's it. Now just talk to Claude — Autopilot's skills trigger on what you say:
You: "I'm starting on WebSocket compression" → sizes it, sets up a plan + branch + quality gates
You: "quick fix for the null check in auth" → fast path, still gated before commit
You: "what should I work on next?" → scans your projects and ranks them
You: "搞定這個重構,你決定" → full autonomous CEO mode
No commands to memorize — say it in your own words and the right skill steps in.
Autopilot is Claude Code-first, but not Claude Code-only. Pick the entry point that matches the harness you actually use:
| If you are... | Start with | What you get |
|---|---|---|
| Claude Code user | The two-command install above | The complete path: skills, methodology agents, hooks, /l3-/l6, and plugin-managed defaults |
| Codex user | .agents/skills/ in this repo, or the local package under platforms/codex/plugin | Autopilot skills, bundled support payload, and the one production PostCompact recovery hook; no Codex-thread-bound direct-mutation enforcement is shipped (D4=NOT_READY/NO-SHIP) |
| OpenCode user | .agents/skills/ plus .opencode/opencode.json | Shared skills and methodology agent bodies, with an OpenCode-specific in-process plugin wrapper |
Antigravity (agy) user | scripts/install-antigravity.sh | Guarded import as a Claude Code-source plugin; no loose skills-dir scan |
| Contributor | ./scripts/dev-setup.sh --check | A read-only readiness dashboard for Claude/Codex/OpenCode/agy; mutating non-Claude setup requires --harness <name> --install |
The course-sized idea is simple: teach the agent the collaboration discipline once, then stop retyping it.
| Principle | Autopilot default |
|---|---|
| Clarify the work before coding | dev-flow expands goals into size, branch, plan, and gates |
| Ask for proof, not reassurance | quality-pipeline runs tests, scans for incomplete work, and reviews the diff |
| Preserve context outside the model | project-lifecycle, handoff, and finish-flow keep state readable by the next session |
| Don't let one brain self-approve | Heterogeneous review and qc panels read artifacts, not the implementer's story |
| Delegate by risk | /l3-/l6 scale from inline autonomy to heterogeneous implementation and verification authoring |
30 skills, grouped by what you're trying to do. Each one triggers from natural language — the Try saying lines are real triggers.
dev-flow (start here — sizes & routes the task) · quality-pipeline (test → scan → review) · finish-flow (clean closing sequence, nothing skipped).
Try saying: "let's implement X" · "quick fix for Y" · "is this ready to commit?"
survey (dual-agent industry research) · think-tank (6-role debate) · brainstorm (pre-code design exploration) · think-tank-dialectic (irreversible, high-stakes calls).
Try saying: "what do others use for X?" · "should we rewrite or patch?" · "要辯論一下"
ceo-agent (you set the goal, it executes) · /l3 /l4 /l5 /l6 (terse front-doors that pre-fill the CEO startup so one line ships the goal). They escalate where the work runs:
| Runs where | Reach for it when | |
|---|---|---|
/l3 | inline, on this thread | full autonomy, but you want to watch it happen |
/l4 | one background, worktree-isolated foreman | a long run you'd rather offload — your context stays clean, the authoritative quality verdict is held at depth 0 |
/l5 | /l4, but the implementer is a different engine (agy / Gemini) | cost-arbitrage, or a decorrelated second engine doing the mechanical coding |
/l6 | /l5, plus verification authoring is delegated to a different engine | when you want implementation and verification labor offloaded, while depth 0 keeps merge authority |
Ordinary strict /l5 Engine execution is fail-closed: before workflow dispatch, the CLI must match the exact implementer/reviewer/verification-author/QC roster to Autopilot's frozen provider policy and consume fresh host-owned qualification plus live-readiness evidence. Lower-level and legacy flows remain explicitly non-strict.
/l3 fix the flaky reconnect test, you decide # inline
/l4 ship the WebSocket reconnect system # offload to a background foreman
/l5 migrate the config loader to the new schema # foreman + heterogeneous implementer
/l6 ship the parser rewrite # hetero implementer + hetero verification authoring
Try saying: "CEO mode, handle it" · "全權處理" · "/l4 ship the reconnect system"
→ Per-level behaviour, presets, override flags (--expand / -x / --solo), and full examples: docs/skills.md.
Autopilot delegates labor, not authority. Implementer self-report is never evidence; reviewers read the task, diff, logs, and artifacts directly. Deterministic gates stay authoritative, higher-risk work needs decorrelated review coverage, and a no_verdict review never clears a gate.
Autopilot remains one product for strong, weak, remote, and local models. It first admits an exact role + task scope + deployment identity, then compiles exactly one guidance payload: guided gives a bounded slice and explicit structure; autonomous removes redundant choreography for a qualified role. Neither profile changes red lines, effects, egress, assurance, or acceptance.
governance.guidance_profile is a project default (guided when omitted), and a task can override it at intake without editing the project. External benchmark data can only create provisional telemetry. Owner/reviewer qualification uses separate host-scored evals; stored JSON cannot recreate session authority. The repository's v2.33.0 cutover receipt remains hold_guided: the autonomous control source is 113 bytes smaller, but exact host-token measurements, an effectful compatibility witness, a current live owner verifier, and five complete independent dogfood receipts are not yet available. The local OpenAI-compatible adapter passed fake-contract transport tests, but no live local runtime or agentic local runner is claimed.
Claude alone is enough. But point autopilot at a second engine family and its review/implement pipeline gets stronger — a cross-family qc panel catches what one vendor and its same-family reviewer jointly miss, and you get a heterogeneous implementer for cost-arbitrage. Recommended order: a subscription you already pay for ≻ a metered API key — OAuth-login runners (codex / agy / grok / explicit-only qoderclicn) need no token at all; GLM / MiniMax go in one canonical mode-600 file (~/.autopilot/endpoints.env) and are wired declaratively in .claude/review-loop-config.md.
Try saying: "set up a GLM reviewer" · "use MiniMax as the /l5 implementer"
→ Credential placement, the subscription-≻-API-key ladder, and the copy-paste setup: docs/installation.md.
learn (capture lessons) · retro (git-history retrospective) · next (what to do next) · distill (turn your repeated workflows into personal skills) · plus debug · profiling · test-strategy · audit · doc-sync.
Try saying: "record this for next time" · "回顧這週" · "what's the highest priority?"
→ Full catalog of all 30 skills, the three cognitive modes, and how they compose: docs/skills.md.
agent-call contacts an already-running named session. Claude↔Claude uses native ListAgents / SendMessage when the target is exact; other targets go through fleet messaging v2 (the fleet CLI, or the fleet MCP tools). An offline target fails explicitly and never turns into a worker spawn.
Try saying: "ask the running codex session for its status" · "send this to the persistent reviewer"
Claude Code (primary) — the two commands above. All 30 skills are available immediately as autopilot:dev-flow, autopilot:survey, etc.
⚠️ Claude Code ≥ 2.1.233 + Claude 5-era models: the task tools (
TaskCreatefamily) are gated off by default on Opus ≥ 4.8 / Sonnet ≥ 5 / Fable ≥ 5 — which silently disables every dev-flow forcing function. Fix: keep{"env": {"CLAUDE_CODE_ENABLE_TODO_TOOLS": "1"}}in your project's.claude/settings.json(tracked, so worktrees inherit it).autopilot:onboardscaffolds this pin automatically; dev-flow warns once if the tools are still missing.
| Harness | How to start | Supported today | Known limits | |
|---|---|---|---|---|
| Claude Code | /plugin marketplace add cookys/autopilot then /plugin install autopilot@autopilot | Full plugin path: 30 skills, 3 methodology agents, 40 hooks | Primary host; Claude-specific hooks and slash behavior do not automatically transfer to other harnesses | |
| Codex | .agents/skills/, or codex plugin add autopilot@autopilot-local after adding platforms/codex as a marketplace | Skills, generated support payload, and one production PostCompact recovery hook (`manual\ | auto`) | This is a Codex-native recovery boundary, not Claude hook parity; no Claude hook bundle, apps, or MCP servers are loaded. Subagent model routing via spawn_agent needs a user opt-in — see platforms/codex/README.md |
| OpenCode | Open this repo with .agents/skills/; use .opencode/opencode.json for agents | Shared skills, methodology agent bodies, and an OpenCode plugin wrapper | Optional TypeScript deps are only needed when editing the wrapper; hook parity is platform-specific | |
Antigravity (agy) | ./scripts/install-antigravity.sh | Guarded agy plugin validate / install / list flow with export-then-install | Runtime hook firing is still unverified; install does not imply hook behavior parity |
Full per-platform instructions, Windows notes, and the contributor dev-mode workflow are in docs/installation.md. Verified capability boundaries live in references/multi-agent-portability.md.
The deep material, moved out of this page so it stays an onboarding tour:
| Topic | Doc |
|---|---|
| All 30 skills + three modes + how they compose | docs/skills.md |
| Superpowers coexistence — three scenarios, migration | docs/coexistence.md |
Per-project configuration — the .claude/ injection model | docs/configuration.md |
| Installation & development — every platform, dev mode | docs/installation.md |
| Architecture & design — philosophy, methodology agents, credits | docs/architecture.md |
| Review-only candidate review — managed review of a range someone else wrote | docs/review-candidate.md |
| Hooks — 25 runtime-enforcement hooks (tiers in the doc) | hooks/README.md |
| Changelog | CHANGELOG.md |
MIT — see LICENSE for details.
mods/register.ts 31 lines1// mods/register.ts — the plugin's one hooks module. Claude Code takes exactly one `modules` entry per plugin (hooks.json; a second entry is refused) and refuses a second
2// matcher-less `session.start` hook, so this file composes the mods: each keeps its own folder, tests and hooks (registerLive, registerViewer: all but session.start), and
3// the one session.start hook here starts live, roundtable, and viewer. A roundtable or viewer start failure is logged and does not stop the others. The live mod's pressable file paths import showPath directly (the spike showed a plugin's own `$.tool.call` of its own tool is not served).
4
5import type { Register } from 'claude-code'
6
7import { registerLive, startLive } from './live/register'
8import { registerRoundtable, startRoundtable } from './roundtable/register'
9import { registerViewer, startViewer } from './viewer/register'
10
11export const register: Register = on => {
12 registerLive(on)
13 registerRoundtable(on)
14 registerViewer(on)
15 on('session.start', async ($, e, next) => {
16 await startLive($)
17 // a roundtable or viewer registration failing must not stop the others or the chain
18 try {
19 await startRoundtable($)
20 } catch (err) {
21 $.ui.log('autopilot roundtable: start failed: ' + String(err))
22 }
23 try {
24 await startViewer($)
25 } catch (err) {
26 $.ui.log('autopilot viewer: start failed: ' + String(err))
27 }
28 return next(e)
29 })
30}
31mods/live/register.ts 847 lines1// mods/live/register.ts — the `live` mod (mods plan P1c; Claude Code only).
2//
3// Reads files the project watcher publishes and draws a band above the prompt, a pane in a wide fullscreen
4// terminal and a toast on an axis change. It writes no file and starts no program. The one thing it sends to the model is the owner's
5// answer from the 待決 tab: the send Button submits one prompt (`$.prompt.submit`, not as the user).
6//
7// pointer $HOME/.autopilot/live-pointer.json
8// project session marker <autopilot_home>/session-mode/<sid>.json -> <live_base>/runs/paths/*.json longest prefix
9// roots the marker's root_run_id + its `campaign_roots` (the Mission roots of the campaigns the session launched; P1W SCOPE):
10// every root of the set is read like the marker root, one band is merged from them
11// snapshot <live_base>/runs/<project_key>[--<root>].json, else the SSD copy <autopilot_home>/review/<key>/live/runs.<scope>.json
12// context <live_base>/context/<sanitised sid>.json (this sid only)
13// account $CLAUDE_CONFIG_DIR or $HOME /.claude.json `oauthAccount` (Claude Code's own file: email, org, plan; re-read only when its
14// size or mtime changed, at most every 30 s)
15// quota $.session.usage().rateLimits (polled each tick; the `session.measure` event is not used, the tick already redraws)
16// job page <autopilot_home>/review/<key>/<date>/<job>/current/model.json (acceptance axis + gate rows, optional)
17// W3a <live_base>/tasks/<sid>.json, attention/<sid>.json (this sid only)
18// <live_base>/runs/<scope>.decisions.json, <scope>.foreman.json, sources/<scope>.json (scope-checked sidecars)
19// <git-common-dir>/autopilot/work-orders/<root>/*.json (campaign start = earliest bound progress receipt;
20// the common dir comes from the envelope's scope.repo_identity, a published path, never a computed live base)
21//
22// spend <live_base>/runs/spend-history.json (host-wide, schema autopilot.spend-history/1): the Spend tab's hourly sparkline; absent / < 2 samples -> a note
23// P7 <live_base>/runs/<project_key>.qc.json, .residue.json, .review.json; <live_base>/stage/<sid>.json; load-source.json; the marker's
24// §2.9 fields (size, urgent, level, stage, stage_set_at, unit, review_families); the envelope's host_today_brain_usd / brain_cap_usd;
25// the decisions sidecar's `ladder`. Each is optional: absent -> its slot is left out and its tab says "no data".
26// The band is ONE line (band.tsx, layout in model.ts layoutBand); the ⓘ opens the pane on the Now tab (7 tabs: Now Decide Dispatch Review Spend Hygiene ?).
27//
28// i18n every word comes from mods/live/locales/{en,zh-TW}.json (compiled to locales.ts) through `t`; the locale is resolved on every tick:
29// ~/.autopilot/config.json ui.locale > AUTOPILOT_LOCALE > Claude Code's language setting ($.config.list() row `language`, else the
30// user settings.json) > LC_ALL / LANG > en
31//
32// $.session.id() is read on EVERY tick: /clear gives the session a new id while the timer keeps running (S7).
33// Every clock comparison uses $.clock.now(), so a test with a mocked clock decides fresh / stale.
34
35import type { EngineInterface, Register } from 'claude-code'
36
37import { newTracker, parseAdvisories, takeNew } from './advisories'
38import { makeT, resolveLocale, T_EN } from './i18n'
39import type { T } from './i18n'
40import { atom, read, update } from 'claude-code'
41import type { AdvisoryTracker } from './advisories'
42import { SHOW_PRESS, showTarget } from './ui'
43import { Band } from './band'
44import { Pane } from './pane'
45import { newScroll, scrollHook } from './scroll'
46import { showPath } from '../viewer/show'
47import {
48 acceptanceToast, autoResidueCount, cleanTargets, normalizeAbs, decideReply, NO_DECIDE, makeRecentTracker, bandLine1, bandView, buildSections, checkEnvelope, commonDirOf, commonDirOfGitdir, gitdirOfGitFile, countsOf, ctxShown, ctxText, earliestReceiptMs, executionToast,
49 headerText, hhmm, projectName as projectNameOf, isKey, isSectionId, isObject, isPlainRoot, jobOf, longestPrefixKey, mergeDecisions, mergeEnvelopes, mergeJobModels, NO_SECTIONS, PANE_TABS, paneRows, parseJson, portOf, readAttention, readTurn, readDecisions,
50 readForeman, readLoadSource, readSpendHistory, hourlySpend, readJobModel, readManifest, readMarker, readQc, readResidue, readReview, readStageWalk, readTasks, reviewLink, sanitizeSid, scopeKeyOf, sessionUsd,
51 slotTab, slotUnfolds, spendOf, startMsOf, stateText, stalledCount, POINTER_SCHEMA, NO_DETAIL, usd, scanBackground, lastOutputLine, bgLabel, readQuota, readAccount,
52} from './model'
53import type { AccountView, ActivityItem, Counts, DecideState, DecisionsView, RecentGroup, EnvelopeCheck, JobModel, Json, LiveSnapshot, Manifest, PaneTab, SlotId, QuotaWindow, Sources } from './model'
54
55const TICK_MS = 5000
56const PANE_ID = 'autopilot-live'
57const PANE_MIN_COLUMNS = 144
58const MAX_PATH_FILES = 256
59const MAX_RECEIPT_FILES = 64
60const MAX_CAMPAIGN_ROOTS = 8 // session-mode.js CAMPAIGN_ROOTS_MAX
61
62// Module state. A hot reload drops it and session.start rebuilds it (the first tick refills the snapshot at once).
63// What the owner picked and typed on the 待決 tab is NOT here: a drawing's inputs belong in $.state (below), so a hot reload keeps them.
64let snapshot: LiveSnapshot | null = null
65// the 待決 tab's picks, notes and what was already sent, by decision id (the contract is types/index.d.ts, named by plugin.json)
66const DECIDE = atom({ plugin: 'autopilot', key: 'decide' } as const, NO_DECIDE)
67const SURFACES_WITH_INPUT = new Set<string>(['terminal', 'desktop', 'vscode']) // the elements tables with an `Input`; a phone has none (the resolved table hands out a stand-in for it, so the surface is what tells)
68const DECIDE_KEEP_MS = 24 * 3600 * 1000 // a sent question the session never closed is forgotten after a day
69let timer: { cancel: () => void } | undefined
70let viewport: { columns: number; isFullscreen?: boolean } | null = null
71let paneAttempted = false
72let paneTab: PaneTab = 'now'
73const expanded = new Set<string>() // the recent-prompt groups the person opened (by group id)
74const folded = new Set<string>() // the Now sections the person folded (SECTION ids); kept across /clear, a view preference and not tied to the transcript
75const recentTracker = makeRecentTracker()
76let recent: RecentGroup[] | null = null // survives ticks: the snapshot is rebuilt each time, a failed read keeps the last value
77let recentSid: string | null = null // group ids are transcript indexes, so a new session id (/clear) drops every opened group
78let activity: ActivityItem[] | null = null // survives ticks like `recent`: a failed read keeps the last value
79let activitySid: string | null = null // the session id those rows belong to; a failed transcript keeps them only while this id still matches
80const tails = new Map<string, { size: number; mtimeMs: number; tail: string | null }>() // a background command's last output line, re-read only when its file changed
81const MAX_TAIL_BYTES = 1024 * 1024 // a bigger output file shows its quiet time, not its last line ($.fs.read takes the whole file)
82const LIVE_AGENT = new Set(['pending', 'running', 'waiting'])
83let quota: QuotaWindow[] = [] // the rate-limit windows; a usage() that throws keeps the last ones
84let account: AccountView | null | undefined = undefined // undefined until .claude.json parsed once; a half-written read keeps the last value
85// the .claude.json the account was parsed from: its path, stat and when (Claude Code rewrites it often)
86let accountFile: { path: string; size: number; mtimeMs: number; parsedMs: number } | null = null
87const MAX_ACCOUNT_BYTES = 4 * 1024 * 1024 // $.fs.read's cap
88const ACCOUNT_REPARSE_MS = 30_000 // a changed .claude.json is parsed again at most this often after a good parse (it can be megabytes)
89let tr: T = T_EN // the active translator, set at the start of every tick (and read by the band / pane draws)
90let pressSeq = 0 // one number per ⓘ press, taken before any await; only the latest press may assign paneTab or end the chain
91let decided: Promise<PaneTab> | null = null // the tab the latest unfinished press chose: a press landing meanwhile steps on from it (N rapid presses = N tabs)
92let previous: { scope: string; counts: Counts | null; acceptance: string | null } | null = null
93const advisories: AdvisoryTracker = newTracker() // P7a: advisory rows seen for the current session; advisories.count feeds a band chip
94const jobDates = new Map<string, string>()
95// earliest bound progress receipt per root: receipts only accumulate, so a found start never moves earlier
96const receiptStarts = new Map<string, number>()
97
98async function readText($: EngineInterface, path: string): Promise<string | null> {
99 try {
100 const v = await $.fs.read(path)
101 return typeof v === 'string' ? v : null
102 } catch (_e) {
103 return null
104 }
105}
106
107async function readObject($: EngineInterface, path: string): Promise<Json | null> {
108 const text = await readText($, path)
109 if (text === null) return null
110 const parsed = parseJson(text)
111 return parsed.ok && isObject(parsed.value) ? parsed.value : null
112}
113
114function plain(state: LiveSnapshot['state'], text: string, over: Partial<LiveSnapshot> = {}): LiveSnapshot {
115 return {
116 state, text, band: null, header: text, pending: [], project_key: null, root_run_id: null, link: null, rows: null, gates: null,
117 sections: NO_SECTIONS, review: null, published_at: null, session_as_of: null, host_as_of: null, detail: NO_DETAIL, ...over,
118 }
119}
120
121// The marker's campaign roots, oldest -> newest: plain path segments only (a root names files), not the marker's own root, no repeats.
122function campaignRootsOf(marker: Json, markerRoot: string | null): string[] {
123 const raw = Array.isArray(marker.campaign_roots) ? marker.campaign_roots : []
124 const out: string[] = []
125 for (const r of raw) {
126 if (typeof r === 'string' && isPlainRoot(r) && r !== markerRoot && !out.includes(r)) out.push(r)
127 }
128 return out.slice(-MAX_CAMPAIGN_ROOTS)
129}
130
131// Which project / root does this session belong to? marker first (an unexpired one with a project_key), then the
132// longest path-boundary prefix of the real cwd among the watchers' runs/paths files. Never git, never a hash.
133type Scope = { key: string; root: string | null; marker: Json | null; campaign: string[] }
134
135async function resolveScope($: EngineInterface, autopilotHome: string, liveBase: string, sid: string, nowMs: number): Promise<Scope | null> {
136 if (sid) {
137 const marker = await readObject($, autopilotHome + '/session-mode/' + sid + '.json')
138 if (marker && isKey(marker.project_key) && typeof marker.expires_at === 'string' && Date.parse(marker.expires_at) > nowMs) {
139 const root = typeof marker.root_run_id === 'string' && marker.root_run_id ? marker.root_run_id : null
140 return { key: marker.project_key, root, marker, campaign: campaignRootsOf(marker, root) }
141 }
142 }
143 const cwd = await $.session.cwd()
144 let real = cwd
145 try {
146 const st = await $.fs.stat(cwd, { resolve: true })
147 if (typeof st.realPath === 'string' && st.realPath) real = st.realPath
148 } catch (_e) { /* keep the cwd spelling */ }
149 const dir = liveBase + '/runs/paths'
150 let names: string[] = []
151 try {
152 names = (await $.fs.list(dir)).filter(entry => entry.kind === 'file' && entry.name.endsWith('.json')).map(entry => entry.name).slice(0, MAX_PATH_FILES)
153 } catch (_e) { return null }
154 const maps: Json[] = []
155 for (const name of names) {
156 const map = await readObject($, dir + '/' + name)
157 if (map) maps.push(map)
158 }
159 const key = longestPrefixKey(real, maps)
160 return key === null ? null : { key, root: null, marker: null, campaign: [] }
161}
162
163// The envelope of one scope: the tmpfs file, then the SSD copy; a fresh one beats a stale one.
164async function findEnvelope($: EngineInterface, autopilotHome: string, liveBase: string, scope: Scope, nowMs: number): Promise<EnvelopeCheck> {
165 const scopeKey = scopeKeyOf(scope.key, scope.root)
166 const want = { project_key: scope.key, root_run_id: scope.root }
167 const paths = [liveBase + '/runs/' + scopeKey + '.json', autopilotHome + '/review/' + scope.key + '/live/runs.' + scopeKey + '.json']
168 let stale: EnvelopeCheck | null = null
169 let malformed = false
170 for (const path of paths) {
171 const check = checkEnvelope(await readText($, path), want, nowMs)
172 if (check.status === 'fresh') return check
173 if (check.status === 'stale' && stale === null) stale = check
174 if (check.status === 'malformed') malformed = true
175 }
176 if (stale !== null) return stale
177 return { status: malformed ? 'malformed' : 'missing', envelope: null }
178}
179
180// date directory of a job under <autopilot_home>/review/<key>/ — the earliest one that holds the job (the
181// watcher's renderer pins the earliest too); null until the job page has been published.
182async function findJobDate($: EngineInterface, autopilotHome: string, key: string, job: string): Promise<string | null> {
183 const base = autopilotHome + '/review/' + key
184 const cacheKey = key + '/' + job
185 const cached = jobDates.get(cacheKey)
186 if (cached) return cached
187 let dates: string[] = []
188 try {
189 dates = (await $.fs.list(base)).filter(entry => entry.kind === 'dir' && /^\d{4}-\d{2}-\d{2}$/.test(entry.name)).map(entry => entry.name).sort()
190 } catch (_e) { return null }
191 for (const date of dates) {
192 try {
193 if ((await $.fs.list(base + '/' + date)).some(entry => entry.name === job)) {
194 jobDates.set(cacheKey, date)
195 return date
196 }
197 } catch (_e) { /* not a readable date dir */ }
198 }
199 return null
200}
201
202// The earliest bound progress receipt of a campaign root (W3a elapsed). The root names a directory, so only a plain
203// segment is used; an unreadable / absent directory is "no receipt" and the earliest run start takes over.
204async function receiptStart($: EngineInterface, identity: unknown, root: string): Promise<number | null> {
205 const cached = receiptStarts.get(root)
206 if (cached !== undefined) return cached
207 const common = commonDirOf(identity)
208 if (common === null || !isPlainRoot(root)) return null
209 const dir = common + '/autopilot/work-orders/' + root
210 let names: string[] = []
211 try {
212 names = (await $.fs.list(dir)).filter(entry => entry.kind === 'file' && entry.name.endsWith('.json')).map(entry => entry.name).sort().slice(0, MAX_RECEIPT_FILES)
213 } catch (_e) { return null }
214 const texts: string[] = []
215 for (const name of names) {
216 const text = await readText($, dir + '/' + name)
217 if (text !== null) texts.push(text)
218 }
219 const ms = earliestReceiptMs(texts, root)
220 if (ms !== null) receiptStarts.set(root, ms)
221 return ms
222}
223
224// The cost fuse's mode as hooks/cost-fuse.js resolves it: AUTOPILOT_COST_FUSE_MODE, else ~/.autopilot/config.json cost_fuse.mode, else warn.
225// (env first, then config: the same result as hooks/cost-fuse.js, which loads the config and then applies the env override)
226async function fuseModeOf($: EngineInterface, autopilotHome: string): Promise<string> {
227 try {
228 const env = await $.env.get('AUTOPILOT_COST_FUSE_MODE')
229 if (env === 'block' || env === 'warn' || env === 'off') return env
230 } catch (_e) { /* no env */ }
231 const cfg = await readObject($, autopilotHome + '/config.json')
232 const cf = cfg !== null && isObject(cfg.cost_fuse) ? cfg.cost_fuse : null
233 return cf !== null && (cf.mode === 'block' || cf.mode === 'warn' || cf.mode === 'off') ? cf.mode : 'warn'
234}
235
236// No watcher scope for this cwd (a repo that was never onboarded): the residue reminder still has to reach the person, so read
237// `reap --auto`'s own result straight from the repo. The mod cannot run git, so it walks up from the cwd to the FIRST `.git`: a
238// directory holds the file directly, a `.git` file (linked worktree / submodule) leads to the common dir via `commondir`. Absent / foreign = 0.
239const MAX_GIT_WALK = 16
240async function orphanResidueCount($: EngineInterface): Promise<number> {
241 try {
242 let dir = await $.session.cwd()
243 for (let i = 0; i < MAX_GIT_WALK && dir !== ''; i++) {
244 // the FIRST `.git` met is the repo: a directory (it holds HEAD) or a gitfile. If its result file cannot be resolved or read the answer
245 // is 0; a parent repo's file is never borrowed.
246 if (await readText($, dir + '/.git/HEAD') !== null) return autoResidueCount(await readText($, dir + '/.git/autopilot-residue-auto.json'))
247 const gitText = await readText($, dir + '/.git')
248 if (gitText !== null) { // a `.git` file exists: it is the repo, even when it is empty or unparseable
249 const gitdir = gitdirOfGitFile(gitText, dir)
250 if (gitdir === null) return 0
251 const common = commonDirOfGitdir(gitdir, await readText($, gitdir + '/commondir'))
252 return autoResidueCount(await readText($, common + '/autopilot-residue-auto.json'))
253 }
254 const cut = dir.lastIndexOf('/')
255 if (cut <= 0) break
256 dir = dir.slice(0, cut)
257 }
258 } catch (_e) { /* no cwd / unreadable: no reminder */ }
259 return 0
260}
261
262// Claude Code's own language setting: the `/config` row named `language` when the engine lists one, else `language` in the user's settings.json.
263// The row exists (verified on Claude Code 2.1.296: a `text` row, e.g. "正體中文台灣用語"); the file fallback covers an engine that lacks it; any failure is "no setting".
264async function claudeLanguage($: EngineInterface, home: string | undefined): Promise<string | null> {
265 try {
266 const row = (await $.config.list()).find(r => r.key === 'language')
267 if (row !== undefined && typeof row.value === 'string' && row.value.trim() !== '') return row.value
268 } catch (_e) { /* no such row / the engine cannot list */ }
269 if (!home) return null
270 const settings = await readObject($, home + '/.claude/settings.json')
271 return settings !== null && typeof settings.language === 'string' && settings.language.trim() !== '' ? settings.language : null
272}
273
274async function resolveT($: EngineInterface): Promise<T> {
275 let home: string | undefined
276 try { home = await $.env.get('HOME') } catch (_e) { home = undefined }
277 const cfg = home ? await readObject($, home + '/.autopilot/config.json') : null
278 const ui = cfg !== null && isObject(cfg.ui) ? cfg.ui : null
279 const envLocale = await $.env.get('AUTOPILOT_LOCALE').catch(() => undefined)
280 const lang = (await $.env.get('LC_ALL').catch(() => undefined)) || (await $.env.get('LANG').catch(() => undefined))
281 const needLanguage = !(ui !== null && (ui.locale === 'en' || ui.locale === 'zh-TW')) && envLocale !== 'en' && envLocale !== 'zh-TW'
282 const language = needLanguage ? await claudeLanguage($, home) : null
283 return makeT(resolveLocale({ config: ui === null ? undefined : ui.locale, env: envLocale, language, lang }))
284}
285
286async function buildSnapshot($: EngineInterface, nowMs: number, t: T): Promise<{ snap: LiveSnapshot; counts: Counts | null; acceptance: string | null }> {
287 const none = (snap: LiveSnapshot) => ({ snap, counts: null, acceptance: null })
288 const STATE_TEXT = stateText(t)
289 const home = await $.env.get('HOME')
290 if (!home) return none(plain('no-pointer', STATE_TEXT.noPointer))
291 const pointerText = await readText($, home + '/.autopilot/live-pointer.json')
292 if (pointerText === null) return none(plain('no-pointer', STATE_TEXT.noPointer))
293 const parsed = parseJson(pointerText)
294 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== POINTER_SCHEMA || typeof parsed.value.live_base !== 'string' || !parsed.value.live_base) {
295 return none(plain('unreadable', STATE_TEXT.unreadable))
296 }
297 const liveBase = parsed.value.live_base.replace(/\/+$/, '')
298 const autopilotHome = typeof parsed.value.autopilot_home === 'string' && parsed.value.autopilot_home ? parsed.value.autopilot_home.replace(/\/+$/, '') : home + '/.autopilot'
299
300 const sid = await $.session.id()
301 const scope = await resolveScope($, autopilotHome, liveBase, sid, nowMs)
302 if (scope === null) {
303 const wt = await orphanResidueCount($)
304 return none(plain('no-project', wt > 0 ? STATE_TEXT.noProjectWt(wt) : STATE_TEXT.noProject))
305 }
306
307 // The root set: the marker root first, then the campaign roots (oldest -> newest). Each root is read like the marker root alone
308 // used to be; a root whose envelope is missing / stale / malformed is left out and never hides the others.
309 const primaryFind = { scope, found: await findEnvelope($, autopilotHome, liveBase, scope, nowMs) }
310 const finds: { scope: Scope; found: EnvelopeCheck }[] = [primaryFind]
311 for (const root of scope.campaign) {
312 const member: Scope = { key: scope.key, root, marker: null, campaign: [] }
313 finds.push({ scope: member, found: await findEnvelope($, autopilotHome, liveBase, member, nowMs) })
314 }
315 const fresh = finds.filter(f => f.found.status === 'fresh')
316 // the base envelope: the marker root's when fresh, else the first fresh campaign root's; with none fresh, the marker root's (stale /
317 // unavailable / unreadable exactly as before), else the first member that has any envelope
318 const baseFind = fresh[0] ?? (primaryFind.found.envelope !== null ? primaryFind : (finds.find(f => f.found.envelope !== null) ?? primaryFind))
319 const found = baseFind.found
320 const keyed = { project_key: scope.key, root_run_id: scope.root }
321 if (found.envelope === null) {
322 const malformed = finds.some(f => f.found.status === 'malformed')
323 return none(malformed ? plain('unreadable', STATE_TEXT.unreadable, keyed) : plain('unavailable', STATE_TEXT.unavailable(scope.key), keyed))
324 }
325 const published = typeof found.envelope.published_at === 'string' ? found.envelope.published_at : null
326
327 // pane data: the job page's model.json of each fresh root when it exists (acceptance axis, gate rows, progress, phase), a Link either way
328 const jobModelOf = async (root: string | null, env: Json): Promise<{ date: string | null; job: string; model: JobModel | null }> => {
329 const jobName = jobOf(env, root)
330 const jobDate = await findJobDate($, autopilotHome, scope.key, jobName)
331 let m: JobModel | null = null
332 if (jobDate !== null) {
333 m = readJobModel(await readText($, autopilotHome + '/review/' + scope.key + '/' + jobDate + '/' + jobName + '/current/model.json'))
334 if (m === null) jobDates.delete(scope.key + '/' + jobName)
335 }
336 return { date: jobDate, job: jobName, model: m }
337 }
338 const baseJob = await jobModelOf(baseFind.scope.root, found.envelope)
339 const primaryFresh = primaryFind.found.status === 'fresh'
340 // the marker root's own job model, kept apart: the sources-manifest fallback and the review Link belong to the marker root
341 const primaryJob = baseFind.scope === scope ? baseJob : null
342 const campaignJobs: JobModel[] = []
343 for (const f of fresh) {
344 if (f.scope === scope) continue
345 const cj = f.scope === baseFind.scope ? baseJob : await jobModelOf(f.scope.root, f.found.envelope as Json)
346 if (cj.model !== null) campaignJobs.push(cj.model)
347 }
348 const jobModel: JobModel | null = fresh.length > 0
349 ? mergeJobModels(primaryFresh && primaryJob !== null ? primaryJob.model : null, campaignJobs)
350 : baseJob.model
351 const env: Json = fresh.length > 0
352 ? mergeEnvelopes(found.envelope, fresh.filter(f => f !== baseFind).map(f => f.found.envelope as Json))
353 : found.envelope
354 const port = portOf(await readText($, liveBase + '/review/server.json'))
355 const common = {
356 ...keyed,
357 link: reviewLink(port, scope.key, baseJob.date, baseJob.job),
358 rows: paneRows(env, nowMs),
359 gates: jobModel === null ? null : jobModel.gates,
360 published_at: published,
361 session_as_of: sessionUsd(env, sid).as_of,
362 host_as_of: typeof env.host_today_as_of === 'string' ? env.host_today_as_of : null,
363 }
364 if (fresh.length === 0) {
365 const at = published !== null && Number.isFinite(Date.parse(published)) ? hhmm(Date.parse(published)) : null
366 return { snap: plain('stale', STATE_TEXT.stale(scope.key, at), common), counts: null, acceptance: null }
367 }
368 // W3a sources. The per-session files are named by the sanitised sid; every sidecar is read for THIS scope only.
369 const fileSid = sanitizeSid(sid)
370 const want = { project_key: scope.key, root_run_id: scope.root }
371 const scopeKey = scopeKeyOf(scope.key, scope.root)
372 const manifestText = await readText($, liveBase + '/runs/sources/' + scopeKey + '.json')
373 const manifestParsed = manifestText === null ? null : parseJson(manifestText)
374 const manifest: Manifest | null = (manifestParsed !== null && manifestParsed.ok ? readManifest(manifestParsed.value, want) : null)
375 || (primaryJob === null || primaryJob.model === null ? null : readManifest(primaryJob.model.sources_manifest, want))
376 const tasks = readTasks(await readText($, liveBase + '/tasks/' + fileSid + '.json'), sid)
377 const attention = readAttention(await readText($, liveBase + '/attention/' + fileSid + '.json'), sid)
378 const turn = readTurn(await readText($, liveBase + '/turn/' + fileSid + '.json'), sid, nowMs, await readText($, liveBase + '/turn-effective/' + fileSid + '.json'))
379 // decisions: the proxy decisions of every fresh root of the set, summed; the foreman sidecar of the marker root (it is bound by session)
380 const decisionViews: DecisionsView[] = []
381 for (const f of fresh) {
382 const ds = f.scope.root === null ? scopeKey : scopeKeyOf(scope.key, f.scope.root)
383 const view = readDecisions(await readText($, liveBase + '/runs/' + ds + '.decisions.json'), { project_key: scope.key, root_run_id: f.scope.root })
384 if (view !== null) decisionViews.push(view)
385 }
386 const decisions = mergeDecisions(decisionViews)
387 const foreman = readForeman(await readText($, liveBase + '/runs/' + scopeKey + '.foreman.json'), want)
388 const loadSource = readLoadSource(await readText($, liveBase + '/load-source.json'))
389 const identity = isObject(env.scope) ? env.scope.repo_identity : null
390 // elapsed: the newest campaign root's bound receipt, else the marker root's
391 let receiptMs: number | null = null
392 let receiptRoot: string | null = null
393 for (const r of [...scope.campaign].reverse().concat(scope.root === null ? [] : [scope.root])) {
394 receiptMs = await receiptStart($, identity, r)
395 if (receiptMs !== null) { receiptRoot = r; break }
396 }
397 // P7: the stage-graph facts. Each is optional; an absent / foreign file reads as null and its slot / tab says "no data".
398 const marker = readMarker(scope.marker)
399 const qc = readQc(await readText($, liveBase + '/runs/' + scope.key + '.qc.json'), { project_key: scope.key, root_run_id: null })
400 const residue = readResidue(await readText($, liveBase + '/runs/' + scope.key + '.residue.json'), scope.key)
401 const stage = readStageWalk(await readText($, liveBase + '/stage/' + fileSid + '.json'), sid)
402 const review = readReview(await readText($, liveBase + '/runs/' + scope.key + '.review.json'), scope.key)
403 const src: Sources = { tasks, attention, turn, decisions, manifest, foreman, loadSource, marker, review, qc, residue, stage, quota, startMs: startMsOf(receiptRoot, env, tasks, scope.marker === null ? null : scope.marker.started_at, receiptMs) }
404 const ctx = ctxShown(ctxText(await readText($, liveBase + '/context/' + fileSid + '.json'), nowMs), manifest, t)
405 const band = bandView(env, jobModel, scope.key, nowMs, src, t)
406 return {
407 snap: plain('ok', bandLine1(band) + (band.reason === null ? '' : '\n' + band.reason), {
408 ...common, band, header: headerText(env, sid, ctx, t), metrics: { ctx }, pending: jobModel === null || !jobModel.needs_decision ? [] : jobModel.decisions,
409 sections: buildSections(src, foreman),
410 review,
411 detail: {
412 counts: countsOf(env), stalled: stalledCount(env, foreman, nowMs),
413 now_ms: nowMs, project: projectNameOf(identity, scope.key), marker, qc, stage, decisions, load_source: loadSource, residue,
414 spend: { session: sessionUsd(env, sid).text, host_all: usd(env.host_today_usd), host_all_n: typeof env.host_today_usd === 'number' && Number.isFinite(env.host_today_usd) ? env.host_today_usd : null, brain: spendOf(env)?.brain ?? null, cap: spendOf(env)?.cap ?? null, mode: await fuseModeOf($, autopilotHome), hourly: hourlySpend(readSpendHistory(await readText($, liveBase + '/runs/spend-history.json')), nowMs) },
415 },
416 }),
417 counts: countsOf(env),
418 acceptance: jobModel === null ? null : jobModel.acceptance,
419 }
420}
421
422// P7a advisory bridge: the rows the hooks appended to <live_base>/advisories/<sid>.jsonl, each new one a toast.
423async function pollAdvisories($: EngineInterface, nowMs: number): Promise<void> {
424 try {
425 const home = await $.env.get('HOME')
426 if (!home) return
427 const pointer = await readObject($, home + '/.autopilot/live-pointer.json')
428 if (pointer === null || pointer.schema !== POINTER_SCHEMA || typeof pointer.live_base !== 'string' || !pointer.live_base) return
429 const sid = await $.session.id()
430 if (!sid) return
431 const text = await readText($, pointer.live_base.replace(/\/+$/, '') + '/advisories/' + sanitizeSid(sid) + '.jsonl')
432 for (const row of takeNew(advisories, sid, parseAdvisories(text), nowMs)) $.ui.toast(row.text)
433 } catch (_e) {
434 // the bridge never takes the session down
435 }
436}
437
438// The background-work rows: the shells and watches scanned from the messages, each shell with its output file's last line and quiet time, then the
439// running subagents. Each source fails on its own: an unread transcript keeps the previous shell and watch rows; null = neither answered (the caller
440// keeps the previous rows). Only the rows the pane shows read their output file.
441async function readActivity($: EngineInterface, msgs: unknown, nowMs: number, prev: readonly ActivityItem[] | null): Promise<ActivityItem[] | null> {
442 const items: ActivityItem[] = []
443 let answered = false
444 if (!Array.isArray(msgs)) items.push(...(prev ?? []).filter(it => it.kind !== 'agent').map(it => ({ ...it, quietMs: null }))) // the age would freeze
445 else {
446 answered = true
447 const seen = new Set<string>()
448 for (const task of scanBackground(msgs as never)) {
449 let tail = task.lastEvent
450 let quietMs: number | null = null
451 if (task.output !== null) {
452 seen.add(task.output)
453 try {
454 const st = await $.fs.stat(task.output)
455 if (st.kind === 'file') {
456 quietMs = Math.max(0, nowMs - st.mtimeMs)
457 const hit = tails.get(task.output)
458 if (hit !== undefined && hit.size === st.size && hit.mtimeMs === st.mtimeMs) tail = hit.tail
459 else {
460 const text = st.size <= MAX_TAIL_BYTES ? await readText($, task.output) : null
461 tail = text === null ? null : lastOutputLine(text)
462 tails.set(task.output, { size: st.size, mtimeMs: st.mtimeMs, tail })
463 }
464 }
465 } catch (_e) { /* no output file yet: the row shows without a tail */ }
466 }
467 items.push({ kind: task.kind, label: task.label, detail: null, tail, quietMs, output: task.output })
468 }
469 for (const path of [...tails.keys()]) if (!seen.has(path)) tails.delete(path)
470 }
471 try {
472 const agents = await $.agent.list()
473 if (Array.isArray(agents)) {
474 answered = true
475 for (const a of agents) if (LIVE_AGENT.has(a.status)) items.push({ kind: 'agent', label: bgLabel(a.description || a.type), detail: a.description ? bgLabel(a.type) : null, tail: null, quietMs: null })
476 }
477 } catch (_e) { /* no agent list: the shells still show */ }
478 return answered ? items : null
479}
480
481// The account and its rate-limit windows. Each source fails on its own and keeps its last value.
482async function readAccountQuota($: EngineInterface, nowMs: number): Promise<void> {
483 try {
484 const usage = await $.session.usage()
485 quota = readQuota(isObject(usage) ? usage.rateLimits : null)
486 } catch (_e) { /* no reading: keep the last windows */ }
487 try {
488 // Claude Code keeps it in CLAUDE_CONFIG_DIR when that is set, else in HOME (checked against the real tool)
489 const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) || (await $.env.get('HOME'))
490 if (!dir) return
491 const path = dir.replace(/\/+$/, '') + '/.claude.json'
492 const clear = () => { account = undefined; accountFile = null } // no stale account, and a file back is read at once
493 if (accountFile !== null && accountFile.path !== path) clear() // another directory: the account shown came from the old one
494 const st = await $.fs.stat(path).catch(() => null)
495 if (st === null) {
496 // the rejection carries only a message across the engine boundary (no `code`): ask whether the file is there instead.
497 // Gone: clear. Still there (a permission or passing I/O error): keep the last account.
498 if (!(await $.fs.exists(path).catch(() => true))) clear()
499 return
500 }
501 if (st.kind !== 'file' || st.size > MAX_ACCOUNT_BYTES) { clear(); return }
502 const prev = accountFile // the same path here: another directory cleared it above, so it is read at once
503 if (prev !== null && prev.size === st.size && prev.mtimeMs === st.mtimeMs) return
504 if (prev !== null && nowMs - prev.parsedMs < ACCOUNT_REPARSE_MS) return // changed again soon after a good parse: wait
505 const next = readAccount(await readText($, path))
506 if (next === undefined) return // unreadable or caught mid-rewrite: try again next tick
507 account = next
508 accountFile = { path, size: st.size, mtimeMs: st.mtimeMs, parsedMs: nowMs }
509 } catch (_e) { /* a failed read: keep the last account */ }
510}
511
512async function refresh($: EngineInterface): Promise<void> {
513 try {
514 const nowMs = await $.clock.now()
515 tr = await resolveT($)
516 await pollAdvisories($, nowMs)
517 await readAccountQuota($, nowMs)
518 const built = await buildSnapshot($, nowMs, tr)
519 let msgs: unknown = null
520 let sid: string | null = null
521 let sidOk = false
522 try {
523 const rawSid = await $.session.id()
524 // unread only for the kept-row decision below: a null id still reads the transcript and updates recent
525 sid = rawSid ?? null
526 sidOk = rawSid !== null && rawSid !== undefined
527 msgs = await $.session.messages()
528 if (recentSid !== null && sid !== recentSid) expanded.clear()
529 recentSid = sid
530 if (Array.isArray(msgs)) recent = recentTracker.update(sid ?? '', msgs as never)
531 } catch (_e) {
532 // the transcript is optional garnish: keep the previous value. `sid` stays set when only messages() threw.
533 }
534 // kept shell and watch rows carry no session id. Drop them when the id was read, the transcript is not an array,
535 // and the id is not the one those rows belong to (/clear or resume while messages() keeps failing). An unread id keeps them.
536 if (sidOk && !Array.isArray(msgs) && sid !== activitySid) {
537 activity = null
538 activitySid = sid
539 }
540 try {
541 const next = await readActivity($, msgs, nowMs, activity)
542 if (next !== null) {
543 activity = next
544 if (Array.isArray(msgs) && sidOk) activitySid = sid // the rows just built belong to this session
545 }
546 } catch (_e) {
547 // garnish too: keep the previous rows
548 }
549 snapshot = { ...built.snap, recent, activity, account: { account, quota } }
550 await pruneDecide($, new Set(built.snap.pending.flatMap(d => (d.id === null ? [] : [d.id]))), built.snap.state === 'ok', nowMs).catch(() => undefined)
551 $.ui.invalidate('ui.render')
552 // toasts: only between two fresh snapshots of the same scope
553 if (built.snap.state === 'ok') {
554 const scope = (built.snap.project_key || '') + '/' + (built.snap.root_run_id || '')
555 if (previous !== null && previous.scope === scope) {
556 const texts: string[] = []
557 if (previous.counts !== null && built.counts !== null) {
558 const t = executionToast(previous.counts, built.counts, tr)
559 if (t !== null) texts.push(t)
560 }
561 if (previous.acceptance !== null && built.acceptance !== null) {
562 const t = acceptanceToast(previous.acceptance, built.acceptance, tr)
563 if (t !== null) texts.push(t)
564 }
565 for (const text of texts) $.ui.toast(text)
566 }
567 previous = { scope, counts: built.counts, acceptance: built.acceptance }
568 }
569 // pane: asked for once, and only where it would be a sidebar (fullscreen, >= 144 columns)
570 if (!paneAttempted && built.snap.project_key !== null && viewport !== null && viewport.isFullscreen === true && viewport.columns >= PANE_MIN_COLUMNS) {
571 paneAttempted = true
572 await $.ui.open({ id: PANE_ID, title: 'Autopilot' })
573 }
574 } catch (_e) {
575 // a bad tick must never take the session down; the next tick tries again
576 }
577}
578
579// A press on the 待決 tab: `pick:<id>:<k>` chooses option k of question id (pressing the chosen one again unchooses it), `submit` sends every answered question.
580async function decidePress($: EngineInterface, id: string): Promise<void> {
581 // a pressed file path (ui.ts linkSegs, the background tail): the viewer window has to open in THIS turn, before any await (mods/viewer/show.ts openWindow)
582 if (id.startsWith(SHOW_PRESS)) {
583 const at = showTarget(id)
584 if (at !== null) await showPath($, at.path, at.line).catch(() => undefined)
585 return
586 }
587 try {
588 const m = /^pick:(.+):(\d+)$/.exec(id)
589 if (m !== null) {
590 const k = Number(m[2])
591 await update($, DECIDE, s => {
592 const picks = { ...s.picks }
593 if (picks[m[1]] === k) delete picks[m[1]]
594 else picks[m[1]] = k
595 return { ...s, picks }
596 })
597 } else if (id === 'submit') await sendDecide($)
598 else if (id.startsWith('clean:')) await cleanPress($, id)
599 } catch (_e) {
600 // a press never takes the session down
601 }
602}
603
604// A press on a 殘留 cleanup button (`clean:all` or `clean:<path>`). The button never builds a delete of its own: it runs one of TWO fixed scripts, by argument vector (`$.process.run`,
605// no shell, so no quoting), each of which classifies again at that moment: `repo-residue-sweep.js reap --yes --worktree <path>` (clean + integrated, or directory gone; a live,
606// dirty or unintegrated worktree is never touched) and `prune-plugin-cache.js --version <v>` (a plain version directory, no live pid, not the loaded copy). The arguments come only
607// from the CURRENT clearable lists of the snapshot, so a stale or forged id runs nothing. Owner ruling 2026-10-16 (d-7a7ee75c): no confirmation dialog.
608export const CLEAN_SCRIPTS = ['scripts/repo-residue-sweep.js', 'scripts/prune-plugin-cache.js'] as const
609type CleanRun = (argv: string[]) => Promise<{ exitCode: number; stdout: string }>
610let cleaning = false
611// the common git dir of the checkout a path belongs to: the first `.git` met walking up (a directory holds HEAD, a gitfile names the gitdir); null when there is none (a directory that is gone)
612async function commonDirAt($: EngineInterface, start: string): Promise<string | null> {
613 let dir = start
614 for (let i = 0; i < MAX_GIT_WALK && dir !== ''; i++) {
615 if (await readText($, dir + '/.git/HEAD') !== null) return normalizeAbs(dir + '/.git')
616 const gitText = await readText($, dir + '/.git')
617 if (gitText !== null) {
618 const gitdir = gitdirOfGitFile(gitText, dir)
619 return gitdir === null ? null : commonDirOfGitdir(gitdir, await readText($, gitdir + '/commondir'))
620 }
621 const cut = dir.lastIndexOf('/')
622 if (cut <= 0) break
623 dir = dir.slice(0, cut)
624 }
625 return null
626}
627type CleanNote = { ok: boolean; note: string }
628export async function cleanPress($: EngineInterface, id: string, run?: CleanRun): Promise<void> {
629 if (cleaning || snapshot === null) return
630 // the only place `$.process` is used: argv is node + a whitelisted script (ui-lint.test.js pins this)
631 const exec = async (script: (typeof CLEAN_SCRIPTS)[number], args: string[]): Promise<string> => {
632 if (!CLEAN_SCRIPTS.includes(script)) throw new Error('script not allowed')
633 const argv = ['node', $.plugin.root + '/' + script, ...args]
634 const r = run === undefined ? await $.process.run(argv, { timeoutMs: 120_000 }) : await run(argv)
635 return r.stdout
636 }
637 // the same list the 全部清掉 count is drawn from (model.ts cleanTargets): what is clearable now and was not already reported on
638 const left = cleanTargets(snapshot.detail, (await read($, DECIDE)).clean ?? {})
639 const asked = id === 'clean:all' ? left.worktrees.map(e => e.target) : left.worktrees.map(e => e.target).filter(x => 'clean:' + x === id)
640 const askedCaches = id === 'clean:all' ? left.caches : left.caches.filter(x => 'clean:' + x === id)
641 if (asked.length === 0 && askedCaches.length === 0) return
642 cleaning = true
643 try {
644 const results: Record<string, CleanNote> = {}
645 for (const dir of askedCaches) {
646 const parts = dir.split('/').filter(x => x !== '')
647 const version = parts[parts.length - 1]
648 const claudeDir = '/' + parts.slice(0, -5).join('/') // <claude-dir>/plugins/cache/autopilot/autopilot/<version>
649 if (!(await $.fs.exists($.plugin.root + '/' + CLEAN_SCRIPTS[1]).catch(() => false))) { results[dir] = { ok: false, note: 'cleanup script not found' }; continue }
650 try {
651 const out = await exec(CLEAN_SCRIPTS[1], ['--version', version, '--claude-dir', claudeDir])
652 const rep = parseJson(out.split('\n').reverse().find(l => l.startsWith('{')) ?? '')
653 results[dir] = rep.ok && isObject(rep.value) && rep.value.ok === true ? { ok: true, note: '' } : { ok: false, note: rep.ok && isObject(rep.value) && typeof rep.value.reason === 'string' ? rep.value.reason : 'no report from the cleanup script' }
654 } catch (e) {
655 results[dir] = { ok: false, note: e instanceof Error ? e.message.split('\n')[0].slice(0, 120) : 'cleanup failed' } // a refusal exits 1 with its JSON reason on stdout (read above); this is a failure to start
656 }
657 }
658 if (asked.length > 0) await cleanWorktrees($, asked, exec, results)
659 await update($, DECIDE, s => ({ ...s, clean: { ...(s.clean ?? {}), ...results } }))
660 } finally {
661 cleaning = false
662 }
663}
664// The worktrees of one press. Each runs under the repository it belongs to (its own checkout's common dir, never just the session's cwd), and only when that is the session's repository.
665// A target counts as cleared only when its directory is really gone afterwards, whatever the report says.
666async function cleanWorktrees($: EngineInterface, asked: string[], exec: (script: (typeof CLEAN_SCRIPTS)[number], args: string[]) => Promise<string>, results: Record<string, CleanNote>): Promise<void> {
667 if (!(await $.fs.exists($.plugin.root + '/' + CLEAN_SCRIPTS[0]).catch(() => false))) { for (const x of asked) results[x] = { ok: false, note: 'cleanup script not found' }; return }
668 const cwd = await $.session.cwd()
669 const mine = await commonDirAt($, cwd)
670 const byRepo = new Map<string, string[]>()
671 for (const x of asked) {
672 const own = await commonDirAt($, x) // null: the directory is gone, nothing to compare; the sweep only knows worktrees of the repo it is given
673 if (own !== null && mine !== null && own !== mine) { results[x] = { ok: false, note: 'this worktree belongs to another repository' }; continue }
674 const common = own ?? mine
675 const repo = common !== null && common.endsWith('/.git') ? common.slice(0, -'/.git'.length) : cwd
676 byRepo.set(repo, [...(byRepo.get(repo) ?? []), x])
677 }
678 for (const [repo, targets] of byRepo) {
679 const kept = new Map<string, string>()
680 let failure = ''
681 try {
682 const out = await exec(CLEAN_SCRIPTS[0], ['reap', '--repo', repo, '--yes', '--json', ...targets.flatMap(x => ['--worktree', x])])
683 const line = out.split('\n').reverse().find(l => l.startsWith('{'))
684 const report = line === undefined ? null : parseJson(line)
685 const acts = report !== null && report.ok && isObject(report.value) && isObject(report.value.actions) ? report.value.actions : null
686 if (acts === null) failure = 'no report from the cleanup script'
687 else if (Array.isArray(acts.worktrees_kept)) for (const w of acts.worktrees_kept) if (isObject(w) && typeof w.path === 'string') kept.set(normalizeAbs(w.path), typeof w.why === 'string' ? w.why : 'kept')
688 } catch (e) {
689 failure = e instanceof Error ? e.message.split('\n')[0].slice(0, 120) : 'cleanup failed'
690 }
691 for (const x of targets) {
692 const gone = !(await $.fs.exists(x).catch(() => true))
693 results[x] = gone ? { ok: true, note: '' } : { ok: false, note: failure !== '' ? failure : kept.get(normalizeAbs(x)) ?? 'the cleanup script did not handle this path' }
694 }
695 }
696}
697
698// One prompt carries every answered question that was not sent yet. The questions are marked sent BEFORE the prompt goes, so a second press cannot send them twice;
699// a prompt the session refuses takes the marks back. The prompt starts a turn once the session is idle: it is not awaited here.
700// The guard is a module flag taken before the first await: two presses landing together (a double click) both run this function before either has written its marks.
701let sending = false
702async function sendDecide($: EngineInterface): Promise<void> {
703 if (sending) return
704 sending = true
705 try {
706 const reply = decideReply(snapshot === null ? [] : snapshot.pending, await read($, DECIDE))
707 if (reply === null) return
708 const at = await $.clock.now()
709 await update($, DECIDE, s => ({ ...s, sent: { ...s.sent, ...Object.fromEntries(reply.ids.map(i => [i, at])) } }))
710 $.prompt.submit({ text: reply.text }).catch(async () => {
711 await update($, DECIDE, s => { const sent = { ...s.sent }; for (const i of reply.ids) delete sent[i]; return { ...s, sent } })
712 })
713 } finally {
714 sending = false
715 }
716}
717
718// An edit of a note field (`note:<id>`).
719async function decideNote($: EngineInterface, key: string, value: string): Promise<void> {
720 if (!key.startsWith('note:')) return
721 const id = key.slice(5)
722 try {
723 await update($, DECIDE, s => ({ ...s, notes: { ...s.notes, [id]: value } }))
724 } catch (_e) {
725 // keep the last text
726 }
727}
728
729// Forget the picks and notes of questions that left the list, and sent marks a day old. Writes only when something is dropped (a write redraws the pane).
730async function pruneDecide($: EngineInterface, listed: ReadonlySet<string>, ok: boolean, nowMs: number): Promise<void> {
731 const st: DecideState = await read($, DECIDE)
732 const gone = (id: string): boolean => !listed.has(id) && (st.sent[id] !== undefined ? nowMs - st.sent[id] > DECIDE_KEEP_MS : ok)
733 const ids = new Set([...Object.keys(st.picks), ...Object.keys(st.notes), ...Object.keys(st.sent)])
734 const drop = [...ids].filter(gone)
735 if (drop.length === 0) return
736 const keep = <V,>(o: Record<string, V>): Record<string, V> => Object.fromEntries(Object.entries(o).filter(([id]) => !drop.includes(id)))
737 await update($, DECIDE, s => ({ ...s, picks: keep(s.picks), notes: keep(s.notes), sent: keep(s.sent) }))
738}
739
740const nextTab = (t: PaneTab): PaneTab => PANE_TABS[(PANE_TABS.indexOf(t) + 1) % PANE_TABS.length]
741
742// After a press on a tab Button (a click, or Tab / arrows + Enter) the keyboard ring returns to the `›` chip, so the next Enter steps on instead of
743// re-pressing the tab that was just chosen. Best effort: a pane that does not hold the keys refuses, and the tab has switched anyway.
744async function ringToNext($: EngineInterface): Promise<void> {
745 try {
746 await $.ui.focus({ requestId: PANE_ID, key: 'next' })
747 } catch (_e) {
748 // not holding the keyboard: nothing to move
749 }
750}
751
752// the live mod's session start. A function of its own because Claude Code refuses a second matcher-less `session.start` hook in one plugin: the composed module
753// (mods/register.ts) registers the one hook and calls this and the viewer's start; the live mod's own tests use `register` below, which hooks it alone.
754export async function startLive($: EngineInterface): Promise<void> {
755 paneTab = 'now'
756 folded.clear() // a new Claude Code session opens every section
757 pressSeq += 1 // presses still in flight become stale: they assign nothing and leave the chain alone
758 decided = null
759 if (timer === undefined) timer = $.clock.every(TICK_MS, () => refresh($))
760 await refresh($)
761}
762
763// every hook of the live mod except `session.start`
764export function registerLive(on: Parameters<Register>[0]): void {
765 // /clear ends the session but no session.start follows and the timer survives it (S7): only a real exit stops it.
766 on('session.end', async ($, e, next) => {
767 if (e.reason !== 'clear' && timer !== undefined) {
768 timer.cancel()
769 timer = undefined
770 }
771 return next(e)
772 })
773
774 on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
775 viewport = e.viewport ? { columns: e.viewport.columns, isFullscreen: e.viewport.isFullscreen } : null
776 if (e.props.hasSurvey) return next(e)
777 // the ⓘ opens the panel on the Now tab; pressed again while the panel is open it shows the next tab (7 tabs, the ? legend last, then Now again) (the pane never gets the keyboard
778 // while the person holds the ⓘ, so this is the keyboard way to change tab). "Open" is the engine's own record, $.ui.panes() (the pane
779 // is listed until it closes, however it was opened). No hotkey: the band's autoFocus puts the keyboard path at Ctrl+x Tab, Enter.
780 const info = async () => {
781 const seq = ++pressSeq
782 const prev = decided
783 const nextOf = nextTab
784 const mine: Promise<PaneTab> = (async () => {
785 if (prev !== null) return nextOf(await prev) // an earlier press is still deciding / opening: $.ui.panes() may not list the pane yet
786 let isOpen = false
787 try {
788 isOpen = (await $.ui.panes()).some(p => p.id === PANE_ID)
789 } catch (_e) {
790 // the engine could not list panes: treat the pane as closed (Now)
791 }
792 return isOpen ? nextOf(paneTab) : 'now'
793 })()
794 decided = mine
795 try {
796 const tab = await mine
797 if (seq === pressSeq) paneTab = tab
798 $.ui.invalidate('ui.render')
799 await $.ui.open({ id: PANE_ID, title: 'Autopilot', focus: true, closeOnEscape: true })
800 } finally {
801 if (seq === pressSeq) decided = null
802 }
803 }
804 // a slot pressed opens the pane on the tab that explains it (model.ts slotTab). It is a press like the ⓘ's: it takes a sequence number, so an
805 // ⓘ press still in flight becomes stale and cannot drag the tab back, and it records its tab as `decided` while its open is in flight, so an
806 // ⓘ landing meanwhile steps on from the slot's tab instead of reading a pane $.ui.panes() does not list yet.
807 const slot = async (id: SlotId) => {
808 const seq = ++pressSeq
809 const tab = slotTab(id)
810 decided = Promise.resolve(tab)
811 paneTab = tab
812 const unfold = slotUnfolds(id)
813 if (unfold !== null) folded.delete(unfold)
814 try {
815 $.ui.invalidate('ui.render')
816 await $.ui.open({ id: PANE_ID, title: 'Autopilot', focus: true, closeOnEscape: true })
817 } finally {
818 if (seq === pressSeq) decided = null
819 }
820 }
821 return Band($.ui.resolve(e), snapshot, e.props.bodyColumns, info, tr, slot)
822 })
823
824 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => (hostScrollHome($, e.props.scroll, paneTab), decideScroll.redraw = () => { void $.ui.invalidate('ui.render') }, Pane($.ui.resolve(e), snapshot, paneTab, (t: PaneTab) => { paneTab = t; $.ui.invalidate('ui.render'); void ringToNext($) }, tr, e.props.bodyColumns, () => { paneTab = nextTab(paneTab); $.ui.invalidate('ui.render') }, expanded, (id: string) => { const set = isSectionId(id) ? folded : expanded; if (!set.delete(id)) set.add(id); $.ui.invalidate('ui.render') }, folded, e.props.scroll ?? null, { state: await read($, DECIDE), inputs: SURFACES_WITH_INPUT.has(e.surface), onPress: (id: string) => { void decidePress($, id) }, onNote: (key: string, value: string) => { void decideNote($, key, value) } }, decideScroll)))
825
826 // The 待決 tab draws its own scrolling window (scroll.tsx), so the person's scroll keys there move the mod's offset and never reach the engine; every other tab keeps the engine's own
827 // scrolling (`next(e)`).
828 on('ui.scroll', { component: 'Pane', requestId: PANE_ID }, ($, e, next) => {
829 return scrollHook(decideScroll, e, next, () => { void $.ui.invalidate('ui.render') })
830 })
831}
832const decideScroll = newScroll()
833
834// The 待決 tab is exactly the pane's height, so the engine's own window must stand at 0 there; one left scrolled by another tab (the engine keeps one offset per pane) would hide the
835// strip. Best effort: a pane that holds no keys refuses, and the next draw asks again.
836function hostScrollHome($: EngineInterface, scroll: { offset: number } | undefined, tab: PaneTab): void {
837 if (tab === 'decide' && scroll !== undefined && scroll.offset > 0) void $.ui.scroll({ in: PANE_ID, to: 'start' }).catch(() => undefined)
838}
839
840export const register: Register = on => {
841 registerLive(on)
842 on('session.start', async ($, e, next) => {
843 await startLive($)
844 return next(e)
845 })
846}
847mods/roundtable/register.ts 210 lines1// mods/roundtable/register.ts — window B. Command /rt-room [id] opens the pane. The log is re-read about once a second.
2// Rooms directory: AUTOPILOT_ROOMS_DIR, else HOME/.autopilot/rooms (plan §6). When $.env.get throws, or neither variable is a non-empty string, the directory is unresolved: the pane says so and does not guess a path. The mod host's own environment is not read.
3// Enter runs `node <plugin root>/scripts/roundtable-window.js send ROOM TEXT` (the same send as window A). A non-zero exit is drawn as a broken line. Success is never reported when the run failed.
4// closeOnEscape is not set: Esc returns the keyboard and leaves the pane open.
5// The one-second read starts on the first open, not at session start, so a failed start cannot leave a timer behind.
6
7import type { EngineInterface, Register } from 'claude-code'
8
9import { resolveLocale } from '../live/i18n'
10import type { Locale } from '../live/i18n'
11import { newScroll, scrollHook } from '../live/scroll'
12import { displayLines, parseRoomLog } from './model'
13import type { RoomRow } from './model'
14import { RoundtablePane } from './pane'
15import { makeRT } from './strings'
16import type { RT } from './strings'
17
18export const PANE_ID = 'autopilot-roundtable'
19const ROOM_RE = /^[a-z0-9-]+$/
20const POLL_MS = 1000
21
22type State = {
23 room: string | null
24 raw: string
25 rows: RoomRow[]
26 failure: string | null
27 note: string | null
28 draft: string
29 locale: Locale
30}
31
32const state: State = { room: null, raw: '', rows: [], failure: null, note: null, draft: '', locale: 'en' }
33const scroll = newScroll()
34let timer: { cancel: () => void } | undefined
35let seen: string | null = null
36
37export async function roomsDirectory($: EngineInterface): Promise<string | null> {
38 let over: string | undefined
39 let home: string | undefined
40 try { over = await $.env.get('AUTOPILOT_ROOMS_DIR') } catch { over = undefined }
41 if (typeof over === 'string' && over.trim() !== '') return over.trim()
42 try { home = await $.env.get('HOME') } catch { home = undefined }
43 if (typeof home !== 'string' || home.trim() === '') return null
44 return home.replace(/\/$/, '') + '/.autopilot/rooms'
45}
46
47async function localeOf($: EngineInterface): Promise<Locale> {
48 const home = await $.env.get('HOME').catch(() => undefined)
49 let ui: unknown
50 if (home) {
51 try {
52 const cfg = JSON.parse(String(await $.fs.read(home + '/.autopilot/config.json')))
53 ui = cfg && typeof cfg === 'object' ? (cfg as { ui?: { locale?: unknown } }).ui?.locale : undefined
54 } catch (_e) { /* no config */ }
55 }
56 const envLocale = await $.env.get('AUTOPILOT_LOCALE').catch(() => undefined)
57 const lang = (await $.env.get('LC_ALL').catch(() => undefined)) || (await $.env.get('LANG').catch(() => undefined))
58 let language: string | null = null
59 if (ui !== 'en' && ui !== 'zh-TW' && envLocale !== 'en' && envLocale !== 'zh-TW') {
60 try {
61 const rows = await $.config.list()
62 const row = rows.find(r => r.key === 'language')
63 if (row && typeof row.value === 'string') language = row.value
64 } catch (_e) { /* unread */ }
65 }
66 return resolveLocale({ config: ui, env: envLocale, language, lang })
67}
68
69async function newestRoom($: EngineInterface, dir: string): Promise<string | null> {
70 let entries: { name: string; kind: string; mtimeMs?: number }[]
71 try { entries = await $.fs.list(dir) } catch { return null }
72 let best: { name: string; mt: number } | null = null
73 for (const e of entries) {
74 if (e.kind !== 'dir' || !ROOM_RE.test(e.name)) continue
75 const mt = typeof e.mtimeMs === 'number' ? e.mtimeMs : 0
76 if (best === null || mt >= best.mt) best = { name: e.name, mt }
77 }
78 return best === null ? null : best.name
79}
80
81export async function pollRoundtable($: EngineInterface): Promise<void> {
82 if (state.room === null) return
83 const dir = await roomsDirectory($)
84 if (dir === null) { state.note = makeRT(state.locale)('rt.unresolved'); return }
85 const path = dir.replace(/\/$/, '') + '/' + state.room + '/room.jsonl'
86 let text = ''
87 try { text = String(await $.fs.read(path)) } catch { text = '' }
88 if (seen !== null && text === seen) return
89 seen = text
90 state.raw = text
91 state.rows = parseRoomLog(text)
92 state.note = text === '' ? makeRT(state.locale)('rt.missing') : null
93 void $.ui.invalidate('ui.render')
94}
95
96function ensureTimer($: EngineInterface): void {
97 if (timer !== undefined) return
98 timer = $.clock.every(POLL_MS, () => { void pollRoundtable($) })
99}
100
101async function adopt($: EngineInterface, room: string): Promise<void> {
102 state.locale = await localeOf($)
103 const t = makeRT(state.locale)
104 if (!ROOM_RE.test(room)) { state.room = null; state.note = t('rt.badRoom'); void $.ui.invalidate('ui.render'); return }
105 const dir = await roomsDirectory($)
106 state.room = room
107 state.failure = null
108 seen = null
109 if (dir === null) { state.note = t('rt.unresolved'); state.rows = []; void $.ui.invalidate('ui.render'); return }
110 await pollRoundtable($)
111}
112
113// Append is the window A script. The runner is the engine's; a failed exit is shown and never treated as success.
114function keepDraft(text: string): void {
115 // The host clears its field on submit; put the submitted text back unless a newer draft arrived in flight.
116 if (state.draft === '' || state.draft === text) state.draft = text
117}
118
119export async function submitSay($: EngineInterface, text: string): Promise<void> {
120 const body = text.trim()
121 if (state.room === null || body === '') {
122 state.draft = ''
123 void $.ui.invalidate('ui.render')
124 return
125 }
126 state.failure = null
127 const root = $.plugin.root.replace(/\/$/, '')
128 const argv = ['node', root + '/scripts/roundtable-window.js', 'send', '--', state.room, body]
129 let ran: { exitCode: number; stderr?: string }
130 try {
131 ran = await $.process.run(argv, { timeoutMs: 30_000 })
132 } catch (err) {
133 state.failure = String(err)
134 keepDraft(text)
135 void $.ui.invalidate('ui.render')
136 return
137 }
138 if (ran.exitCode !== 0) {
139 const errText = (ran.stderr || '').trim()
140 state.failure = errText !== '' ? errText : 'exit ' + ran.exitCode
141 keepDraft(text)
142 void $.ui.invalidate('ui.render')
143 return
144 }
145 // Success clears only the submitted text; a draft typed while the send was in flight stays.
146 if (state.draft === text) state.draft = ''
147 await pollRoundtable($)
148 void $.ui.invalidate('ui.render')
149}
150
151export async function startRoundtable($: EngineInterface): Promise<void> {
152 await $.command.register({ name: 'rt-room', description: 'Open the roundtable room pane', argumentHint: '[room-id]' })
153}
154
155export function registerRoundtable(on: Parameters<Register>[0]): void {
156 on('command.run', { command: 'rt-room' }, async ($, e) => {
157 const arg = e.args.trim()
158 if (arg !== '') {
159 void $.ui.open({ id: PANE_ID, title: arg, focus: true })
160 ensureTimer($)
161 await adopt($, arg)
162 return {}
163 }
164 const dir = await roomsDirectory($)
165 const room = dir === null ? null : await newestRoom($, dir)
166 void $.ui.open({ id: PANE_ID, title: room ?? 'roundtable', focus: true })
167 ensureTimer($)
168 if (room === null) {
169 state.locale = await localeOf($)
170 state.room = null
171 state.note = makeRT(state.locale)(dir === null ? 'rt.unresolved' : 'rt.empty')
172 void $.ui.invalidate('ui.render')
173 return {}
174 }
175 await adopt($, room)
176 return {}
177 })
178
179 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
180 const t: RT = makeRT(state.locale)
181 const cols = frameCols(e)
182 scroll.redraw = () => { void $.ui.invalidate('ui.render') }
183 return RoundtablePane($.ui.resolve(e), {
184 room: state.room,
185 count: state.rows.length,
186 lines: displayLines(state.rows, Math.max(4, cols - 1)),
187 failure: state.failure,
188 note: state.note,
189 draft: state.draft,
190 }, t, (v: string) => { state.draft = v }, (v: string) => submitSay($, v), { props: (e as { props?: unknown }).props, model: scroll })
191 })
192
193 on('ui.scroll', { component: 'Pane', requestId: PANE_ID }, ($, e, next) => {
194 return scrollHook(scroll, e, next, () => { void $.ui.invalidate('ui.render') })
195 })
196}
197
198function frameCols(e: unknown): number {
199 const cols = (e as { props?: { bodyColumns?: unknown } }).props?.bodyColumns
200 return typeof cols === 'number' && cols > 0 ? cols : 80
201}
202
203export const register: Register = on => {
204 registerRoundtable(on)
205 on('session.start', async ($, e, next) => {
206 await startRoundtable($)
207 return next(e)
208 })
209}
210mods/viewer/register.ts 114 lines1// mods/viewer/register.ts — the `viewer` mod (Claude Code only): the `show` tool, a window that shows a file or a git diff to the owner without the text passing
2// through the model.
3//
4// The model calls `mcp__autopilot__show` with a file path (optionally a line range) or git diff arguments. This module reads the file (or runs `git diff` by argv, no shell),
5// opens a dialog-style pane with the text, and answers the model with ONE short line (model.ts summaryOf*): the path, the line numbers, the counts — never the text.
6// The live mod's pressable file paths import showPath and call it directly (the spike showed a plugin's own `$.tool.call` of its own tool is not served), so one window serves both. Esc closes the window (closeOnEscape) and the keyboard goes back.
7//
8// tool show { path, start?, end? } | { diff: ["HEAD~1", "--", "src"] }
9// command /show <path[:line]> | /show diff <git diff arguments> (opens the same window; answers no text, so nothing reaches the model)
10// pane id autopilot-viewer; scrolling is the engine's (arrows, PgUp, PgDn, Home, End)
11
12import type { EngineInterface, Register } from 'claude-code'
13
14import { errorOf, fileView, parseShowInput } from './model'
15import type { ShowInput, ShowRequest } from './model'
16import { aiState, cancelAi, runAi, sendToChat, toggleAi } from './assist'
17import type { Source } from './assist'
18import { Viewer } from './pane'
19import { newScroll, scrollHook } from '../live/scroll'
20import type { AiView } from './pane'
21import { PANE_ID, TOOL_DESCRIPTION, TOOL_FULL, TOOL_NAME, TOOL_SCHEMA, currentView, reopenWindow, setCurrentView, shownFile, show } from './show'
22import { makeVT } from './strings'
23import type { VT } from './strings'
24
25// the registrations that need a bound session; run from `session.start`
26export async function startViewer($: EngineInterface): Promise<void> {
27 await $.tool.register({ name: TOOL_NAME, description: TOOL_DESCRIPTION, inputSchema: TOOL_SCHEMA, isDeferred: false })
28 await $.command.register({ name: 'show', description: 'Show a file or a git diff in a window (the text does not go to the model)', argumentHint: '<path[:line]> | diff <git diff arguments>' })
29}
30
31// every hook of the mod except `session.start` (the composed module hands startViewer to the live mod's session.start)
32export function registerViewer(on: Parameters<Register>[0]): void {
33
34 on('tool.call', { tool: TOOL_FULL }, async ($, e) => {
35 const parsed = parseShowInput(e as unknown as ShowInput)
36 if (!parsed.ok) return { deny: errorOf(parsed.why) }
37 const out = await show($, parsed.req)
38 if (out.ok && !out.placed) $.ui.toast(makeVT(currentView()?.locale ?? 'en')('viewer.waiting')) // the owner's way in is /show, which is placed at any width
39 return out.ok ? { result: out.summary } : { deny: errorOf(out.why) }
40 })
41
42 on('command.run', { command: 'show' }, async ($, e) => {
43 const arg = e.args.trim()
44 const t = makeVT(currentView()?.locale ?? 'en')
45 if (arg === '') {
46 if (!(await reopenWindow($))) $.ui.toast(t('viewer.nothing'))
47 return {}
48 }
49 let parsed
50 if (arg === 'diff' || arg.startsWith('diff ')) parsed = parseShowInput({ diff: arg.slice(4).trim() })
51 else {
52 const m = /^(.*?):(\d+)$/.exec(arg)
53 parsed = parseShowInput(m === null ? { path: arg } : { path: m[1], start: Number(m[2]) })
54 }
55 if (!parsed.ok) $.ui.toast(t('viewer.failed', { why: parsed.why }))
56 else {
57 const out = await show($, parsed.req)
58 if (!out.ok) $.ui.toast(t('viewer.failed', { why: out.why }))
59 }
60 return {} // no text: a command's text becomes a transcript line the model reads, and the window is the point
61 })
62
63 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
64 const cur = currentView()
65 if (cur === null) return Viewer($.ui.resolve(e), { kind: 'loading' }, '', makeVT('en'), () => {})
66 const c = cur
67 const t: VT = makeVT(c.locale)
68 const src = sourceOf(c)
69 const lang = c.locale === 'zh-TW' ? 'zh-TW' : 'en'
70 const ai: AiView | undefined = src === null ? undefined : {
71 state: aiState(),
72 summarize: () => { void runAi($, 'summary', null, src, lang, t) },
73 cancel: () => cancelAi($),
74 focusAsk: () => { void $.ui.focus({ requestId: PANE_ID, key: 'ask-input' }).catch(() => undefined) },
75 ask: (q: string) => { if (q.trim() === '') $.ui.toast(t('viewer.ai.emptyQuestion')); else { void runAi($, 'ask', q.trim(), src, lang, t); void $.ui.focus({ requestId: PANE_ID, key: 'ask' }).catch(() => undefined) } }, // the keyboard leaves the field, so 1 to 4 press buttons again
76 toChat: () => { void sendToChat($, t) },
77 toggle: () => toggleAi($),
78 }
79 viewerScroll.redraw = () => { void $.ui.invalidate('ui.render') } // a click on the track moves the offset and asks for a draw
80 return Viewer($.ui.resolve(e), c.shown, c.title, t, (start: number) => {
81 if (c.shown.kind !== 'file' || c.text === null || currentView() !== c) return
82 const view = fileView(c.shown.view.path, c.text, start, null)
83 if (view === null) return
84 setCurrentView({ ...c, shown: shownFile(view, null) })
85 viewerScroll.offset = 0 // another part of the file starts at the top
86 void $.ui.invalidate('ui.render')
87 void $.ui.scroll({ in: PANE_ID, to: 'start' }).catch(() => undefined)
88 }, ai, { props: (e as unknown as { props?: unknown }).props, model: viewerScroll })
89 })
90
91 // the person's scroll keys on the window: the mod moves its own offset (the frame, ../live/scroll.tsx); without a frame the engine scrolls as before
92 on('ui.scroll', { component: 'Pane', requestId: PANE_ID }, ($, e, next) => {
93 return scrollHook(viewerScroll, e, next, () => { void $.ui.invalidate('ui.render') })
94 })
95}
96const viewerScroll = newScroll()
97
98// what the summary and the question read: the whole text of the window's file (not only the part on screen) or the whole diff
99function sourceOf(c: NonNullable<ReturnType<typeof currentView>>): Source | null {
100 if (c.text === null) return null
101 if (c.shown.kind === 'file') return { text: c.text, path: c.shown.view.path, title: c.title, isDiff: false }
102 if (c.shown.kind === 'diff') return { text: c.text, path: null, title: c.title, isDiff: true }
103 return null
104}
105
106// standalone (the viewer's own tests): the mod with its own session.start
107export const register: Register = on => {
108 registerViewer(on)
109 on('session.start', async ($, e, next) => {
110 await startViewer($)
111 return next(e)
112 })
113}
114mods/live/advisories.ts 57 lines1// mods/live/advisories.ts — the advisory bridge reader (stage-graph plan A1, P7a; Claude Code only).
2//
3// Four hooks (cost-tracker, version-drift-check, context-budget T1, suggest-compact) no longer inject their owner-facing
4// advice into the model's context. Each appends a row to <live_base>/advisories/<sanitised sid>.jsonl:
5// {id, kind, severity, text, at} (hooks/_shared/advisory-sink.js writes it; the text is the hook's own, unchanged)
6// This module reads that file for the CURRENT session and returns the rows not seen yet; register.ts shows each as a toast.
7// The running count (rows seen this session) is kept for a band chip (P7 renders the band). Read-only: nothing is written.
8
9export type Advisory = { id: string; kind: string; severity: 'info' | 'warn'; text: string; at: string }
10
11// Rows of one file, malformed lines and rows without an id / text skipped. Pure.
12export function parseAdvisories(text: string | null): Advisory[] {
13 if (text === null) return []
14 const out: Advisory[] = []
15 for (const line of text.split('\n')) {
16 if (!line.trim()) continue
17 let v: unknown
18 try { v = JSON.parse(line) } catch (_e) { continue }
19 if (typeof v !== 'object' || v === null) continue
20 const r = v as Record<string, unknown>
21 if (typeof r.id !== 'string' || !r.id || typeof r.text !== 'string' || !r.text) continue
22 out.push({
23 id: r.id,
24 kind: typeof r.kind === 'string' ? r.kind : 'advisory',
25 severity: r.severity === 'warn' ? 'warn' : 'info',
26 text: r.text,
27 at: typeof r.at === 'string' ? r.at : '',
28 })
29 }
30 return out
31}
32
33// A row already older than this when the mod first reads a session's file is history, not news: it is counted, not toasted.
34export const FRESH_MS = 5 * 60 * 1000
35
36export type AdvisoryTracker = { sid: string | null; seen: Set<string>; count: number }
37
38export function newTracker(): AdvisoryTracker {
39 return { sid: null, seen: new Set(), count: 0 }
40}
41
42// The rows to toast now. A new sid (or /clear) starts a fresh tracker. On the first read of a session only rows younger
43// than FRESH_MS are toasted; afterwards every unseen row is.
44export function takeNew(tracker: AdvisoryTracker, sid: string, rows: Advisory[], nowMs: number): Advisory[] {
45 const first = tracker.sid !== sid
46 if (first) { tracker.sid = sid; tracker.seen = new Set(); tracker.count = 0 }
47 const fresh: Advisory[] = []
48 for (const row of rows) {
49 if (tracker.seen.has(row.id)) continue
50 tracker.seen.add(row.id)
51 tracker.count += 1
52 const at = Date.parse(row.at)
53 if (!first || (Number.isFinite(at) && nowMs - at <= FRESH_MS)) fresh.push(row)
54 }
55 return fresh
56}
57mods/live/i18n.ts 64 lines1// mods/live/i18n.ts — the live mod's string tables and locale choice (docs/plans/evidence/2026-10-10-tui-v2/i18n.md).
2//
3// A hooks module can import only code files, never .json, so `locales/en.json` and `locales/zh-TW.json` (the editable sources) are
4// compiled into `locales.ts` by `gen-locales.js` (`node mods/live/gen-locales.js` writes it, `--check` fails on drift, a missing id,
5// a placeholder mismatch or an id the code uses but en lacks; run-tests.sh runs the check first). This file stays pure: no `$`,
6// no fs. register.ts reads the config / env / Claude Code language once per tick and hands the answer to `resolveLocale`.
7
8import { EN, ZH_TW } from './locales'
9
10export type Locale = 'en' | 'zh-TW'
11export type Vars = Record<string, string | number>
12export type T = (id: string, vars?: Vars) => string
13
14const TABLES: Record<Locale, Record<string, string>> = { en: EN, 'zh-TW': ZH_TW }
15
16// The text of one id. Order: the active locale, then en, then the id itself (visible and greppable, never throws).
17// `{name}` placeholders take a value from `vars`; an unknown placeholder stays as written. A counted noun has `<id>.one` / `<id>.other`
18// in the table, chosen by `vars.n` (en: 1 = one, else other; zh-TW repeats the same text for both).
19export function makeT(locale: Locale): T {
20 const own = TABLES[locale]
21 return (id: string, vars?: Vars): string => {
22 let key = id
23 if (vars !== undefined && typeof vars.n === 'number') {
24 const form = id + (vars.n === 1 ? '.one' : '.other')
25 if (own[form] !== undefined || EN[form] !== undefined) key = form
26 }
27 const text = own[key] ?? EN[key] ?? key
28 return vars === undefined ? text : text.replace(/\{(\w+)\}/g, (m, name: string) => (vars[name] === undefined ? m : String(vars[name])))
29 }
30}
31
32export const T_EN: T = makeT('en')
33
34// Claude Code's own language setting is free text ("正體中文台灣用語", "Traditional Chinese", "zh-TW", "English"…): map by pattern.
35// No other Chinese variant is claimed until someone ships it, so everything else is en.
36export function localeFromLanguage(text: string): Locale {
37 return /正體|繁體|台灣|zh[-_]?tw|zh[-_]?hant|traditional/i.test(text) ? 'zh-TW' : 'en'
38}
39
40// LANG / LC_ALL style value: zh_TW.UTF-8, zh_TW, zh-TW -> zh-TW; anything else -> en
41export function localeFromPosix(text: string): Locale {
42 return /^zh[-_]TW/i.test(text) ? 'zh-TW' : 'en'
43}
44
45const asLocale = (v: unknown): Locale | null => (v === 'en' || v === 'zh-TW' ? v : null)
46
47export type LocaleInputs = {
48 config: unknown // ~/.autopilot/config.json ui.locale: "en" | "zh-TW" | "auto"
49 env: string | null | undefined // AUTOPILOT_LOCALE
50 language: string | null | undefined // Claude Code's language setting (the /config row or settings.json)
51 lang: string | null | undefined // LC_ALL, else LANG
52}
53
54// ui.locale (explicit) > AUTOPILOT_LOCALE (explicit) > the Claude Code language setting > LC_ALL / LANG > en. "auto" / absent / unknown falls through.
55export function resolveLocale(i: LocaleInputs): Locale {
56 const c = asLocale(i.config)
57 if (c !== null) return c
58 const e = asLocale(i.env)
59 if (e !== null) return e
60 if (typeof i.language === 'string' && i.language.trim() !== '') return localeFromLanguage(i.language)
61 if (typeof i.lang === 'string' && i.lang.trim() !== '') return localeFromPosix(i.lang.trim())
62 return 'en'
63}
64mods/live/ui.ts 1158 lines1// mods/live/ui.ts — the live pane's design system (docs/plans/2026-10-13-live-pane-design-system.md, P0).
2//
3// One module owns the vocabulary the pane draws with: the ten states (glyph + theme key + word), the glyph tables, the layout grid, the formatters, the
4// status mapping from domain objects to states (`classify` -> `STATUS_MAP` -> `stateOf`, `worst`, `SEVERITY`), the freshness thresholds, the fact-ownership
5// table, and the line components. Tab code (P1-P5) builds lines only through the components here; a line or fragment is a `PaneLine` / `Frag` only when
6// `mk()` / `frag()` made it (module-private WeakSets, read back through `isMade` / `isFrag`).
7//
8// P0 scope: the tokens, formatters, components, brand, FRESH_MS and the mapping exist and are tested; `PaneLine.kind` is still optional and no tab is forced
9// through them yet. This file imports TYPES only and uses erasable syntax only, so `node --test mods/live/ui-lint.test.js` can load it directly
10// (Node strips the types) and run the glyph and vocabulary lint against the very tables the pane draws from.
11
12import type { PaneLine, PaneTab, Seg, ThemeKey } from './model'
13
14// ---------------------------------------------------------------------------------------------------------------------------------------------
15// display width (moved here from model.ts, which re-exports it)
16
17export function cellWidth(c: number): number {
18 if (c === 0 || (c >= 0x0300 && c <= 0x036f) || (c >= 0x200b && c <= 0x200f) || (c >= 0xfe00 && c <= 0xfe0f) || (c >= 0x20d0 && c <= 0x20ff)) return 0
19 if ((c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0x303e) || (c >= 0x3041 && c <= 0x33ff) || (c >= 0x3400 && c <= 0x4dbf)
20 || (c >= 0x4e00 && c <= 0x9fff) || (c >= 0xa000 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff)
21 || (c >= 0xfe30 && c <= 0xfe4f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6)
22 || (c >= 0x1f300 && c <= 0x1f64f) || (c >= 0x1f900 && c <= 0x1f9ff) || (c >= 0x20000 && c <= 0x3fffd)) return 2
23 return 1
24}
25// Terminal cell width of a string: East Asian Wide / Fullwidth = 2, combining and zero-width = 0, everything else (the band glyphs included) = 1.
26export function displayWidth(text: string): number {
27 let w = 0
28 for (const ch of text) w += cellWidth(ch.codePointAt(0) as number)
29 return w
30}
31const padCells = (text: string, width: number): string => text + ' '.repeat(Math.max(0, width - displayWidth(text)))
32const padLeft = (text: string, width: number): string => ' '.repeat(Math.max(0, width - displayWidth(text))) + text
33
34// ---------------------------------------------------------------------------------------------------------------------------------------------
35// tokens
36
37export const GRID = [0, 2, 4, 12] as const // the four columns a body line may start at (§3.1)
38export const KEY_W = 12 // the key column of a key/value row, in display cells
39
40export const STATE_IDS = ['need_you', 'failed', 'stalled', 'findings', 'running', 'done', 'pending', 'stopped', 'skipped', 'unknown'] as const
41export type StateId = (typeof STATE_IDS)[number]
42
43// The glyph tables (§3.2, §3.4). Three groups that do not cross: state glyphs, structure glyphs, chart glyphs. `verified` records, per glyph that is new to
44// the vocabulary, where it was checked to draw in ONE cell: confirmed 2026-10-13 by the owner (ssh + tmux, all ten single-cell); was `pending-owner` until the owner ran `node mods/live/glyph-check.js` in the real ssh + tmux
45// terminal (P0 b). `↓` is East Asian Ambiguous and its width is still unchecked (`pending-owner`); the owner's 2026-10-14 ruling settled only its meaning (behind upstream, nothing else), see the plan §8. `fallback` is the next candidate when a glyph fails that check (§8 Q2); it is linted like every other glyph.
46export const GLYPHS = {
47 state: { need_you: '▲', failed: '✗', stalled: '⊘', findings: '△', running: '●', done: '✓', pending: '○', stopped: '◌', skipped: '∅', unknown: '?' },
48 structure: { open: '▾', folded: '▸', rule: '─', detail: '└', command: '$', goto: '›', bullet: '◦', empty: '—', tabMark: '━', residue: '⚑', behind: '↓', bandSep: '│', info: 'ⓘ', round: '↺', decisions: '◆', age: '◷', recommend: '★' },
49 chart: { meterOn: '▰', meterOff: '▱', here: '◐' },
50 scrollbar: { track: '│', thumb: '█' }, // §12.10: the scrolling window's right-hand column; track and thumb borrow the drawing of bandSep and the top spark step, a second meaning each (SHARED_GLYPHS)
51 spark: ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'],
52 fallback: { stalled: '◍', findings: '!' },
53 verified: { '⊘': '2026-10-13 owner-ssh-tmux', '△': '2026-10-13 owner-ssh-tmux', '○': '2026-10-13 owner-ssh-tmux', '◌': '2026-10-13 owner-ssh-tmux', '∅': '2026-10-13 owner-ssh-tmux', '◦': '2026-10-13 owner-ssh-tmux', '›': '2026-10-13 owner-ssh-tmux', '━': '2026-10-13 owner-ssh-tmux', '◐': '2026-10-13 owner-ssh-tmux', '◍': '2026-10-13 owner-ssh-tmux', '↓': 'pending-owner', '★': 'pending-owner' } as Record<string, string>,
54}
55// glyphs that are new to the pane's vocabulary: each must carry a `verified` entry (L3)
56export const NEW_GLYPHS = ['⊘', '△', '○', '◌', '∅', '◦', '›', '━', '◐', '◍', '↓', '★'] as const
57// Extended_Pictographic glyphs a terminal may draw as an emoji box (§3.4); repeated so the rule survives a Unicode update
58export const EMOJI_BANNED = ['⏸', '⚙', '⚠', '✔', '✖', '▶', '⏹', '⏺', '▪', '▫'] as const
59
60// The semantic palette (owner ruling 2026-10-16): ONE colour means ONE thing. This table is the only place in mods/live that names a theme key; every colour the pane
61// and the band draw goes through a ROLE here (ui-lint L8 reads the sources and fails on a theme-key literal anywhere else). A role with no entry (`undefined`) is the
62// default text colour, `dim` is a weight (not a key), and bold is a whitelist (BOLD_USES below).
63// attention (warning) = the owner must look or act here (claude) = you are here
64// broken (error) = failed, stalled or over the cap done (success) = finished
65// running (suggestion) = running now idle (inactive) = nothing to do
66// structure (subtle) = rules, fold marks, separators action (merged) = you can press this (a pressable `[ ... ]` button or option, never a state)
67export type PaletteRole = 'attention' | 'here' | 'broken' | 'done' | 'running' | 'idle' | 'structure' | 'action'
68export const PALETTE: Record<PaletteRole, ThemeKey> = { attention: 'warning', here: 'claude', broken: 'error', done: 'success', running: 'suggestion', idle: 'inactive', structure: 'subtle', action: 'merged' }
69// the one bold whitelist: a section title, the verdict line, the active tab name, a tab name that needs the owner, a decision card's question, a picked decision option and the send button. Nothing else is bold.
70export const BOLD_USES = ['header title', 'verdict line', 'active tab name', 'needing tab name', 'question title', 'picked option', 'send button'] as const
71// which whitelist entry a bold segment belongs to, or null (a violation); invariant I4 reads this so the test never keeps its own copy of the list
72export function boldUseOf(line: PaneLine, s: Seg): (typeof BOLD_USES)[number] | null {
73 if (line.kind === 'verdict') return 'verdict line'
74 if (line.kind === 'header' && s.role === 'prose') return 'header title'
75 if (s.role === 'tab') return s.here === true && (s.color === undefined || s.color === PALETTE.attention) ? 'active tab name' : s.color === PALETTE.attention ? 'needing tab name' : null
76 if (line.kind === 'item' && s.role === 'title') return 'question title'
77 if (line.kind === 'choice' && s.role === 'pick') return 'picked option'
78 if (line.kind === 'choice' && s.role === 'send' && s.press !== undefined) return 'send button'
79 return null
80}
81// a segment option that sets a colour only when there is one (the default text colour is the absence of a key)
82export const tone = (k: ThemeKey | undefined): { color?: ThemeKey } => (k === undefined ? {} : { color: k })
83
84// glyph colour (key) and word colour (wordKey): a need_you row draws only its mark yellow (the owner's attention is drawn once per surface: the verdict line and the tab name
85// carry the yellow words), findings (待修) is not the owner's to act on, so it is default text
86export const STATES: Record<StateId, { glyph: string; key: ThemeKey | undefined; wordKey: ThemeKey | undefined }> = {
87 need_you: { glyph: GLYPHS.state.need_you, key: PALETTE.attention, wordKey: undefined },
88 failed: { glyph: GLYPHS.state.failed, key: PALETTE.broken, wordKey: PALETTE.broken },
89 stalled: { glyph: GLYPHS.state.stalled, key: PALETTE.broken, wordKey: PALETTE.broken },
90 findings: { glyph: GLYPHS.state.findings, key: undefined, wordKey: undefined },
91 running: { glyph: GLYPHS.state.running, key: PALETTE.running, wordKey: PALETTE.running },
92 done: { glyph: GLYPHS.state.done, key: PALETTE.done, wordKey: PALETTE.done },
93 pending: { glyph: GLYPHS.state.pending, key: PALETTE.idle, wordKey: PALETTE.idle },
94 stopped: { glyph: GLYPHS.state.stopped, key: PALETTE.idle, wordKey: PALETTE.idle },
95 skipped: { glyph: GLYPHS.state.skipped, key: PALETTE.idle, wordKey: PALETTE.idle },
96 unknown: { glyph: GLYPHS.state.unknown, key: PALETTE.idle, wordKey: PALETTE.idle },
97}
98// the one total order of "worse" (§3.3); `unknown` ranks last so a missing mapping never hides a real finding
99export const SEVERITY: readonly StateId[] = ['need_you', 'failed', 'stalled', 'findings', 'running', 'stopped', 'pending', 'done', 'skipped', 'unknown']
100
101// freshness thresholds (§2.5), ms; dispatch = a finished run older than 6 h is counted in the chip, not listed (BL-0149); abandonedPlan = a non-terminal plan review untouched for 7 d fades to one line; every comparison is strict (`>`): exactly at the threshold is still fresh
102export const FRESH_MS = { quiet: 1_800_000, planReview: 86_400_000, terminalPlan: 604_800_000, abandonedPlan: 604_800_000, codeReview: 86_400_000, dispatch: 21_600_000 } as const
103export type FreshKind = keyof typeof FRESH_MS
104export const isStale = (kind: FreshKind, ageMs: number): boolean => ageMs > FRESH_MS[kind]
105
106// ---------------------------------------------------------------------------------------------------------------------------------------------
107// glyph and vocabulary lint (the pure checks behind I5 (a), I20 and ui-lint.test.js L3; tests also call them on planted tables)
108
109const EXT_PICT = /\p{Extended_Pictographic}/u
110export type GlyphTables = { state: Record<string, string>; structure: Record<string, string>; chart: Record<string, string>; scrollbar?: Record<string, string>; spark?: readonly string[]; fallback?: Record<string, string>; verified?: Record<string, string> }
111// I5 (c) for one text: an emoji-presentation hazard. `allowPictographic` is true for kind 'detail' lines only. Digits, `#` and `*` are legal (keycap bases, not pictographs).
112export function emojiViolations(text: string, allowPictographic = false): string[] {
113 const out: string[] = []
114 for (const ch of text) {
115 const cp = ch.codePointAt(0) as number
116 if (cp === 0xfe0f) out.push('U+FE0F (emoji variation selector)')
117 else if (cp === 0x20e3) out.push('U+20E3 (keycap mark)')
118 else if ((EMOJI_BANNED as readonly string[]).includes(ch)) out.push('banned emoji-prone glyph ' + ch)
119 else if (!allowPictographic && EXT_PICT.test(ch)) out.push('Extended_Pictographic ' + ch)
120 }
121 return out
122}
123const tableGlyphs = (g: GlyphTables): string[] => [...Object.values(g.state), ...Object.values(g.structure), ...Object.values(g.chart), ...Object.values(g.scrollbar ?? {}), ...(g.spark ?? []), ...Object.values(g.fallback ?? {})]
124// a `verified` entry is `pending-owner` or `<YYYY-MM-DD> <terminal>`; anything else (`yes`, ``, `pending`) is refused
125export const verifiedOk = (v: unknown): boolean => typeof v === 'string' && (v === 'pending-owner' || /^\d{4}-\d{2}-\d{2} \S/.test(v))
126// I5 (a) + L3: every glyph is non-emoji, and each new-to-vocabulary glyph carries a `verified` entry
127export function glyphTableViolations(g: GlyphTables = GLYPHS): string[] {
128 const out: string[] = []
129 for (const glyph of tableGlyphs(g)) for (const v of emojiViolations(glyph)) out.push(`glyph ${glyph}: ${v}`)
130 for (const glyph of NEW_GLYPHS) {
131 if (!tableGlyphs(g).includes(glyph)) continue
132 const v = g.verified?.[glyph]
133 if (!verifiedOk(v)) out.push(`glyph ${glyph} is new to the vocabulary and has no \`verified\` entry`)
134 }
135 return out
136}
137// I20 (tables): one glyph, one meaning. No glyph character under two meanings across the state, structure and chart tables; the ten state glyphs are pairwise distinct.
138// (the fallbacks are alternatives for an existing meaning, so they are exempt from the cross-table check.)
139// The one deliberate exception to one-glyph-one-meaning: the scrollbar's track and thumb are drawn with characters another table already owns (a vertical line, a full block), in
140// their own place (the right-hand column of a scrolling window) and their own colours (structure, here). Each pairing is named here, so any other shared glyph is still reported.
141export const SHARED_GLYPHS: readonly (readonly [string, string])[] = [['structure.bandSep', 'scrollbar.track'], ['spark', 'scrollbar.thumb']]
142const sharedOk = (a: string, b: string): boolean => SHARED_GLYPHS.some(([x, y]) => (x === a && y === b) || (x === b && y === a))
143export function vocabularyViolations(g: GlyphTables = GLYPHS): string[] {
144 const out: string[] = []
145 const seen = new Map<string, string>()
146 for (const [group, table] of [['state', g.state], ['structure', g.structure], ['chart', g.chart], ['scrollbar', g.scrollbar ?? {}]] as const) {
147 for (const [name, glyph] of Object.entries(table)) {
148 const prior = seen.get(glyph)
149 if (prior !== undefined && !sharedOk(prior, group + '.' + name)) out.push(`glyph ${glyph} means both ${prior} and ${group}.${name}`)
150 else if (prior === undefined) seen.set(glyph, group + '.' + name)
151 }
152 }
153 for (const glyph of g.spark ?? []) {
154 const prior = seen.get(glyph)
155 if (prior !== undefined && !sharedOk(prior, 'spark')) out.push(`glyph ${glyph} means both ${prior} and spark`)
156 }
157 return out
158}
159// I20 (lines): no segment both bold and dim; no line outside header / verdict with more than one bold value (a `here` segment pair counts as one)
160export function emphasisViolations(line: PaneLine): string[] {
161 const out: string[] = []
162 const segs = line.segs ?? []
163 for (const s of segs) if (s.bold === true && s.dim === true) out.push('segment both bold and dim: ' + JSON.stringify(s.text))
164 if (line.kind !== 'header' && line.kind !== 'verdict' && line.kind !== 'choice') { // a decision card's picked option is bold as a whole (head and label)
165 const value = (s: Seg): boolean => s.bold === true && s.role !== 'glyph' && s.role !== 'state' // a state's glyph and word are one mark, not a value
166 const bolds = segs.filter(s => value(s) && s.here !== true).length + (segs.some(s => value(s) && s.here === true) ? 1 : 0)
167 if (bolds > 1) out.push('more than one bold value on a ' + String(line.kind) + ' line')
168 }
169 return out
170}
171
172// ---------------------------------------------------------------------------------------------------------------------------------------------
173// formatters (§3.5): tab code never concatenates a unit
174
175export function money(n: number): string {
176 const neg = n < 0
177 const [whole, frac] = Math.abs(n).toFixed(2).split('.')
178 return (neg ? '-' : '') + '$' + whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + frac
179}
180// a ratio (1.17 = 117%) -> integer, floored, no space. The epsilon keeps 0.58 * 100 = 57.999... from reading 57.
181export const pct = (ratio: number): string => Math.floor(ratio * 100 + 1e-9) + '%'
182const two = (n: number): string => (n < 10 ? '0' : '') + n
183// at most two units, minutes zero-padded after hours: 29s, 5m, 8h05m, 4d04h; >= 7 d as 27d
184export function dur(ms: number): string {
185 if (!Number.isFinite(ms) || ms < 0) return '—'
186 const s = Math.floor(ms / 1000)
187 if (s < 60) return s + 's'
188 const m = Math.floor(s / 60)
189 if (m < 60) return m + 'm'
190 const h = Math.floor(m / 60)
191 if (h < 24) return h + 'h' + two(m % 60) + 'm'
192 const d = Math.floor(h / 24)
193 return d >= 7 ? d + 'd' : d + 'd' + two(h % 24) + 'h'
194}
195export const ago = (ms: number, t: Translate): string => t('ago', { age: dur(ms) })
196// HH:MM when `ms` is on the same local day as `nowMs`, MM-DD otherwise
197export function clock(ms: number, nowMs: number): string {
198 const d = new Date(ms)
199 const n = new Date(nowMs)
200 if (d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate()) return two(d.getHours()) + ':' + two(d.getMinutes())
201 return two(d.getMonth() + 1) + '-' + two(d.getDate())
202}
203// 1 decimal below 10, integer above: 2.0 MB, 14 MB, 1.3 GB
204export function size(bytes: number): string {
205 const units = ['B', 'KB', 'MB', 'GB', 'TB']
206 let v = Math.max(0, bytes)
207 let u = 0
208 while (v >= 1024 && u < units.length - 1) { v /= 1024; u++ }
209 return (u === 0 ? String(Math.round(v)) : v < 10 ? v.toFixed(1) : String(Math.round(v))) + ' ' + units[u]
210}
211// 8 hex characters; a range `a..b` shortens both ends
212export const sha = (s: string): string => s.split('..').map(x => x.slice(0, 8)).join('..')
213// an identifier too long: cut from the LEFT, keeping the unique tail (`…2031601-0e0c`)
214export function idTail(id: string, width: number): string {
215 if (displayWidth(id) <= width) return id
216 const chars = [...id]
217 let out = ''
218 let w = 1
219 for (let i = chars.length - 1; i >= 0; i--) {
220 const cw = cellWidth(chars[i].codePointAt(0) as number)
221 if (w + cw > width) break
222 out = chars[i] + out
223 w += cw
224 }
225 return '…' + out.replace(/^[-_.]+/, '')
226}
227// prose too long: cut from the right with `…`
228export function cutProse(text: string, width: number): string {
229 if (displayWidth(text) <= width) return text
230 let out = ''
231 let w = 1
232 for (const ch of text) {
233 const cw = cellWidth(ch.codePointAt(0) as number)
234 if (w + cw > width) break
235 out += ch
236 w += cw
237 }
238 return out + '…'
239}
240// number first, then the measure word from the string table; never `N*`
241export const count = (n: number, measure: string): string => n + ' ' + measure
242
243// ---------------------------------------------------------------------------------------------------------------------------------------------
244// the status mapping (§3.3): classify (ordered precedence -> one atom) -> STATUS_MAP[domain][atom] -> StateId. stateOf / worst are the only producers of `Stated`.
245
246export type Translate = (id: string, vars?: Record<string, string | number>) => string
247declare const STATED: unique symbol
248export type Stated = { readonly [STATED]: true; readonly id: StateId }
249const STATED_OBJS = {} as Record<StateId, Stated>
250for (const id of STATE_IDS) STATED_OBJS[id] = Object.freeze({ id }) as unknown as Stated
251const stated = (id: StateId): Stated => STATED_OBJS[id]
252export const isStated = (v: unknown): v is Stated => typeof v === 'object' && v !== null && Object.values(STATED_OBJS).includes(v as Stated)
253
254export type Domain = 'verdict' | 'run' | 'seat' | 'round' | 'gate' | 'qc' | 'background' | 'task' | 'loadSource' | 'attention' | 'residueGroup' | 'cleanup'
255export type RunSubject = { rc: number | null; final_status: string | null; stall: boolean; fresh: boolean; starting?: boolean } // `starting`: never probed yet, but inside the freshness bound since launch
256export type SeatSubject = { kind: 'code' | 'plan'; verdict: string | null; status: string | null }
257export type RoundSubject = { stale: boolean; converged: boolean; seats: readonly Stated[] }
258export type BackgroundSubject = { exit: number | null; quietMs: number }
259export type LoadSourceSubject = { source: string; behind: number; flags: number }
260export type AttentionSubject = { source: Stated | null } // null = the one item of its own: task acceptance
261export type CleanupSubject = { errors: number; done: number }
262export type Subject = {
263 verdict: string; run: RunSubject; seat: SeatSubject; round: RoundSubject; gate: string; qc: string; background: BackgroundSubject; task: string
264 loadSource: LoadSourceSubject; attention: AttentionSubject; residueGroup: string; cleanup: CleanupSubject
265}
266
267// token normalisation, once: trim, upper-case; a prefix class (`NEEDS*`, `CACHE:*`) is one atom
268const norm = (v: unknown): string => (typeof v === 'string' ? v.trim().toUpperCase() : '')
269const present = (v: string | null | undefined): v is string => typeof v === 'string' && v.trim() !== ''
270const FAILED_FINAL = ['FAILED', 'ERROR', 'KILLED']
271const DONE_FINAL = ['REVIEWED', 'DONE', 'OK']
272
273const CLASSIFY: { [D in Domain]: (s: Subject[D]) => string } = {
274 verdict: s => norm(s),
275 run: r => {
276 const fs = present(r.final_status) ? norm(r.final_status) : null
277 if ((typeof r.rc === 'number' && r.rc !== 0) || (fs !== null && FAILED_FINAL.includes(fs))) return 'failed'
278 if (r.rc === 0 || (fs !== null && DONE_FINAL.includes(fs))) return 'done'
279 if (fs !== null) return 'weird' // a final_status in neither set beats stall and freshness; the raw text goes to detail
280 if (r.stall) return 'stall'
281 return r.fresh ? 'running' : r.starting === true ? 'starting' : 'stopped'
282 },
283 seat: s => {
284 if (present(s.verdict)) return s.kind + ':' + norm(s.verdict)
285 if (present(s.status)) return 'status:' + norm(s.status)
286 return 'none'
287 },
288 round: r => {
289 if (r.stale && !r.converged) return 'stale'
290 const ids = r.seats.map(x => x.id)
291 if (ids.includes('running')) return 'running'
292 if (ids.includes('failed')) return 'failed'
293 if (ids.includes('findings')) return 'findings'
294 if (r.converged || (ids.length > 0 && ids.every(i => i === 'done'))) return 'done'
295 // §3.3 has no row for a round whose seats are partly `unknown` and nothing is running, failed or to fix (a gap, decided in P1): the round is `unknown`, not
296 // `stopped`. `stopped` means "no verdict, or stale"; `unknown` means "a token missing from the mapping", and a round holding one is the second. worst() would
297 // rank it last and show `done`, which hides it again.
298 if (ids.includes('unknown')) return 'unknown'
299 return 'open' // no seats published: the round is not moving and has no verdict (`stopped`)
300 },
301 gate: g => (norm(g).startsWith('NEEDS') ? 'NEEDS' : norm(g)),
302 qc: q => norm(q),
303 background: b => {
304 if (b.exit !== null) return b.exit === 0 ? 'exit0' : 'exitN'
305 return b.quietMs <= FRESH_MS.quiet ? 'fresh' : 'quiet'
306 },
307 task: t => norm(t),
308 loadSource: l => {
309 const src = norm(l.source)
310 if (src.startsWith('CACHE:') || src === 'MISSING') return 'bad'
311 if (l.behind > 0 || l.flags > 0) return 'bad'
312 return src === 'DEV' || src === 'DIRECTORY' ? 'ok' : 'weird'
313 },
314 attention: a => (a.source === null ? 'acceptance' : 'from:' + a.source.id),
315 residueGroup: c => norm(c).toLowerCase(),
316 cleanup: c => (c.errors > 0 ? 'errors' : c.done > 0 ? 'done' : 'nothing'),
317}
318const ATTENTION_FROM = Object.fromEntries(STATE_IDS.map(id => ['from:' + id, id])) as Record<string, StateId>
319export const STATUS_MAP: { [D in Domain]: Record<string, StateId> } = {
320 verdict: { DECIDE: 'need_you', STALLED: 'stalled', WAITING: 'done', RUNNING: 'running', IDLE: 'stopped' },
321 run: { failed: 'failed', done: 'done', weird: 'unknown', stall: 'stalled', running: 'running', starting: 'pending', stopped: 'stopped' },
322 seat: {
323 'code:SHIP-AS-IS': 'done', 'code:FIX-THEN-SHIP': 'findings', 'code:BLOCK': 'failed', 'code:REJECT': 'failed',
324 'plan:READY': 'done', 'plan:APPROVE': 'done', 'plan:PASS': 'done', 'plan:CONDITIONAL': 'findings', 'plan:STOP': 'findings', 'plan:REJECT': 'failed', 'plan:BLOCK': 'failed', // Q5: REJECT and BLOCK are both ✗ 失敗, in a plan review as in a code review
325 'status:RUNNING': 'running', 'status:REVIEWED': 'done',
326 },
327 round: { stale: 'stopped', running: 'running', failed: 'failed', findings: 'findings', done: 'done', unknown: 'unknown', open: 'stopped' },
328 gate: { PASS: 'done', OK: 'done', ACCEPT: 'done', APPROVED: 'done', CONVERGED: 'done', OPEN: 'need_you', OWED: 'need_you', NEEDS: 'need_you', FAIL: 'failed', REJECT: 'failed', BLOCK: 'failed' },
329 qc: { OK: 'done', OWED: 'need_you', NOT_NEEDED: 'skipped', UNKNOWN: 'unknown' },
330 background: { exitN: 'failed', exit0: 'done', fresh: 'running', quiet: 'stopped' },
331 task: { COMPLETED: 'done', IN_PROGRESS: 'running', PENDING: 'pending' },
332 loadSource: { bad: 'need_you', ok: 'done', weird: 'need_you' }, // a source that is neither the dev directory nor a known cache copy is not the copy the owner expects
333 attention: { acceptance: 'need_you', ...ATTENTION_FROM },
334 residueGroup: { dirty: 'need_you', 'clean-integrated': 'done', 'clean-unintegrated': 'need_you', 'unintegrated-branch': 'need_you', 'missing-dir': 'done', live: 'running', unverifiable: 'unknown' }, // a 'clean' class (RESIDUE_KINDS) is drawn as a neutral row, never as a mark
335 cleanup: { errors: 'failed', done: 'done', nothing: 'skipped' },
336}
337export function classify<D extends Domain>(domain: D, subject: Subject[D]): string {
338 return (CLASSIFY[domain] as (s: Subject[D]) => string)(subject)
339}
340export function stateOf<D extends Domain>(domain: D, subject: Subject[D]): Stated {
341 return stated(STATUS_MAP[domain][classify(domain, subject)] ?? 'unknown')
342}
343// the worst of several states under SEVERITY; [] -> skipped
344export function worst(states: readonly Stated[]): Stated {
345 if (states.length === 0) return stated('skipped')
346 let best = states[0].id
347 for (const s of states) if (SEVERITY.indexOf(s.id) < SEVERITY.indexOf(best)) best = s.id
348 return stated(best)
349}
350
351// ---------------------------------------------------------------------------------------------------------------------------------------------
352// fact ownership (§2.6): every fact has one home tab; any other tab shows it only as a projection (a line with `goto`)
353
354export type Owner = PaneTab | 'header' | 'pane'
355export const FACT_OWNER = {
356 'dispatch.runs': 'dispatch', 'dispatch.counts': 'dispatch',
357 'review.round': 'review', 'review.seats': 'review', 'review.qc': 'review', 'review.gates': 'review', 'review.plan': 'review',
358 'review.decisions': 'review', 'review.ladder': 'review', 'review.undocumented': 'review',
359 'decide.cards': 'decide',
360 'now.attention': 'now', 'now.position': 'now', 'now.background': 'now', 'now.tasks': 'now', 'now.recent': 'now',
361 'usage.limit_max': 'spend', 'usage.brain': 'spend', 'usage.window5h': 'spend', 'usage.window7d': 'spend', 'usage.today': 'spend', 'usage.history': 'spend', 'usage.account': 'spend',
362 'spend.session': 'spend', 'spend.local_today': 'spend',
363 'usage.window_other': 'spend', // any other rate-limit window the host reports (spend_limit, an unknown kind)
364 'residue.groups': 'hygiene', 'residue.cleanup': 'hygiene', 'residue.source': 'hygiene',
365 'legend.states': 'legend', 'legend.structure': 'legend', 'legend.keys': 'legend',
366 'header.verdict': 'header',
367 'pane.chrome': 'pane', // lines that carry no fact of the session (the blank between sections, a heading with no chip, a fold / more toggle, an attached detail)
368 'pane.overflow': 'pane', // pane.tsx's own scroll state, not a fact of the session: the header's last metrics line says how many rows lie below
369} as const satisfies Record<string, Owner>
370export type FactId = keyof typeof FACT_OWNER
371
372// the order of sections inside each tab (§2.1), as data; and the sections that start folded (要你處理 never does)
373export const SECTION_ORDER: Record<PaneTab, readonly string[]> = {
374 now: ['attention', 'where', 'tabs', 'background', 'tasks', 'recent'],
375 decide: ['cards'],
376 dispatch: ['running', 'finished', 'other'],
377 review: ['code', 'qc', 'decisions', 'plan'],
378 spend: ['limits', 'today', 'last24', 'account'],
379 hygiene: ['attention', 'cleanable', 'auto', 'source'],
380 legend: ['states', 'structure', 'keys'],
381}
382// the sections that start folded: read by recentLines (now.recent) through sectionOpen; review.plan folds only while it is stale (F2, I11), by passing `stale` to sectionOpen
383export const SECTION_DEFAULTS: Record<string, { folded: boolean }> = { 'now.recent': { folded: true }, 'review.plan': { folded: true }, 'hygiene.cleanable': { folded: false } }
384
385// ---------------------------------------------------------------------------------------------------------------------------------------------
386// the brand: a PaneLine / Frag exists only if a component made it. `mk` and `frag` are not exported as makers for tab code to call by hand; the WeakSets are private.
387
388export type LineKind = 'verdict' | 'header' | 'kv' | 'item' | 'bullet' | 'table' | 'meter' | 'empty' | 'more' | 'command' | 'detail' | 'chart' | 'blank' | 'choice' | 'field'
389declare const FRAG: unique symbol
390export type Frag = { readonly [FRAG]: true; readonly text: string; readonly segs: readonly Seg[]; readonly fact?: FactId }
391const MADE = new WeakSet<object>()
392const FRAGS = new WeakSet<object>()
393type LineInit = Omit<PaneLine, 'kind' | 'fact'> & { kind?: LineKind; fact?: FactId }
394function mk(line: LineInit & { kind: LineKind }): PaneLine {
395 MADE.add(line)
396 return line as PaneLine // a made line carries a fact: the components below pass one, and the invariants (I-fact) check it over every tab
397}
398export const isMade = (line: unknown): boolean => typeof line === 'object' && line !== null && MADE.has(line)
399function frag(segs: Seg[], fact?: FactId): Frag {
400 const f = { text: segs.map(s => s.text).join(''), segs, ...(fact === undefined ? {} : { fact }) }
401 FRAGS.add(f)
402 return f as unknown as Frag
403}
404export const isFrag = (v: unknown): v is Frag => typeof v === 'object' && v !== null && FRAGS.has(v)
405
406export type FmtKind = 'money' | 'pct' | 'dur' | 'ago' | 'clock' | 'size' | 'sha' | 'id' | 'count'
407export type SegRole = 'glyph' | 'state' | 'value' | 'prose' | 'key' | 'rule' | 'tab' | 'title' | 'pick' | 'send' | 'act'
408type SegOpts = { color?: ThemeKey; bold?: boolean; dim?: boolean; role?: SegRole; here?: boolean; fmt?: FmtKind; press?: string }
409const sg = (text: string, o: SegOpts = {}): Seg => ({ text, ...o })
410const dim = (text: string, o: SegOpts = {}): Seg => sg(text, { ...o, dim: true })
411
412// ---- pressable file paths: a press opens the viewer window (mods/viewer) on the file ----
413// A press id of the form `show:<path>[:<line>|:end]`. The pane routes it to the viewer; the segment is drawn in the `action` role, the one colour that means "press this".
414export const SHOW_PRESS = 'show:'
415export const showPress = (path: string, at?: number | 'end'): string => SHOW_PRESS + path + (at === undefined ? '' : ':' + at)
416export function showTarget(id: string): { path: string; line: number | 'end' | null } | null {
417 if (!id.startsWith(SHOW_PRESS)) return null
418 const m = /^(.+?)(?::(\d+|end))?$/.exec(id.slice(SHOW_PRESS.length))
419 if (m === null || m[1] === '') return null
420 return { path: m[1], line: m[2] === undefined ? null : m[2] === 'end' ? 'end' : Number(m[2]) }
421}
422// a path written in prose: it has a directory part or a known file extension, optionally followed by `:<line>`; a trailing sentence mark is not part of it
423const PATH_IN_TEXT = /(?<![\w./~-])(?:~\/|\.{1,2}\/|\/)?(?:[\w.@+-]+\/)+[\w.@+-]*[\w@+-]\.[A-Za-z][A-Za-z0-9]{0,7}(?::\d+)?|(?<![\w./~-])[\w@+-][\w.@+-]*\.(?:md|ts|tsx|js|mjs|cjs|json|sh|py|txt|log|yml|yaml|toml|diff|patch)(?::\d+)?(?![\w/-])/g
424// Split `text` into segments: the paths in it become pressable (action colour), the rest keeps `base`. No path -> one segment, exactly `sg(text, base)`.
425export function linkSegs(text: string, base: SegOpts): Seg[] {
426 const out: Seg[] = []
427 let last = 0
428 for (const m of text.matchAll(PATH_IN_TEXT)) {
429 const at = m.index as number
430 if (at > last) out.push(sg(text.slice(last, at), base))
431 const hit = m[0]
432 const line = /:(\d+)$/.exec(hit)
433 out.push(sg(hit, { role: base.role, color: PALETTE.action, press: showPress(line === null ? hit : hit.slice(0, line.index), line === null ? undefined : Number(line[1])) }))
434 last = at + hit.length
435 }
436 if (last === 0) return [sg(text, base)]
437 if (last < text.length) out.push(sg(text.slice(last), base))
438 return out
439}
440export type Ctx = { t: Translate; cols: number; expanded?: ReadonlySet<string> }
441
442// inline fragments: they exist only as arguments of a builder
443export const val = (s: string, o: { role?: 'value' | 'prose'; fmt?: FmtKind; bold?: boolean; dim?: boolean; here?: boolean; tone?: 'dim' | 'strong'; fact?: FactId } = {}): Frag => frag([sg(s, { role: o.role ?? 'value', ...(o.fmt ? { fmt: o.fmt } : {}), ...(o.here ? { here: true } : {}), ...(o.bold || o.tone === 'strong' ? { bold: true } : {}), ...(o.dim || o.tone === 'dim' ? { dim: true } : {}) })], o.fact)
444export const fmtd = (kind: FmtKind, s: string, fact?: FactId): Frag => frag([sg(s, { role: 'value', fmt: kind })], fact)
445// the state glyph (state colour) and, unless `word: false`, its word (same colour)
446export function stateLead(u: Ctx, s: Stated, o: { word?: boolean; wordW?: number } = {}): Frag {
447 const st = STATES[s.id]
448 const segs: Seg[] = [sg(st.glyph, { ...tone(st.key), role: 'glyph' })]
449 if (o.word !== false) segs.push(sg(' '), sg(padCells(u.t('ui.state.' + s.id), o.wordW ?? 0), { ...tone(st.wordKey), role: 'state' }))
450 return frag(segs)
451}
452// a meter level's theme key: < 80% default text (a healthy level says nothing), >= 80% attention, >= 100% broken (on the raw ratio)
453export const meterKey = (ratio: number): ThemeKey | undefined => (ratio >= 1 ? PALETTE.broken : ratio >= 0.8 ? PALETTE.attention : undefined)
454export function meterValue(value: number, cap: number, o: { cells: number; fact?: FactId }): Frag {
455 const ratio = cap > 0 ? value / cap : 0
456 const on = Math.max(0, Math.min(o.cells, Math.round(Math.min(1, ratio) * o.cells)))
457 const key = meterKey(ratio)
458 return frag([
459 sg(GLYPHS.chart.meterOn.repeat(on), { ...tone(key), role: 'glyph' }),
460 ...(o.cells - on > 0 ? [sg(GLYPHS.chart.meterOff.repeat(o.cells - on), { color: PALETTE.idle, role: 'glyph' })] : []),
461 sg(' '),
462 sg(padLeft(pct(ratio), 4), { ...tone(key), role: 'value', fmt: 'pct' }),
463 ], o.fact)
464}
465const BADGE_STATES = ['need_you', 'running', 'stalled'] as const
466export type BadgeStated = Stated & { readonly id: (typeof BADGE_STATES)[number] }
467// narrows a Stated to the three states that have a badge form, so `stateBadge` rejects the other seven at the type level
468export const isBadgeState = (s: Stated): s is BadgeStated => (BADGE_STATES as readonly string[]).includes(s.id)
469// the only two badge constructors (§3.2 b, I14): ▲, ●N, ⊘N for a state; ⚑N for residue. Any other state is refused.
470export function stateBadge(s: BadgeStated, n: number | undefined, fact: FactId): Frag {
471 if (!isBadgeState(s)) throw new Error('badge: state ' + (s as Stated).id + ' has no badge form')
472 const st = STATES[s.id]
473 if (s.id !== 'need_you' && (n === undefined || n < 1)) throw new Error('badge: ' + s.id + ' needs a count')
474 return frag([sg(st.glyph + (s.id === 'need_you' || n === undefined ? '' : String(n)), { ...tone(st.key), role: 'glyph' })], fact)
475}
476// a header's spend figures: one fragment per fact, no goto, typed as a projection of the 用量 facts
477export function headerProjection(fact: FactId, s: string, label?: string): Frag {
478 if (FACT_OWNER[fact] !== 'spend') throw new Error('headerProjection: ' + fact + ' is not a spend fact')
479 return frag([...(label === undefined ? [] : [sg(label + ' ', { role: 'prose', dim: true })]), sg(s, { role: 'value', fmt: 'money', dim: true })], fact)
480}
481
482// ---------------------------------------------------------------------------------------------------------------------------------------------
483// line builders. Every one returns PaneLine(s) stamped with a `kind` and registered with `mk`.
484
485const segsOf = (...fs: (Frag | Seg)[]): Seg[] => fs.flatMap(f => (isFrag(f) ? [...f.segs] : [f as Seg]))
486const lineOf = (kind: LineKind, segs: Seg[], extra: Partial<PaneLine> = {}): PaneLine => mk({ kind, text: segs.map(s => s.text).join(''), segs, fact: 'pane.chrome', ...extra })
487
488export const blank = (): PaneLine => mk({ kind: 'blank', text: '', fact: 'pane.chrome' })
489
490// `▾ Title chip ────`: foldable section header (the toggle id is the section id); the rule runs to cols - 1
491export function header(u: Ctx, title: string, fold: { id: string; open: boolean }, o: { right?: Frag; fact?: FactId } = {}): PaneLine {
492 if (o.right !== undefined && o.fact === undefined) throw new Error('header: a chip needs a fact')
493 const lead: Seg = sg(fold.open ? GLYPHS.structure.open : GLYPHS.structure.folded, { color: PALETTE.structure, role: 'glyph' })
494 const chip: Seg[] = o.right === undefined ? [] : [...o.right.segs]
495 const titleSeg: Seg = sg(title, { bold: true, role: 'prose' })
496 const widthOf = (): number => displayWidth([lead, sg(' '), titleSeg, ...(chip.length > 0 ? [sg(' '), ...chip] : [])].map(s => s.text).join(''))
497 // the line is `cols - 1` wide with a rule of at least 3 cells (I4): a title or chip too long is cut (§3.1: no line wider than cols). The title goes first, down to
498 // 6 cells; then the last chip segment (the dim meta) takes the rest.
499 const room = u.cols - 1 - 1 - 3 // one space and a 3-cell rule
500 let over = widthOf() - room
501 if (over > 0) {
502 titleSeg.text = cutProse(title, Math.max(Math.min(displayWidth(title), 6), displayWidth(title) - over))
503 over = widthOf() - room
504 }
505 if (over > 0 && chip.length > 0) {
506 const last = chip.length - 1
507 chip[last] = { ...chip[last], text: cutProse(chip[last].text, Math.max(1, displayWidth(chip[last].text) - over)) }
508 }
509 const segs: Seg[] = [lead, sg(' '), titleSeg]
510 if (chip.length > 0) segs.push(sg(' '), ...chip)
511 const fill = u.cols - 1 - widthOf() - 1
512 if (fill >= 3) segs.push(sg(' ' + GLYPHS.structure.rule.repeat(fill), { color: PALETTE.structure, role: 'rule' }))
513 return lineOf('header', segs, { toggle: fold.id, ...(o.fact === undefined ? {} : { fact: o.fact }) })
514}
515
516// key (dim, padded to 12) + value at column 12; no value = a bare key heading the rows beneath it; goto = a press target (`key ›`)
517export function kv(u: Ctx, key: string, value: readonly Frag[], o: { fact: FactId; goto?: PaneTab }): PaneLine {
518 const label = o.goto === undefined ? key : key + ' ' + GLYPHS.structure.goto
519 const segs: Seg[] = [dim(padCells(label, KEY_W), { role: 'key' }), ...segsOf(...value)]
520 return lineOf('kv', segs, { hang: KEY_W, fact: o.fact, ...(o.goto === undefined ? {} : { goto: o.goto }) })
521}
522// an absent value: `—` plus a dim reason
523export const absent = (reason: string): Frag => frag([dim(GLYPHS.structure.empty, { role: 'value' }), dim(' ' + reason, { role: 'prose' })])
524
525// state glyph, state word (padded to the widest in the list), text, dim meta after ` · `, a toggle at the right edge
526export function item(u: Ctx, s: Stated, body: string, meta: Meta | undefined, o: { fact: FactId; at?: 0 | 12; goto?: PaneTab; toggle?: { id: string; open: boolean }; word?: boolean; wordW?: number }): PaneLine {
527 const st = STATES[s.id]
528 const at = o.at ?? 0
529 const segs: Seg[] = []
530 if (at > 0) segs.push(sg(' '.repeat(at)))
531 segs.push(...stateLead(u, s, { word: o.word, wordW: o.wordW }).segs, sg(o.word === false ? ' ' : ' ')) // §5 mockups: two cells after the state word, one after a bare glyph
532 segs.push(sg(body, { role: 'prose', ...(s.id === 'stopped' ? { dim: true } : {}) }))
533 segs.push(...metaSegs(meta))
534 return withToggle(u, 'item', segs, o)
535}
536// a neutral `◦` row that has no state
537export function bullet(u: Ctx, body: string, meta: Meta | undefined, o: { fact: FactId; toggle?: { id: string; open: boolean } }): PaneLine {
538 const segs: Seg[] = [dim(GLYPHS.structure.bullet, { role: 'glyph' }), sg(' '), sg(body, { role: 'prose' })]
539 segs.push(...metaSegs(meta))
540 return withToggle(u, 'bullet', segs, o)
541}
542// the dim meta after a row's body: parts joined by ` · `, each its own segment so a number keeps the formatter that made it (I8). A bare string is one part
543// with no formatter (it must hold no number); `{ text, fmt }` names the formatter. Nothing concatenates a number into a string and hides it from the checker.
544export type MetaPart = string | { text: string; fmt: FmtKind }
545export type Meta = string | readonly MetaPart[]
546const partText = (p: MetaPart): string => (typeof p === 'string' ? p : p.text)
547const metaSegs = (meta: Meta | undefined): Seg[] => {
548 const parts = meta === undefined ? [] : typeof meta === 'string' ? [meta] : meta
549 return parts.filter(p => partText(p) !== '').flatMap(p => [dim(' · ', { role: 'prose' }), dim(partText(p), { role: 'value', ...(typeof p === 'string' ? {} : { fmt: p.fmt }) })])
550}
551function withToggle(u: Ctx, kind: 'item' | 'bullet', segs: Seg[], o: { fact: FactId; goto?: PaneTab; toggle?: { id: string; open: boolean } }): PaneLine {
552 const extra: Partial<PaneLine> = { fact: o.fact, ...(o.goto === undefined ? {} : { goto: o.goto }) }
553 const widthOf = (): number => displayWidth(segs.map(s => s.text).join(''))
554 const mark = o.toggle !== undefined ? (o.toggle.open ? GLYPHS.structure.open : GLYPHS.structure.folded) : o.goto !== undefined ? tabName(o.goto, u) : ''
555 fitSegs(segs, u.cols - 1 - (mark === '' ? 0 : 1 + displayWidth(mark))) // one item is one line (§2.4): too long = the body is cut so the line (and its mark) still fits
556 if (mark !== '') {
557 segs.push(sg(' '.repeat(Math.max(1, u.cols - 1 - widthOf() - displayWidth(mark)))))
558 if (o.toggle === undefined && o.goto !== undefined) segs.push(dim(u.t('tab.' + o.goto), { role: 'prose' }), sg(' '), dim(GLYPHS.structure.goto, { role: 'glyph' })) // the press target: the tab's name, then the `›` glyph
559 else segs.push(dim(mark, { role: 'glyph' }))
560 if (o.toggle !== undefined) extra.toggle = o.toggle.id
561 }
562 return lineOf(kind, segs, extra)
563}
564// cut `segs` (in place) so their text is at most `limit` cells: the body (first prose segment) down to 8 cells at most, then the dim meta, then the body further
565function fitSegs(segs: Seg[], limit: number): void {
566 const widthOf = (): number => displayWidth(segs.map(s => s.text).join(''))
567 const cutBy = (i: number, by: number): void => { segs[i] = { ...segs[i], text: cutProse(segs[i].text, Math.max(1, displayWidth(segs[i].text) - by)) } }
568 if (widthOf() <= limit) return
569 const b = segs.findIndex(s => s.role === 'prose')
570 if (b >= 0) cutBy(b, Math.min(widthOf() - limit, Math.max(0, displayWidth(segs[b].text) - 8)))
571 // the meta is ` · ` + part pairs after the body: the last parts go whole first, then the one left is cut
572 while (b >= 0 && widthOf() > limit && segs.length - (b + 1) > 2) segs.splice(segs.length - 2, 2)
573 if (b >= 0 && widthOf() > limit && segs.length - (b + 1) === 2) cutBy(segs.length - 1, widthOf() - limit)
574 if (widthOf() > limit && b >= 0) cutBy(b, widthOf() - limit)
575}
576const tabName = (tab: PaneTab, u: Ctx): string => u.t('tab.' + tab) + ' ' + GLYPHS.structure.goto
577
578// an empty state: `—` at column 0, dim reason at 2. At most one per section (I10).
579export const empty = (reason: string, fact: FactId): PaneLine => lineOf('empty', [dim(GLYPHS.structure.empty, { role: 'glyph' }), dim(' ' + reason, { role: 'prose' })], { fact })
580// ` ▸ 還有 27 筆已完成` (open: ` ▾ 收起`), a toggle at column 2
581// `bare`: the whole group sits behind the toggle (`▸ 16 項已結束`), so there is no `還有` (it is not "more of a list")
582export function more(u: Ctx, n: number, noun: string, id: string, open = false, bare = false): PaneLine {
583 const body = open ? u.t('ui.collapse') : u.t(bare ? 'ui.more_all' : 'ui.more', { n, noun })
584 return lineOf('more', [sg(' '), dim(open ? GLYPHS.structure.open : GLYPHS.structure.folded, { role: 'glyph' }), dim(' ' + body, { role: 'prose' })], { toggle: id })
585}
586
587// ---- the 待決 tab's controls (pick-and-submit). A `choice` line is a row of pressable options: every seg that carries a `press` id is drawn as a Button by
588// pane.tsx, consecutive segs of one id are one Button. A `field` line is a label followed by a text field (pane.tsx draws the Input). Neither is a number or a state. ----
589export type Choice = { label: string; picked: boolean; recommended: boolean; press?: string }
590// the 待決 card's rows share the pane's key/value grammar: the key (dim) at column 2 in a 10-cell slot, the value at column 12, continuation lines hung at 12.
591export const CARD_KEY_W = KEY_W - 2
592const cardLead = (key: string): Seg[] => [sg(' '), dim(padCells(cutProse(key, CARD_KEY_W - 1), CARD_KEY_W), { role: 'key' })]
593const cardHang = (): Seg => sg(' '.repeat(KEY_W))
594// the question line(s): `▲ n. question` with the glyph of its state; the whole text is bold default text (the 'question title' bold use) while the question is open, plain once it is
595// sent. It wraps (never cut, never repeated) and continuation lines start at column 2. `meta` (dim, after ` · `) closes the last line, or takes one of its own when it does not fit.
596export function cardTitle(u: Ctx, s: Stated, title: string, meta: string | undefined, o: { fact: FactId; sent: boolean }): PaneLine[] {
597 const room = u.cols - 1 - 2
598 const pieces = wrapPlain(title, room, room)
599 const lines = pieces.map((piece, i) => {
600 const body = sg(piece, { role: 'title', ...(o.sent ? {} : { bold: true }) })
601 const lead = i === 0 ? [...stateLead(u, s, { word: false }).segs, sg(' ')] : [sg(' ')]
602 return lineOf('item', [...lead, body], { fact: o.fact, hang: 2 })
603 })
604 if (meta !== undefined && meta !== '') {
605 const last = lines[lines.length - 1]
606 const tail = dim(' · ' + meta, { role: 'prose' })
607 if (displayWidth(last.text) + displayWidth(tail.text) <= u.cols - 1) lines[lines.length - 1] = lineOf('item', [...(last.segs as Seg[]), tail], { fact: o.fact, hang: 2 })
608 else lines.push(lineOf('item', [sg(' '), dim(cutProse(meta, Math.max(1, room)), { role: 'prose' })], { fact: o.fact, hang: 2 }))
609 }
610 return lines
611}
612// one key/value row of a card: ` key value` (the value wraps, continuation lines hang at column 12). `subtle` draws the value dim; an empty key makes a continuation-only row.
613export function cardRow(u: Ctx, key: string, value: string, o: { fact: FactId; subtle?: boolean }): PaneLine[] {
614 const room = Math.max(1, u.cols - 1 - KEY_W)
615 return wrapPlain(value, room, room).map((piece, i) =>
616 lineOf('kv', [...(i === 0 ? cardLead(key) : [cardHang()]), ...linkSegs(piece, { role: 'prose', ...(o.subtle === true ? { dim: true } : {}) })], { hang: KEY_W, fact: o.fact }))
617}
618// the options of one question: the key `選項` at column 2, then rows of at most `cols - 1` cells from column 12: `[x] ★ label` (picked: bold default text) beside `[ ] label`, two
619// cells between options. A press-less choice is drawn plain (a question already sent), its picked mark kept. The star marks the recommendation here and nowhere else.
620export function choiceRows(u: Ctx, key: string, choices: readonly Choice[], o: { fact: FactId }): PaneLine[] {
621 const room = u.cols - 1 - KEY_W
622 const piece = (c: Choice): Seg[] => {
623 const press = c.press === undefined ? {} : { press: c.press, color: PALETTE.action }
624 const pick = c.picked ? { bold: true, role: 'pick' as const } : c.press === undefined ? { dim: true } : {}
625 const head = c.picked ? '[x] ' : '[ ] '
626 const star: Seg[] = c.recommended ? [sg(GLYPHS.structure.recommend, { role: 'glyph', ...(c.press === undefined ? {} : { press: c.press }) }), sg(' ', { role: 'prose', ...(c.press === undefined ? {} : { press: c.press }) })] : []
627 const used = displayWidth(head) + star.reduce((n, x) => n + displayWidth(x.text), 0)
628 return [sg(head, { role: 'prose', ...pick, ...press }), ...star, sg(cutProse(c.label, Math.max(1, room - used)), { role: 'prose', ...pick, ...press })]
629 }
630 const rows: Seg[][] = []
631 let cur: Seg[] = []
632 let w = 0
633 for (const c of choices) {
634 const segs = piece(c)
635 const cw = segs.reduce((n, x) => n + displayWidth(x.text), 0)
636 if (cur.length > 0 && w + 2 + cw > room) { rows.push(cur); cur = []; w = 0 }
637 if (cur.length > 0) { cur.push(sg(' ')); w += 2 }
638 cur.push(...segs)
639 w += cw
640 }
641 if (cur.length > 0) rows.push(cur)
642 return rows.map((r, i) => lineOf('choice', [...(i === 0 ? cardLead(key) : [cardHang()]), ...r], { fact: o.fact }))
643}
644// the send row: `[ label ]` at column 2, bold default text and pressable under `press`, dim and inert without it (nothing chosen yet, or already sent), then a dim `note` saying where
645// the answers go; a note that does not fit beside the button takes the line below, at column 2.
646export function actionRow(u: Ctx, label: string, o: { press?: string; note?: string; fact: FactId }): PaneLine[] {
647 const text = cutProse('[ ' + label + ' ]', Math.max(1, u.cols - 1 - 2))
648 const button = o.press === undefined ? dim(text, { role: 'prose' }) : sg(text, { role: 'send', bold: true, color: PALETTE.action, press: o.press })
649 const note = o.note === undefined || o.note === '' ? undefined : o.note
650 if (note !== undefined && 2 + displayWidth(text) + 2 + displayWidth(note) <= u.cols - 1) return [lineOf('choice', [sg(' '), button, sg(' '), dim(note, { role: 'prose' })], { fact: o.fact })]
651 const out = [lineOf('choice', [sg(' '), button], { fact: o.fact })]
652 if (note !== undefined) out.push(...wrapPlain(note, u.cols - 1 - 2, u.cols - 1 - 2).map(piece => lineOf('detail', [sg(' '), dim(piece, { role: 'prose' })], { fact: o.fact })))
653 return out
654}
655// a pressable `[ label ]` button at column 2 in the action colour (the one pressable look, design plan §12.9); `done` replaces it with the dim result of the press (a plain
656// line, nothing to press). Used by the 殘留 tab: one per entry, always the entry's last row, and one for the whole section, always the section's first row.
657export function buttonRow(u: Ctx, label: string, o: { press: string; fact: FactId }): PaneLine {
658 return lineOf('choice', [sg(' '), sg(cutProse('[ ' + label + ' ]', Math.max(1, u.cols - 1 - 2)), { role: 'act', color: PALETTE.action, press: o.press })], { fact: o.fact })
659}
660// lines meant for a scrolling window's fixed action strip (§12.10): pane.tsx draws them under the rule, not among the scrolling rows
661export const asBar = (ls: PaneLine[]): PaneLine[] => ls.map(l => carry(l, { ...l, bar: true as const }))
662export const resultRow = (u: Ctx, text: string, fact: FactId): PaneLine[] => detail(u, text, { fact })
663// a labelled text field: the key at column 2, the Input at column 12 (drawn by pane.tsx; a surface without Input never gets this line: the card says to answer in the conversation)
664export function fieldRow(u: Ctx, label: string, o: { key: string; placeholder: string; value: string; fact: FactId }): PaneLine {
665 return lineOf('field', cardLead(label), { fact: o.fact, field: { key: o.key, placeholder: o.placeholder, value: o.value } })
666}
667
668const CLOSING_PUNCT_UI = ')」』、。,;:!?)]}】》〉,.;:!?'
669// wrap plain text at spaces, after `/`, and between wide characters; continuation lines hang at `hang` (already part of `first`'s prefix width)
670function wrapPlain(body: string, firstW: number, restW: number): string[] {
671 const out: string[] = []
672 let cur = ''
673 let w = 0
674 let limit = firstW
675 let lastBreak = -1 // index into `cur` just after the last break opportunity
676 for (const ch of body) {
677 const cw = cellWidth(ch.codePointAt(0) as number)
678 if (w + cw > limit && cur !== '') {
679 // in code points, so a step back never splits a surrogate pair
680 const cps = [...cur]
681 let cut = lastBreak > 0 ? [...cur.slice(0, lastBreak)].length : cps.length
682 // a closing mark never starts a line: while the next line would open with one (after its leading spaces are dropped), the character before the cut goes
683 // down too. This covers a run of marks (`。」`), a space before the mark, and a cut at an earlier break; at least one character stays on this line.
684 const head = (k: number): string => (cps.slice(k).join('') + ch).replace(/^ +/, '')[0] ?? ''
685 const closing = (c: string): boolean => c !== '' && CLOSING_PUNCT_UI.includes(c)
686 while (cut > 1 && closing(head(cut))) cut -= 1
687 out.push(cps.slice(0, cut).join('').replace(/ +$/, ''))
688 cur = cps.slice(cut).join('').replace(/^ +/, '')
689 w = displayWidth(cur)
690 limit = restW
691 lastBreak = -1
692 }
693 cur += ch
694 w += cw
695 if (ch === ' ' || ch === '/' || cw === 2) lastBreak = cur.length
696 }
697 if (cur !== '') out.push(cur.replace(/ +$/, ''))
698 // a last line of one wide character (a CJK orphan) takes the last character of the line above, so no line is a lone glyph
699 if (out.length > 1) {
700 const last = [...out[out.length - 1]]
701 const prev = [...out[out.length - 2]]
702 if (last.length === 1 && cellWidth(last[0].codePointAt(0) as number) === 2 && prev.length > 2) { out[out.length - 2] = prev.slice(0, -1).join(''); out[out.length - 1] = prev[prev.length - 1] + last[0] }
703 }
704 return out
705}
706// `$` at 2, the command dim at 4; wraps at spaces and `/`, hangs at 4, is never cut (the owner copies it)
707export function command(u: Ctx, cmd: string, o: { at?: 0 | 12 } = {}): PaneLine[] {
708 const at = o.at ?? 0
709 const pad = ' '.repeat(at)
710 return wrapPlain(cmd, u.cols - 1 - at - 4, u.cols - 1 - at - 4).map((piece, i) =>
711 lineOf('command', [sg(pad + ' '), dim(i === 0 ? GLYPHS.structure.command : ' ', { role: 'glyph' }), sg(' '), dim(piece, { role: 'value' })]))
712}
713// `└` at 2 with text at 4 when it belongs to the item above (it inherits that item's fact); a plain note at 2 otherwise (then it needs its own fact).
714// The only kind allowed to carry raw tokens.
715export function detail(u: Ctx, body: string, o: { attached: true; at?: 0 | 12; fact?: FactId; press?: string } | { attached?: false; at?: 0 | 12; fact: FactId }): PaneLine[] {
716 const at = o.at ?? 0
717 const pad = ' '.repeat(at)
718 if (o.attached === true) {
719 return wrapPlain(body, u.cols - 1 - at - 4, u.cols - 1 - at - 4).map((piece, i) =>
720 lineOf('detail', [sg(pad + ' '), dim(i === 0 ? GLYPHS.structure.detail : ' ', { role: 'glyph' }), sg(' '), o.press === undefined ? dim(piece, { role: 'prose' }) : sg(piece, { role: 'prose', color: PALETTE.action, press: o.press })], o.fact === undefined ? {} : { fact: o.fact }))
721 }
722 return wrapPlain(body, u.cols - 1 - at - 2, u.cols - 1 - at - 2).map(piece => lineOf('detail', [sg(pad + ' '), dim(piece, { role: 'prose' })], { fact: (o as { fact: FactId }).fact }))
723}
724
725// a full-row meter: key, bar, percent, amount, then (when `resetMs` is given) the relative reset time
726export function meter(u: Ctx, key: string, value: number, cap: number, o: { cells: number; amount?: Frag; resetMs?: number; fact: FactId; goto?: PaneTab }): PaneLine {
727 const segs: Seg[] = [dim(padCells(o.goto === undefined ? key : key + ' ' + GLYPHS.structure.goto, KEY_W), { role: 'key' }), ...meterValue(value, cap, { cells: o.cells }).segs]
728 if (o.amount !== undefined) segs.push(sg(' '), ...o.amount.segs)
729 if (o.resetMs !== undefined) segs.push(sg(' '), dim(u.t('ui.reset', { age: dur(o.resetMs) }), { role: 'value', fmt: 'ago' }))
730 return lineOf('meter', segs, { hang: KEY_W, fact: o.fact, ...(o.goto === undefined ? {} : { goto: o.goto }) })
731}
732
733// charts: a two-line unit (value line + caption), both from column 12
734export function chart(u: Ctx, key: string, value: Frag, caption: string | undefined, fact: FactId): PaneLine[] {
735 const lines = [lineOf('chart', [dim(padCells(key, KEY_W), { role: 'key' }), ...value.segs], { hang: KEY_W, fact })]
736 if (caption !== undefined) lines.push(lineOf('chart', [sg(' '.repeat(KEY_W)), dim(caption, { role: 'prose' })], { fact }))
737 return lines
738}
739// the stage walk `✓─✓─◐─○─○`: done nodes success, the current node `◐` claude (tagged `here`), the rest inactive
740const walkDot = (i: number, current: number): Seg =>
741 i < current ? sg(STATES.done.glyph, { color: PALETTE.done, role: 'glyph' })
742 : i === current ? sg(GLYPHS.chart.here, { color: PALETTE.here, here: true, role: 'glyph' })
743 : sg(STATES.pending.glyph, { color: PALETTE.idle, role: 'glyph' })
744export function walkValue(current: number, n: number): Frag {
745 const segs: Seg[] = []
746 for (let i = 0; i < n; i++) {
747 if (i > 0) segs.push(dim(GLYPHS.structure.rule, { role: 'rule' }))
748 segs.push(walkDot(i, current))
749 }
750 return frag(segs)
751}
752// the stage walk as aligned columns: one column per stage, `labelWidth + 2` cells wide; the dot sits above the label's first cell, `─` fills up to the next dot.
753// When the columns do not fit (KEY_W + total > cols - 1) it falls back to the dot row plus a "step k/n · stage next: stage" line.
754export function walkChart(u: Ctx, key: string, labels: readonly string[], current: number, fact: FactId): PaneLine[] {
755 const n = labels.length
756 const w = labels.map(x => displayWidth(x) + 2)
757 const total = w.reduce((a, b) => a + b, 0) - 2
758 const rule = GLYPHS.structure.rule
759 if (KEY_W + total > u.cols - 1) {
760 const next = current < n - 1 ? u.t('now.walk_next', { stage: labels[current + 1] }) : ''
761 const line = lineOf('chart', [sg(' '.repeat(KEY_W)), dim(u.t('now.walk_step', { n: current + 1, total: n }) + ' · ', { role: 'prose' }), sg(labels[current], { role: 'prose', color: PALETTE.here, here: true }), ...(next === '' ? [] : [dim(next, { role: 'prose' })])], { hang: KEY_W, fact })
762 return [lineOf('chart', [dim(padCells(key, KEY_W), { role: 'key' }), ...walkValue(current, n).segs], { hang: KEY_W, fact }), line]
763 }
764 const dots: Seg[] = [dim(padCells(key, KEY_W), { role: 'key' })]
765 const names: Seg[] = [sg(' '.repeat(KEY_W))]
766 labels.forEach((x, i) => {
767 dots.push(walkDot(i, current))
768 if (i < n - 1) dots.push(dim(rule.repeat(w[i] - 1), { role: 'rule' }))
769 names.push(i === current ? sg(x, { role: 'prose', color: PALETTE.here, here: true }) : i < current ? dim(x, { role: 'prose' }) : sg(x, { role: 'prose', color: PALETTE.idle }))
770 if (i < n - 1) names.push(sg(' '.repeat(w[i] - displayWidth(x))))
771 })
772 return [lineOf('chart', dots, { hang: KEY_W, fact }), lineOf('chart', names, { fact })]
773}
774// a sparkline: one glyph per value scaled to the largest value
775export function sparkValue(values: readonly number[]): Frag {
776 const max = Math.max(0, ...values)
777 const top = GLYPHS.spark.length - 1
778 return frag([sg(values.map(v => GLYPHS.spark[max <= 0 ? 0 : Math.max(0, Math.min(top, Math.round((v / max) * top)))]).join(''), { role: 'glyph' })])
779}
780
781// ---- tables ---------------------------------------------------------------------------------------------------------------------------------
782// Each column: { head, min, priority, flex?, cut }. `priority` 1 is kept longest; the column with the largest number is dropped first (the state column is
783// always kept). When the table is still too wide, the `flex` column is cut to fit (an identifier from the left), then the others down to `min`. It never falls
784// back to key/value blocks.
785export type Column = { head: string; min: number; priority: number; flex?: boolean; cut: 'left' | 'right' }
786export type Cell = string | { text: string; fmt: FmtKind } // a cell holding a number names the formatter that made it (I8)
787const cellText = (c: Cell | undefined): string => (c === undefined ? '' : typeof c === 'string' ? c : c.text)
788const cellFmt = (c: Cell | undefined): { fmt?: FmtKind } => (c === undefined || typeof c === 'string' ? {} : { fmt: c.fmt })
789export type TableRow = { state: Stated; cells: readonly Cell[]; group?: string; ts?: number } // group / ts are stamped on the line (I22); tableList() requires them
790export function table(u: Ctx, columns: readonly Column[], rows: readonly TableRow[], o: { fact: FactId }): PaneLine[] {
791 const stateHead = u.t('ui.table.state')
792 const stateW = Math.max(displayWidth(stateHead), ...rows.map(r => displayWidth(u.t('ui.state.' + r.state.id)))) // the word column; the glyph and a space precede it
793 const lead = 2 + stateW
794 const w = columns.map((c, i) => Math.max(displayWidth(c.head), ...rows.map(r => displayWidth(cellText(r.cells[i])))))
795 const floor = columns.map((c, i) => Math.max(c.min, Math.min(w[i], displayWidth(c.head)))) // a column never narrows below its own heading: the heading row must not wrap or clip, or it stops lining up with the cells under it
796 const keep = columns.map((_, i) => i)
797 const total = (): number => lead + keep.reduce((n, i) => n + 2 + w[i], 0)
798 // 1. drop whole columns, the largest priority number first, only while the table cannot fit even with every kept column cut to its `min`
799 // (the state column is never dropped; one data column stays)
800 const minTotal = (): number => lead + keep.reduce((n, i) => n + 2 + Math.min(w[i], floor[i]), 0)
801 while (minTotal() > u.cols - 1 && keep.length > 1) {
802 let drop = keep[0]
803 for (const i of keep) if (columns[i].priority > columns[drop].priority) drop = i
804 keep.splice(keep.indexOf(drop), 1)
805 }
806 // 2. cut the flex column, then every other column, down to its `min`
807 let over = total() - (u.cols - 1)
808 for (const flexPass of [true, false]) {
809 for (const i of keep) {
810 if (over <= 0) break
811 if ((columns[i].flex === true) !== flexPass) continue
812 const take = Math.max(0, Math.min(w[i] - floor[i], over))
813 w[i] -= take
814 over -= take
815 }
816 }
817 const fit = (cell: string, i: number): string => padCells(displayWidth(cell) > w[i] ? (columns[i].cut === 'left' ? idTail(cell, w[i]) : cutProse(cell, w[i])) : cell, w[i])
818 const head = lineOf('table', [sg(' '), dim(padCells(stateHead, stateW), { role: 'key' }), ...keep.flatMap(i => [sg(' '), dim(padCells(columns[i].head, w[i]), { role: 'key' })])], { fact: o.fact })
819 const body = rows.map(r => {
820 const st = STATES[r.state.id]
821 return lineOf('table', [
822 sg(st.glyph, { ...tone(st.key), role: 'glyph' }), sg(' '), sg(padCells(u.t('ui.state.' + r.state.id), stateW), { ...tone(st.wordKey), role: 'state' }),
823 ...keep.flatMap(i => [sg(' '), sg(fit(cellText(r.cells[i]), i), { role: 'value', ...cellFmt(r.cells[i]) })]),
824 ], { fact: o.fact, ...(r.group === undefined ? {} : { group: r.group }), ...(r.ts === undefined ? {} : { ts: r.ts }) })
825 })
826 return [head, ...body]
827}
828
829// ---- lists and sections -----------------------------------------------------------------------------------------------------------------------
830// Every list of rows goes through list(): equal `group` keys fold into one counted row, rows run needs-you -> live -> finished and newest first inside a
831// state, the cap applies to the grouped rows, and a `more` toggle carries the rest.
832export type RowSpec = {
833 group: string; ts: number; state: Stated; fact: FactId; body: string; meta?: Meta
834 groupBody?: (n: number) => string // the text of a folded group of n rows
835 shape?: 'item' | 'bullet'; toggle?: string; goto?: PaneTab; word?: boolean
836 at?: 0 | 12 // the column the row starts at (a seat `item` under the valueless `席位` key sits at 12)
837 children?: readonly PaneLine[] // the detail / command lines that follow the row while its toggle is open
838 bodyOpen?: string; metaOpen?: Meta // the row's own text while its toggle is open (an opened decision reads `id` + `可逆 · writer`)
839}
840// `keepOrder`: the rows stay in the order given (seats are a panel in seat order, not a queue; §5.3 draws s0, s1, s2, s3). Grouping and the cap still apply.
841export function list(u: Ctx, id: string, noun: string, rows: readonly RowSpec[], o: { cap?: number; keepOrder?: boolean } = {}): PaneLine[] {
842 const cap = o.cap ?? 5
843 const groups = new Map<string, { first: RowSpec; n: number; state: Stated }>()
844 for (const r of o.keepOrder === true ? rows : [...rows].sort((a, b) => b.ts - a.ts)) {
845 const g = groups.get(r.group)
846 if (g === undefined) groups.set(r.group, { first: r, n: 1, state: r.state })
847 else { g.n++; g.state = worst([g.state, r.state]) }
848 }
849 const ordered = o.keepOrder === true ? [...groups.values()] : [...groups.values()].sort((a, b) => SEVERITY.indexOf(a.state.id) - SEVERITY.indexOf(b.state.id) || b.first.ts - a.first.ts)
850 const expanded = u.expanded?.has('more:' + id) === true
851 const shown = expanded ? ordered : ordered.slice(0, cap)
852 const wordW = Math.max(0, ...shown.map(g => displayWidth(u.t('ui.state.' + g.state.id))))
853 const out = shown.flatMap(g => {
854 const r = g.first
855 const isOpen = r.toggle !== undefined && u.expanded?.has(r.toggle) === true
856 const body = isOpen && r.bodyOpen !== undefined ? r.bodyOpen : g.n > 1 && r.groupBody !== undefined ? r.groupBody(g.n) : r.body
857 const meta = isOpen && r.bodyOpen !== undefined ? r.metaOpen : r.meta
858 const tog = r.toggle === undefined ? undefined : { id: r.toggle, open: isOpen }
859 const line = r.shape === 'bullet'
860 ? bullet(u, body, meta, { fact: r.fact, ...(tog === undefined ? {} : { toggle: tog }) })
861 : item(u, g.state, body, meta, { fact: r.fact, wordW, ...(r.at === undefined ? {} : { at: r.at }), ...(r.word === undefined ? {} : { word: r.word }), ...(tog === undefined ? {} : { toggle: tog }), ...(r.goto === undefined ? {} : { goto: r.goto }) })
862 return isOpen && r.children !== undefined ? [line, ...r.children] : [line]
863 })
864 if (ordered.length > cap) out.push(more(u, ordered.length - cap, noun, 'more:' + id, expanded))
865 return out
866}
867// the sections of one tab, emitted in SECTION_ORDER[tab]; a missing or an unknown section id is an error, so tab code cannot reorder or skip a header
868export function sections(tab: PaneTab, parts: Record<string, readonly PaneLine[]>): PaneLine[] {
869 const order = SECTION_ORDER[tab]
870 for (const id of Object.keys(parts)) if (!order.includes(id)) throw new Error('sections: ' + tab + ' has no section ' + id)
871 for (const id of order) if (parts[id] === undefined) throw new Error('sections: ' + tab + ' is missing section ' + id)
872 return order.flatMap(id => [...parts[id]])
873}
874// typed constructors for body lines of a tab (§2.6 rule 7): an owner row is checked against the tab, a projection must carry `goto` and belong to another tab
875export function ownerRow(tab: PaneTab, fact: FactId, line: PaneLine): PaneLine {
876 if (fact === 'pane.chrome') return line // a heading, a toggle row or a spacer: no fact of the session, no owner to check
877 if (FACT_OWNER[fact] !== tab) throw new Error('ownerRow: ' + fact + ' is owned by ' + FACT_OWNER[fact] + ', not ' + tab)
878 return line
879}
880export function projection(tab: PaneTab, fact: FactId, line: PaneLine): PaneLine {
881 if (FACT_OWNER[fact] === tab) throw new Error('projection: ' + fact + ' is owned by ' + tab + ' (use ownerRow)')
882 if (line.goto === undefined) throw new Error('projection: ' + fact + ' on ' + tab + ' needs goto')
883 return line
884}
885
886// the global header (§2.2): line 1 = verdict glyph + word (state colour, bold), project (bold), elapsed (dim); line 2 = metrics (dim). At >= 110 columns, when both
887// fit with a gap of at least 4 cells, they merge into one line with the metrics right-aligned.
888export function verdictHeader(u: Ctx, v: { state: Stated; word: string; project: string; elapsed: string; metrics: readonly Frag[] }): PaneLine[] {
889 const st = STATES[v.state.id]
890 const left: Seg[] = [
891 sg(st.glyph, { ...tone(st.key), bold: true, role: 'glyph' }), sg(' '), sg(v.word, { ...tone(st.key), bold: true, role: 'state' }), sg(' '),
892 sg(v.project, { bold: true, role: 'value' }), ...(v.elapsed === '' ? [] : [dim(' · ' + v.elapsed, { role: 'value' })]), // no known start: no elapsed segment
893 ]
894 const metrics: Seg[] = v.metrics.flatMap((m, i) => [...(i > 0 ? [dim(' · ')] : []), ...m.segs.map(s => ({ ...s, dim: true, ...(m.fact === undefined ? {} : { fact: m.fact }) }))])
895 const lw = displayWidth(left.map(s => s.text).join(''))
896 const mw = displayWidth(metrics.map(s => s.text).join(''))
897 if (u.cols >= 110 && lw + 4 + mw <= u.cols - 1) return [lineOf('verdict', [...left, sg(' '.repeat(u.cols - 1 - lw - mw)), ...metrics], { fact: 'header.verdict' })]
898 return [lineOf('verdict', left, { fact: 'header.verdict' }), lineOf('verdict', metrics, { fact: 'header.verdict' })]
899}
900
901// ---------------------------------------------------------------------------------------------------------------------------------------------
902// P1 additions (the review tab): small helpers other tabs may reuse
903
904// a header chip: the state glyph and word, then optional dim meta after ` · ` (`● 執行中 · 1 席已有發現`)
905export function chip(u: Ctx, s: Stated, meta?: string, fmt?: FmtKind): Frag {
906 const segs: Seg[] = [...stateLead(u, s).segs]
907 if (meta !== undefined && meta !== '') segs.push(dim(' · ' + meta, { role: 'value', ...(fmt === undefined ? {} : { fmt }) })) // a number in the meta is tagged with the formatter that made it (I8)
908 return frag(segs)
909}
910// a count of cells as a bar: `on` filled (done; with `here`, the last filled cell is the current one, tagged `here`), the rest inactive
911export function stepBar(total: number, on: number, o: { here?: boolean } = {}): Frag {
912 const k = Math.max(0, Math.min(total, on))
913 const done = o.here === true ? Math.max(0, k - 1) : k
914 const segs: Seg[] = []
915 if (done > 0) segs.push(sg(GLYPHS.chart.meterOn.repeat(done), { color: PALETTE.done, role: 'glyph' }))
916 if (o.here === true && k > 0) segs.push(sg(GLYPHS.chart.meterOn, { color: PALETTE.here, here: true, role: 'glyph' }))
917 if (total - k > 0) segs.push(sg(GLYPHS.chart.meterOff.repeat(total - k), { color: PALETTE.idle, role: 'glyph' }))
918 return frag(segs)
919}
920// whether a foldable section is open. `folded` holds the sections the person TOGGLED away from their default (register.ts flips membership on every press),
921// so a section that starts folded (`defaultFolded`) is open exactly when it was toggled.
922export const sectionOpen = (folded: ReadonlySet<string> | undefined, id: string, defaultFolded = false): boolean => defaultFolded === (folded?.has(id) === true)
923// a wrapped piece of a made line keeps the brand and the line's identity (kind, fact, goto, hang); a hand-made line stays unbranded
924export function carry(from: PaneLine, piece: LineInit): PaneLine {
925 if (!MADE.has(from)) return piece as PaneLine
926 return mk({ ...piece, kind: from.kind as LineKind, ...(from.fact === undefined ? {} : { fact: from.fact }), ...(from.goto === undefined ? {} : { goto: from.goto }), ...(from.hang === undefined ? {} : { hang: from.hang }) })
927}
928
929// P2 (派工) helpers
930
931// a header chip made of a state glyph (no word) and a count: `✓ 32`. The section header names the state, the count says how many.
932// a need_you count is a plain number: the owner's attention is drawn once per surface (the verdict line and the tab name), not again on the section title
933export function countChip(u: Ctx, s: Stated, n: number, fact: FactId): Frag {
934 const lead = s.id === 'need_you' ? [] : [...stateLead(u, s, { word: false }).segs, sg(' ')]
935 return frag([...lead, ...plainCount(n, fact).segs], fact)
936}
937
938// a table whose rows go through the same rules as list(): equal `group` keys fold into one row (the newest), rows run in SEVERITY order and, inside a
939// state, newest `ts` first, the cap applies to the grouped rows, and a `more` toggle carries the rest. A row without a `group` or a finite `ts` is refused.
940export type TableListRow = TableRow & { group: string; ts: number }
941export function tableList(u: Ctx, id: string, noun: string, columns: readonly Column[], rows: readonly TableListRow[], o: { fact: FactId; cap?: number }): PaneLine[] {
942 for (const r of rows) if (typeof r.group !== 'string' || r.group === '' || !Number.isFinite(r.ts)) throw new Error('tableList: ' + id + ' has a row without group or ts')
943 const cap = o.cap ?? 5
944 const seen = new Set<string>()
945 const ordered = [...rows].sort((a, b) => b.ts - a.ts).filter(r => (seen.has(r.group) ? false : (seen.add(r.group), true)))
946 .sort((a, b) => SEVERITY.indexOf(a.state.id) - SEVERITY.indexOf(b.state.id) || b.ts - a.ts)
947 const expanded = u.expanded?.has('more:' + id) === true
948 const shown = expanded ? ordered : ordered.slice(0, cap)
949 const out = table(u, columns, shown, { fact: o.fact })
950 if (ordered.length > cap) out.push(more(u, ordered.length - cap, noun, 'more:' + id, expanded))
951 return out
952}
953
954// P3 (用量) helpers: fragments a tab joins into one value
955
956// several fragments as one (a `chart` takes a single value fragment)
957export const cat = (...fs: Frag[]): Frag => frag(fs.flatMap(f => [...f.segs]))
958// a header chip naming a meter level (正常 / 接近上限 / 已超過), in the level's theme key; the word is the chip, there is no glyph
959export const levelChip = (ratio: number, word: string, fact: FactId): Frag => frag([sg(word, { ...tone(meterKey(ratio)), role: 'value' })], fact)
960// a plain share bar of `cells` cells (default text colour: a share is not a level)
961export const barValue = (cells: number): Frag => frag([sg(GLYPHS.chart.meterOn.repeat(Math.max(0, cells)), { role: 'glyph' })])
962
963// ---------------------------------------------------------------------------------------------------------------------------------------------
964// P5: the tab strip, the right-aligned hint, the 殘留 rows and the generated `?` tab. Every theme key, bold and dim of the pane's chrome is decided here;
965// pane.tsx and band.tsx only draw the segments (drawSeg).
966
967// the props a drawn Text gets from one segment: pane.tsx / band.tsx spread this, so they carry no colour decision of their own (§6.1)
968export function drawSeg(s: Seg): { color: ThemeKey | undefined; bold: boolean | undefined; dimColor: boolean | undefined } {
969 return { color: s.color, bold: s.bold, dimColor: s.dim }
970}
971
972// `need`: the tab holds something for the owner, so its name is drawn attention bold (the colour of `▲ 要你決定`)
973export type StripTab = { id: PaneTab; label: string; need?: boolean }
974export type Strip = {
975 next: Seg | null // the next-tab chip `›`
976 tabs: { id: PaneTab; on: boolean; label: Seg }[]
977 rule: Seg[] // the baseline under the strip; on one row it carries the active mark (`━` under the active label)
978 rows: number // drawn rows: the strip's wrapped rows + the baseline
979 exact: boolean // the strip fits one row, so `rows` is certain and the `━` mark is drawn
980}
981// Q1 (owner 2026-10-13, revised 2026-10-16): no background; the active tab name is bold default text (attention bold when it needs the owner) and the `here` colour
982// is only the run of `━` in the baseline; a strip that wraps falls back to bold alone. The `›` next-page button is an action, not a place: dim.
983export function strip(u: Ctx, active: PaneTab, tabs: readonly StripTab[], hasNext: boolean): Strip {
984 const next = hasNext ? sg(GLYPHS.structure.goto, { dim: true, role: 'glyph' }) : null
985 const built = tabs.map(tb => {
986 const on = tb.id === active
987 const needs = tb.need === true
988 // any tab that needs the owner is attention bold (the active one too: the `━` run marks where you are); the active one otherwise default bold, the rest dim.
989 // `here` tags the active label for I4 and the strip test; it is not a colour
990 const o: SegOpts = on ? { ...(needs ? { color: PALETTE.attention } : {}), bold: true, here: true, role: 'tab' } : needs ? { color: PALETTE.attention, bold: true, role: 'tab' } : { dim: true, role: 'tab' }
991 const label = sg(' ' + tb.label + ' ', o)
992 return { id: tb.id, on, label, width: displayWidth(label.text) + 1 }
993 })
994 let rows = 1
995 let x = next === null ? 0 : displayWidth(next.text) + 1
996 let w = x
997 let markAt = -1
998 let markW = 0
999 for (const b of built) {
1000 if (w > 0 && w + b.width > u.cols) { rows++; w = 0 }
1001 if (b.on) { markAt = x; markW = displayWidth(b.label.text) }
1002 w += b.width
1003 x += b.width
1004 }
1005 const exact = rows === 1
1006 const bar = (n: number, glyph: string, o: SegOpts): Seg[] => (n > 0 ? [sg(glyph.repeat(n), { role: 'rule', ...o })] : [])
1007 const rule: Seg[] = exact && markAt >= 0
1008 ? [...bar(markAt, GLYPHS.structure.rule, { color: PALETTE.structure }), ...bar(markW, GLYPHS.structure.tabMark, { color: PALETTE.here, here: true }), ...bar(u.cols - markAt - markW, GLYPHS.structure.rule, { color: PALETTE.structure })]
1009 : bar(u.cols, GLYPHS.structure.rule, { color: PALETTE.structure })
1010 return { next, tabs: built.map(({ id, on, label }) => ({ id, on, label })), rule, rows: rows + 1, exact }
1011}
1012
1013// a hint at the right edge of a made line: in the gap when the line leaves room, else in the run of blanks the one-line header already holds; null = no room
1014export function appendRight(u: Ctx, line: PaneLine, hint: string, fact: FactId): PaneLine | null {
1015 const base: Seg[] = line.segs ?? [{ text: line.text }]
1016 const hintSeg: Seg = { text: hint, dim: true, fact }
1017 const gap = u.cols - 1 - displayWidth(line.text) - displayWidth(hint)
1018 let segs: Seg[]
1019 if (gap >= 2) segs = [...base, { text: ' '.repeat(gap) }, hintSeg]
1020 else {
1021 const pad = base.findIndex((s, i) => i > 0 && i < base.length - 1 && /^ +$/.test(s.text) && s.text.length >= displayWidth(hint) + 4)
1022 if (pad < 0) return null
1023 const n = base[pad].text.length
1024 segs = [...base.slice(0, pad), { text: ' ' }, hintSeg, { text: ' '.repeat(n - 2 - displayWidth(hint)) }, ...base.slice(pad + 1)]
1025 }
1026 return carry(line, { text: segs.map(x => x.text).join(''), segs })
1027}
1028
1029// the overflow hint (live-pane height): `N more rows below` (text only, no glyph; owner ruling 2026-10-14) at the right edge of the header's last metrics line
1030export const overflowHint = (u: Ctx, line: PaneLine, text: string): PaneLine | null => appendRight(u, line, text, 'pane.overflow')
1031
1032// a row of the `?` tab: the example (a fragment) padded to the key column, then the explanation
1033export function legendRow(u: Ctx, example: Frag, body: string, fact: FactId): PaneLine {
1034 const w = displayWidth(example.text)
1035 const segs: Seg[] = [...example.segs, sg(' '.repeat(Math.max(1, KEY_W - w))), sg(body, { role: 'prose' })]
1036 return lineOf('kv', segs, { hang: w < KEY_W ? KEY_W : w + 1, fact })
1037}
1038// the `?` tab's three sections, generated from the same tables the tabs draw from: STATES, the structure glyphs, the meter levels (§5.6). Section ids: `sec:legend.<key>`.
1039export function legendParts(u: Ctx, folded: ReadonlySet<string> | undefined): Record<string, PaneLine[]> {
1040 const t = u.t
1041 const part = (key: string, title: string, body: readonly PaneLine[]): PaneLine[] => {
1042 const id = 'sec:legend.' + key
1043 const open = sectionOpen(folded, id)
1044 return [header(u, title, { id, open }), ...(open ? body : [])]
1045 }
1046 const S = GLYPHS.structure
1047 const wordW = Math.max(...STATE_IDS.map(i => displayWidth(t('ui.state.' + i))))
1048 const states = STATE_IDS.map(id => legendRow(u, stateLead(u, stated(id), { wordW }), t('legend.state.' + id), 'legend.states'))
1049 states.push(legendRow(u, frag([dim(S.empty, { role: 'glyph' })]), t('legend.nodata'), 'legend.states'))
1050 const ex = (...segs: Seg[]): Frag => frag(segs)
1051 const bar = ex(sg(GLYPHS.chart.meterOn, { ...tone(meterKey(0.5)), role: 'glyph' }), sg(GLYPHS.chart.meterOn, { ...tone(meterKey(0.9)), role: 'glyph' }), sg(GLYPHS.chart.meterOn, { ...tone(meterKey(1)), role: 'glyph' }), sg(GLYPHS.chart.meterOff, { color: PALETTE.idle, role: 'glyph' }))
1052 const walk = ex(sg(GLYPHS.state.done, { ...tone(STATES.done.key), role: 'glyph' }), dim(S.rule, { role: 'glyph' }), sg(GLYPHS.chart.here, { color: PALETTE.here, here: true, role: 'glyph' }), dim(S.rule, { role: 'glyph' }), sg(GLYPHS.state.pending, { ...tone(STATES.pending.key), role: 'glyph' }))
1053 const badges = ex(sg(' Aa ', { color: PALETTE.attention, bold: true, role: 'tab' }))
1054 const structure = [
1055 legendRow(u, ex(dim(S.open, { role: 'glyph' }), sg(' '), dim(S.folded, { role: 'glyph' })), t('legend.fold'), 'legend.structure'),
1056 legendRow(u, ex(dim(S.goto, { role: 'glyph' })), t('legend.goto'), 'legend.structure'),
1057 legendRow(u, ex(dim(S.bullet, { role: 'glyph' })), t('legend.bullet'), 'legend.structure'),
1058 legendRow(u, ex(dim(S.detail, { role: 'glyph' }), sg(' '), dim(S.command, { role: 'glyph' })), t('legend.detail'), 'legend.structure'),
1059 legendRow(u, ex(sg(S.tabMark, { color: PALETTE.here, here: true, role: 'glyph' })), t('legend.tabmark'), 'legend.structure'),
1060 legendRow(u, bar, t('legend.meter'), 'legend.structure'),
1061 legendRow(u, walk, t('legend.walk'), 'legend.structure'),
1062 legendRow(u, badges, t('legend.badges'), 'legend.structure'),
1063 legendRow(u, ex(dim(S.behind, { role: 'glyph' })), t('legend.behind'), 'legend.structure'),
1064 legendRow(u, ex(sg(S.recommend, { role: 'glyph' })), t('legend.recommend'), 'legend.structure'),
1065 legendRow(u, ex(sg('[ ]', { role: 'act', color: PALETTE.action })), t('legend.action'), 'legend.structure'),
1066 ]
1067 return {
1068 states: part('states', t('legend.sec_states'), states),
1069 structure: part('structure', t('legend.sec_structure'), structure),
1070 keys: part('keys', t('legend.sec_keys'), detail(u, t('legend.keys', { icon: GLYPHS.structure.info }), { fact: 'legend.keys' })),
1071 }
1072}
1073
1074// ---- 殘留 (§12.7) ----
1075export type ResidueEntry = { kind: string; target: string; cls: string; ageMs: number | null; bytes: number | null; reason: string | null; command: string | null }
1076// what a press on a cleanable entry reported (kept by the host under the entry's target): ok = cleared, otherwise `note` says why not
1077export type CleanResult = { ok: boolean; note: string }
1078// which residue classes need the owner's judgement ('judge'), which can simply be cleared ('clean'), and which are in use ('live', never listed). Every count on every
1079// surface (the tab's chip, 現況's row and summary, the tab name, the band's ⚑N) is derived from this one table; a class it does not name is 'judge'.
1080export type ResidueKind = 'judge' | 'clean' | 'live'
1081export const RESIDUE_KINDS: Record<string, ResidueKind> = {
1082 dirty: 'judge', 'clean-unintegrated': 'judge', 'unintegrated-branch': 'judge', unverifiable: 'judge',
1083 'clean-integrated': 'clean', 'missing-dir': 'clean',
1084 live: 'live',
1085}
1086export const residueKindOf = (cls: string): ResidueKind => (Object.prototype.hasOwnProperty.call(RESIDUE_KINDS, norm(cls).toLowerCase()) ? RESIDUE_KINDS[norm(cls).toLowerCase()] : 'judge')
1087// the name of an entry: a worktree's last path segment (whole, cut from the tail only when the row cannot hold it), a branch's own name
1088export const residueNameOf = (e: ResidueEntry): string => (e.kind === 'branch' ? e.target : (e.target.split('/').filter(x => x !== '').pop() ?? e.target))
1089// the owner-facing reason lines of an entry: the class's sentence from the string table; a class the table does not name keeps the producer's own words
1090export function residueWhy(t: Translate, e: ResidueEntry): string[] {
1091 const cls = norm(e.cls).toLowerCase()
1092 if (!Object.prototype.hasOwnProperty.call(RESIDUE_KINDS, cls) || RESIDUE_KINDS[cls] === 'live') return [t('residue.class_raw', { cls: e.cls }), ...(e.reason === null ? [] : [e.reason])]
1093 if (cls === 'dirty') {
1094 const m = /^(\d+) uncommitted/.exec(e.reason ?? '')
1095 return [m === null ? t('residue.why.dirty_unknown') : t('residue.why.dirty', { n: m[1] })]
1096 }
1097 return [t('residue.why.' + cls.replace(/-/g, '_'))]
1098}
1099// a plain count, no state mark: a header chip whose section name already says what the number is
1100export const plainCount = (n: number, fact: FactId): Frag => frag([sg(String(n), { role: 'value', fmt: 'count' })], fact)
1101const dimParts = (parts: readonly { text: string; fmt: FmtKind }[]): Seg[] => parts.flatMap((p, i) => [...(i > 0 ? [dim(' · ', { role: 'prose' })] : []), dim(p.text, { role: 'value', fmt: p.fmt })])
1102// one residue entry's name row: the mark (the state's glyph, or the neutral `◦`), the name from the left, the dim `age · size` at the right edge. A name too long loses its tail.
1103function residueNameRow(u: Ctx, e: ResidueEntry, state: Stated | null): PaneLine {
1104 const parts: { text: string; fmt: FmtKind }[] = [...(e.ageMs === null ? [] : [{ text: dur(e.ageMs), fmt: 'dur' as const }]), ...(e.bytes === null ? [] : [{ text: size(e.bytes), fmt: 'size' as const }])]
1105 const lead: Seg[] = state === null ? [dim(GLYPHS.structure.bullet, { role: 'glyph' }), sg(' ')] : [...stateLead(u, state, { word: false }).segs, sg(' ')]
1106 const leadW = 2
1107 let meta = dimParts(parts)
1108 let metaW = displayWidth(meta.map(s => s.text).join(''))
1109 if (u.cols - 1 - leadW - metaW - 2 < 8) { meta = []; metaW = 0 } // no room for the name beside the meta: the name wins
1110 const room = u.cols - 1 - leadW - (metaW > 0 ? metaW + 2 : 0)
1111 const name = cutProse(residueNameOf(e), room)
1112 const segs: Seg[] = [...lead, sg(name, { role: 'prose' })]
1113 if (metaW > 0) segs.push(sg(' '.repeat(room - displayWidth(name) + 2)), ...meta)
1114 return lineOf(state === null ? 'bullet' : 'item', segs, { fact: 'residue.groups' })
1115}
1116// one residue section's rows: newest first (judge rows by severity first), each entry the name row, its reason (dim, column 2) and its command (`$`, never cut), at most
1117// `cap` entries and a `more` row for the rest. No grouping, no per-row fold: what the owner has to read is on the screen.
1118// newest first; an entry with no age goes last, and two with no age keep their order (Infinity - Infinity is NaN, which a comparator must never return)
1119const ageOrder = (a: number | null, b: number | null): number => (a === null ? (b === null ? 0 : 1) : b === null ? -1 : a - b)
1120// the last rows of one cleanable entry. On a surface with buttons (`results` given): a `[ 清掉 ]` button, or after the press the dim result (ok), or the failure note and then the
1121// command so the owner can run it by hand. A surface without buttons keeps printing the command. A judged entry never gets a button.
1122function cleanRows(u: Ctx, e: ResidueEntry, results: Record<string, CleanResult> | undefined): PaneLine[] {
1123 const cmd = e.command === null ? [] : command(u, e.command)
1124 if (results === undefined) return cmd
1125 const r = results[e.target]
1126 if (r === undefined) return e.kind === 'worktree' ? [buttonRow(u, u.t('hygiene.clear'), { press: 'clean:' + e.target, fact: 'residue.groups' })] : cmd
1127 return r.ok ? resultRow(u, u.t('hygiene.cleared'), 'residue.groups') : [...resultRow(u, u.t('hygiene.clear_failed', { why: r.note }), 'residue.groups'), ...cmd, ...(e.kind === 'worktree' ? [buttonRow(u, u.t('hygiene.clear'), { press: 'clean:' + e.target, fact: 'residue.groups' })] : [])] // a failed press can be tried again: the reason may be gone
1128}
1129export function residueRows(u: Ctx, id: string, entries: readonly ResidueEntry[], o: { judge: boolean; cap?: number; buttons?: Record<string, CleanResult> }): PaneLine[] {
1130 const cap = o.cap ?? 5
1131 const rows = entries.map(e => ({ e, state: o.judge ? stateOf('residueGroup', e.cls) : null }))
1132 rows.sort((a, b) => (a.state === null || b.state === null ? 0 : SEVERITY.indexOf(a.state.id) - SEVERITY.indexOf(b.state.id)) || ageOrder(a.e.ageMs, b.e.ageMs))
1133 const expanded = u.expanded?.has('more:' + id) === true
1134 const shown = expanded ? rows : rows.slice(0, cap)
1135 const out = shown.flatMap(({ e, state }) => [
1136 residueNameRow(u, e, state),
1137 ...residueWhy(u.t, e).flatMap(w => detail(u, w, { fact: 'residue.groups' })),
1138 ...cleanRows(u, e, o.buttons),
1139 ])
1140 if (rows.length > cap) out.push(more(u, rows.length - cap, u.t('residue.noun'), 'more:' + id, expanded))
1141 return out
1142}
1143
1144// the one dim line of a snapshot that is not ok (no band): the state text as published, nothing invented around it
1145export const stateText = (text: string, fact: FactId): PaneLine => lineOf('verdict', [dim(text, { role: 'prose' })], { fact })
1146
1147// state predicates: tabs.ts asks a Stated what it is without spelling a StateId (lint L7)
1148export const isRunning = (s: Stated): boolean => s.id === 'running'
1149export const isStopped = (s: Stated): boolean => s.id === 'stopped'
1150export const isFindings = (s: Stated): boolean => s.id === 'findings'
1151export const isUnknown = (s: Stated): boolean => s.id === 'unknown'
1152export const isNeedYou = (s: Stated): boolean => s.id === 'need_you'
1153export const hasStageArrow = (s: string): boolean => s.includes(GLYPHS.structure.folded)
1154// the U0-U5 ladder span, drawn once here
1155export const ladderSpan = (): string => 'U0 ' + GLYPHS.structure.rule + ' U5'
1156// text props for a dim run of plain text (a view that holds no colour decision of its own asks for these)
1157export const dimProps = (): ReturnType<typeof drawSeg> => drawSeg({ text: "", dim: true })
1158mods/live/band.tsx 50 lines1// mods/live/band.tsx — the band above the prompt: ONE line (stage-graph P7, contract ②; TUI v2 grammar). Pure view over the snapshot's slots:
2// `layoutBand` (model.ts) applies the width table, this file only draws the result: each slot a plain Button keyed by its slot id (a press opens
3// the pane on the tab that explains it), the separators plain Texts between them, then the ⓘ Button.
4// Colours are theme keys as text colour only: no backgroundColor, no inverse, no raw colour. No Image, no Raster.
5
6import { T_EN } from './i18n'
7import type { T } from './i18n'
8import { BAND_INFO_LABEL, BAND_SEP, layoutBand, plainBandText } from './model'
9import type { LiveSnapshot, Seg, SlotId } from './model'
10import { dimProps, drawSeg } from './ui'
11
12type El = (props: any) => any
13
14export function Band(el: { Box: El; Text: El; Button?: El }, snap: LiveSnapshot | null, columns: number, onInfo: () => void, t: T = T_EN, onSlot: (id: SlotId) => void = () => {}) {
15 const { Box, Text, Button } = el
16 // only the ⓘ autoFocuses: Ctrl+x Tab lands on it, as before the slots were controls
17 const icon = Button === undefined
18 ? <Text>{BAND_INFO_LABEL}</Text>
19 : <Button key="info" plain autoFocus onPress={onInfo}>{BAND_INFO_LABEL}</Button>
20 if (snap === null || snap.band === null) {
21 const reason = snap === null ? t('band.waiting') : snap.text
22 return (
23 <Box>
24 <Text {...dimProps()} wrap="truncate">{plainBandText(reason, columns) + BAND_SEP}</Text>
25 {icon}
26 </Box>
27 )
28 }
29 const line = layoutBand(snap.band.slots, columns)
30 const text = (s: Seg, i: number) => <Text key={'s' + i} {...drawSeg(s)} wrap="truncate">{s.text}</Text>
31 // consecutive segs of one slot become one Button; a seg with no slot (a separator) stays a bare Text
32 const runs: { slot: SlotId | undefined; at: number; segs: Seg[] }[] = []
33 line.segs.forEach((s, i) => {
34 const last = runs[runs.length - 1]
35 if (s.slot !== undefined && last !== undefined && last.slot === s.slot) last.segs.push(s)
36 else runs.push({ slot: s.slot, at: i, segs: [s] })
37 })
38 return (
39 <Box>
40 {runs.map(r => {
41 const texts = r.segs.map((s, j) => text(s, r.at + j))
42 const id = r.slot
43 if (id === undefined || Button === undefined) return texts
44 return <Button key={id} plain onPress={() => onSlot(id)}>{texts}</Button>
45 })}
46 {icon}
47 </Box>
48 )
49}
50mods/live/pane.tsx 138 lines1// mods/live/pane.tsx — the panel the ⓘ opens (TUI v2): Now · Decide · Dispatch · Review · Spend · Hygiene · ? (the stage walk lives in Now, the proxy decisions in Review, the owner's open questions in Decide,
2// the glyph legend is the `?` tab). Pure view over the snapshot; `el` comes from $.ui.resolve(e). Every tab builds its lines in tabs.ts, out of ui.ts components
3// (a missing fact is an explicit "no data" line there, never an empty tab). Words come from the string tables through `t`. This file decides no colour: every Text
4// gets its props from `drawSeg` (ui.ts), theme keys as text colour only, no background, no inverse.
5
6import { T_EN } from './i18n'
7import type { T } from './i18n'
8import { paneWidth } from './model'
9import type { DecideState, LiveSnapshot, PaneLine, PaneTab, Seg } from './model'
10import { decideTabLines, dispatchLines, headerLines, hygieneTabLines, legendLines, nowLines, reviewTabLines, spendTabLines, stripOf, treeRowCount, withOverflowHint } from './tabs'
11import type { ScrollView } from './tabs'
12import { dimProps, drawSeg } from './ui'
13import { keyedGrow, scrollFrame } from './scroll'
14import type { ScrollModel } from './scroll'
15
16export type { PaneTab } from './model'
17
18// What the 待決 tab's controls call: a press on an option or the send Button (by its `press` id), and an edit of a note field (by the field's key). `state` is the
19// owner's picks and notes as the host holds them; `inputs` is whether the surface draws text fields.
20export type DecideActs = { state: DecideState; inputs: boolean; onPress: (id: string) => void; onNote: (key: string, value: string) => void }
21
22type El = (props: any) => any
23
24// The tab strip (ui.ts `strip`): Buttons when the surface has them (a click or Enter switches the tab), plain Text otherwise. The active tab is a bold name, and
25// the baseline under the strip carries a `claude` run of `━` beneath it (a strip that wraps keeps the bold alone). A tab that holds something for the owner is
26// drawn attention bold (no badge, no count).
27// The FIRST drawn Button is the `›` next-tab chip and it carries the pane's autoFocus ("of several in one site the first drawn wins"): whenever Ctrl+x Tab or
28// `open({focus})` hands the pane the keyboard, the ring lands on a Button whose Enter steps to the next tab. It used to land on the ACTIVE tab's Button,
29// where Enter pressed the tab already showing (a no-op): "Ctrl+x Tab, Enter, Enter" cycled tabs only when the ring happened to sit on the band's ⓘ
30// (real machine 2026-10-10, 120 columns). The tab Buttons stay pressable (a click, or Tab / arrows + Enter) and still select their own tab.
31function tabStrip(el: { Box: El; Text: El; Button?: El }, tab: PaneTab, onTab: (t: PaneTab) => void, onNext: () => void, snap: LiveSnapshot | null, t: T, cols: number) {
32 const { Box, Text, Button } = el
33 const strip = stripOf(snap, { t, cols }, tab, Button !== undefined)
34 const draw = (s: Seg, k: string | number) => <Text key={k} {...drawSeg(s)} wrap="truncate">{s.text}</Text>
35 return (
36 <Box flexDirection="column">
37 <Box flexWrap="wrap">
38 {Button === undefined || strip.next === null ? null : <Box key="next"><Button key="next" plain autoFocus onPress={onNext}>{strip.next.text}</Button><Text> </Text></Box>}
39 {strip.tabs.map(x => (
40 <Box key={x.id}>
41 {Button === undefined ? draw(x.label, 'label') : <Button key={x.id} plain onPress={() => onTab(x.id)}>{draw(x.label, 'label')}</Button>}
42 <Text> </Text>
43 </Box>
44 ))}
45 </Box>
46 <Box>{strip.rule.map((s, i) => draw(s, 'rule' + i))}</Box>
47 </Box>
48 )
49}
50
51export function Pane(el: { Box: El; Text: El; Link: El; Button?: El; Input?: El }, snap: LiveSnapshot | null, tab: PaneTab = 'now', onTab: (t: PaneTab) => void = () => {}, t: T = T_EN, bodyColumns: number | null = null, onNext: () => void = () => {}, expanded: ReadonlySet<string> = new Set(), onToggle: (id: string) => void = () => {}, folded: ReadonlySet<string> = new Set(), scroll: ScrollView | null = null, decide: DecideActs | null = null, win: ScrollModel | null = null) {
52 const { Box, Text, Link, Button, Input } = el
53 const cols = paneWidth(bodyColumns)
54 const ctx = { t, cols, expanded, folded, ...(decide === null ? {} : { decide: { ...decide.state, inputs: decide.inputs && Input !== undefined } }) }
55 const segsOf = (l: PaneLine): Seg[] => l.segs ?? [{ text: l.text }]
56 const drawn = (l: PaneLine) => segsOf(l).map((x, j) => <Text key={'g' + j} {...drawSeg(x)} wrap="truncate">{x.text}</Text>)
57 // a line with no segments is the blank (drawn as a one-cell Text: an empty Text takes no row); every other line is a row of segments
58 const plainLine = (l: PaneLine, i: number, k = '') => l.segs !== undefined
59 ? <Box key={k + 'l' + i} flexWrap={l.wrap === true ? 'wrap' : undefined}>{l.segs.map((s, j) => <Text key={'g' + j} {...drawSeg(s)} wrap={l.wrap === true ? 'wrap' : 'truncate'}>{s.text}</Text>)}</Box>
60 : <Text key={k + 'l' + i} wrap="truncate">{l.text === '' ? ' ' : l.text}</Text>
61 // a line with pressable segments (the 待決 option row and send row): consecutive segments of one `press` id are one Button, the rest plain Text. Without Button it is plain.
62 const pressLine = (l: PaneLine, i: number, k: string) => {
63 const runs: { press: string | undefined; segs: Seg[] }[] = []
64 for (const s of l.segs as Seg[]) {
65 const last = runs[runs.length - 1]
66 if (last !== undefined && last.press === s.press) last.segs.push(s)
67 else runs.push({ press: s.press, segs: [s] })
68 }
69 return (
70 <Box key={k + 'p' + i} flexWrap="wrap">
71 {runs.map((r, j) => {
72 const texts = r.segs.map((s, n) => <Text key={'g' + n} {...drawSeg(s)} wrap="truncate">{s.text}</Text>)
73 return r.press === undefined || Button === undefined || decide === null
74 ? <Box key={'r' + j}>{texts}</Box>
75 : <Button key={r.press} plain onPress={() => decide.onPress(r.press as string)}>{texts}</Button>
76 })}
77 </Box>
78 )
79 }
80 // a text-field line: the label, then the Input (what is typed is the owner's note, kept by the host under the field's key)
81 const fieldLine = (l: PaneLine, i: number, k: string) => {
82 const f = l.field as NonNullable<PaneLine['field']>
83 return (
84 <Box key={k + 'f' + i}>
85 {l.segs === undefined ? null : l.segs.map((s, j) => <Text key={'g' + j} {...drawSeg(s)} wrap="truncate">{s.text}</Text>)}
86 {Input === undefined || decide === null ? null : <Input key={f.key} placeholder={f.placeholder} value={f.value} onInput={(v: string) => decide.onNote(f.key, v)} onSubmit={(v: string) => decide.onNote(f.key, v)} />}
87 </Box>
88 )
89 }
90 // a line that carries a `toggle` id is a Button when the surface has them (a press expands / collapses its group), the plain line otherwise
91 const line = (l: PaneLine, i: number, k = '') => l.field !== undefined && l.segs !== undefined
92 ? fieldLine(l, i, k)
93 : l.segs !== undefined && (l.kind === 'choice' || l.segs.some(x => x.press !== undefined))
94 ? pressLine(l, i, k)
95 : l.toggle !== undefined && Button !== undefined
96 ? <Button key={k + 'b' + i} plain onPress={() => onToggle(l.toggle as string)}>{drawn(l)}</Button>
97 // a line that carries a `goto` tab (a projection row, design plan §2.3) is a Button that opens that tab
98 : l.goto !== undefined && Button !== undefined
99 ? <Button key={k + 'g' + i} plain onPress={() => onTab(l.goto as PaneTab)}>{drawn(l)}</Button>
100 : plainLine(l, i, k)
101 const strip = tabStrip(el, tab, onTab, onNext, snap, t, cols)
102 if (snap === null) {
103 return (
104 <Box flexDirection="column">
105 {strip}
106 <Text {...dimProps()}>{t('pane.waiting')}</Text>
107 </Box>
108 )
109 }
110 // the global header (design plan §2.2): drawn here, once, on every tab; no tab builder emits it (I9)
111 // (pane.overflow: this site's own scroll state, so the one thing allowed to differ between tabs: the last metrics line may end with the overflow hint)
112 const body: PaneLine[] = tab === 'legend' ? legendLines(ctx) : tab === 'now' ? nowLines(snap, ctx) : tab === 'decide' ? decideTabLines(snap, ctx) : tab === 'review' ? reviewTabLines(snap, ctx) : tab === 'spend' ? spendTabLines(snap, ctx) : tab === 'hygiene' ? hygieneTabLines(snap, ctx) : dispatchLines(snap, ctx)
113 const link = tab === 'dispatch' && snap.link !== null
114 const stripH = stripOf(snap, ctx, tab, Button !== undefined)
115 const plainHead = headerLines(snap, ctx)
116 // the 待決 tab is a scrolling window of its own (design plan §12.10): the strip and the header stay, the cards scroll, the send row sits in the fixed action strip under a rule
117 if (win !== null) win.framed = false // set again by the frame; a plain tree leaves ui.scroll to the engine
118 if (tab === 'decide' && scroll !== null && win !== null && snap.band !== null) {
119 const cards = body.filter(l => l.bar !== true)
120 const barLines = body.filter(l => l.bar === true)
121 keyedGrow(win, snap.pending.map(d => d.id ?? d.question))
122 return scrollFrame(el, {
123 rows: scroll.bodyRows, cols, head: [strip, ...plainHead.map((l, i) => line(l, i, 'h'))], headRows: stripH.rows + plainHead.length,
124 total: cards.length, window: (off, room) => cards.slice(off, off + room).map((l, i) => line(l, off + i)),
125 bar: barLines.map((l, i) => line(l, i, 'bar')), barRows: barLines.length, model: win,
126 })
127 }
128 const head = withOverflowHint(plainHead, ctx, scroll, treeRowCount(stripH.rows, plainHead, body, link ? 1 : 0), stripH.exact).map((l, i) => line(l, i, 'h'))
129 return (
130 <Box flexDirection="column">
131 {strip}
132 {head}
133 {body.map((l, i) => line(l, i))}
134 {link ? <Link href={snap.link as string} label={t('dispatch.link')} /> : null}
135 </Box>
136 )
137}
138mods/live/scroll.tsx 66 lines1// mods/live/scroll.tsx — the one scrolling window both panes use: the viewer window and the live 待決 tab (design plan §12.10).
2//
3// The engine scrolls a pane by moving a window over the whole tree it was handed, which carries the pane's own header and any button row along. A tab that needs its buttons in
4// view while its content scrolls draws its own window instead: the pane body is exactly `bodyRows` rows high (read from `e.props.scroll.bodyRows`), made of a fixed head, a content
5// window the mod cuts itself, one rule and a fixed action strip. The person's scroll keys reach `ui.scroll`; the mod moves its own offset there and never calls `next`, so the
6// engine's window stays at 0. One blank row is drawn under the frame so the tree is one row taller than the window, which is what makes the engine raise `ui.scroll` at all.
7//
8// The cost of drawing the rows ourselves is that every content row must be exactly one row: a line wider than the room is cut (no wrapping), the caller pre-wraps what must wrap.
9// Colour: the track is the `structure` role, the thumb the `here` role (you are here), the rule `structure`; text colour only. Glyphs: GLYPHS.scrollbar and GLYPHS.structure.rule
10// Five track cells (top, quarter, middle, three quarters, bottom: scrollmath.jumpCells) are plain Buttons (no chrome, the Text child keeps its colour); a click on one jumps the window (scrollmath.jumpOffset). The host has no prop to keep a Button out of
11// the Tab ring, so the keyboard walk gains one stop per jump cell (five); the click is the pointer path, the keys scroll as before.
12// (ui.ts owns every glyph; ui-lint L2 keeps literals out of this file).
13import { GLYPHS, PALETTE } from './ui'
14import { jumpCells, jumpOffset, roomOf, thumbOf } from './scrollmath'
15import type { ScrollModel } from './scrollmath'
16export * from './scrollmath'
17
18type El = (props: any) => any
19
20export type FrameOptions = {
21 rows: number // the pane body's rows (props.scroll.bodyRows)
22 cols: number // the pane body's columns (props.bodyColumns)
23 head: unknown[] // the fixed top: already drawn nodes
24 headRows: number // how many rows they take
25 total: number // content rows in all
26 window: (offset: number, room: number) => unknown[] // the nodes for content rows offset .. offset + room, one row each (a node may hold several rows of one block)
27 bar: unknown[] // the fixed action strip under the rule
28 barRows: number
29 model: ScrollModel
30}
31
32export function scrollFrame(el: { Box: El; Text: El; Button?: El }, o: FrameOptions) {
33 const { Box, Text, Button } = el
34 const room = roomOf(o)
35 o.model.max = Math.max(0, o.total - room)
36 o.model.room = room
37 o.model.framed = true
38 o.model.offset = Math.min(o.model.offset, o.model.max)
39 const off = o.model.offset
40 const th = thumbOf(o.total, room, off)
41 const cells: unknown[] = []
42 const jumps = new Set(jumpCells(room))
43 if (th !== null) {
44 for (let i = 0; i < room; i++) {
45 const on = i >= th.top && i < th.top + th.len
46 const glyph = <Text key={'sb' + i} color={on ? PALETTE.here : PALETTE.structure}>{on ? GLYPHS.scrollbar.thumb : GLYPHS.scrollbar.track}</Text>
47 // only the five jump cells (jumpCells) are Buttons: a click jumps the window to that share of the track (jumpOffset); the other cells stay plain Text, as does every cell on a host with no Button
48 cells.push(Button === undefined || !jumps.has(i) ? glyph : <Button key={'sbj' + i} plain onPress={() => { o.model.offset = jumpOffset(i, room, o.model.max); o.model.redraw?.() }}>{glyph}</Button>)
49 }
50 }
51 return (
52 <Box key="frame" flexDirection="column">
53 <Box key="fixed" flexDirection="column" height={o.rows} overflow="hidden">
54 {o.head}
55 <Box key="content" flexDirection="row" flexGrow={1} overflow="hidden">
56 <Box key="rows" flexDirection="column" flexGrow={1} overflow="hidden">{o.window(off, room)}</Box>
57 {th === null ? null : <Box key="scrollbar" flexDirection="column" width={1} flexShrink={0}>{cells}</Box>}
58 </Box>
59 <Text key="rule" color={PALETTE.structure}>{GLYPHS.structure.rule.repeat(Math.max(1, o.cols))}</Text>
60 {o.bar}
61 </Box>
62 <Text key="spare"> </Text>
63 </Box>
64 )
65}
66mods/viewer/show.ts 158 lines1// mods/viewer/show.ts — what the `show` tool does: read a file (or run `git diff` by argv), remember what the window draws, open the window, and say in ONE line what was shown.
2// Lives apart from register.ts so the live mod's pressable file paths can call it directly: `$.tool.call` of a plugin's own tool is not served to the same plugin
3// (the engine answers "no tool.call hook answered this call"), so a press in the live pane cannot go through the tool; it calls `showPath` instead.
4
5import type { EngineInterface } from 'claude-code'
6
7import { resolveLocale } from '../live/i18n'
8import type { Locale } from '../live/i18n'
9import { MAX_FILE_BYTES, TAIL_LINES, diffView, startAbove, fileView, gitDiffArgv, nextStart, prevStart, splitLines, summaryOfDiff, summaryOfEmpty, summaryOfFile } from './model'
10import type { DiffView, FileView, ShowRequest } from './model'
11import type { Shown } from './pane'
12import { resetAssist } from './assist'
13import { makeVT } from './strings'
14
15export const PANE_ID = 'autopilot-viewer'
16export const TOOL_NAME = 'show'
17export const TOOL_FULL = 'mcp__autopilot__show'
18
19export const TOOL_DESCRIPTION =
20 'Show a file or a git diff to the USER in a window on their screen. Use it when the user asks to see, open or look at a file or a diff, instead of reading it and retyping it. ' +
21 'The content is displayed to the user only and is NOT returned to you: you get one line saying what was shown. If you need to analyze the content yourself, read the file or run the diff separately. ' +
22 'Give exactly one of: path (optionally start and end, 1-based inclusive line numbers), or diff (the arguments after "git diff", one string each, e.g. ["HEAD~1"] or ["HEAD~1", "--", "src/a.ts"]).'
23
24export const TOOL_SCHEMA = {
25 type: 'object',
26 properties: {
27 path: { type: 'string', description: 'File to show (absolute, or relative to the working directory).' },
28 start: { type: 'integer', minimum: 1, description: 'First line to show (with path).' },
29 end: { type: 'integer', minimum: 1, description: 'Last line to show (with path).' },
30 diff: { type: 'array', items: { type: 'string' }, description: 'Arguments of git diff, e.g. ["HEAD~1"] or ["--", "path"].' },
31 },
32}
33
34export type Current = { shown: Shown; title: string; text: string | null; locale: Locale } // text: the whole file, or the whole `git diff` output (what the summary reads)
35let current: Current | null = null
36export const currentView = (): Current | null => current
37export const setCurrentView = (c: Current): void => { current = c }
38
39// Same inputs as the live mod's resolveT (config ui.locale > AUTOPILOT_LOCALE > Claude Code language > LC_ALL / LANG > en), with the literal names the engine's analysis wants.
40async function localeOf($: EngineInterface): Promise<Locale> {
41 const home = await $.env.get('HOME').catch(() => undefined)
42 let ui: unknown
43 if (home) {
44 try {
45 const cfg = JSON.parse(String(await $.fs.read(home + '/.autopilot/config.json')))
46 ui = cfg && typeof cfg === 'object' ? (cfg as { ui?: { locale?: unknown } }).ui?.locale : undefined
47 } catch (_e) { /* no config: fall through */ }
48 }
49 const envLocale = await $.env.get('AUTOPILOT_LOCALE').catch(() => undefined)
50 const lang = (await $.env.get('LC_ALL').catch(() => undefined)) || (await $.env.get('LANG').catch(() => undefined))
51 let language: string | null = null
52 if (ui !== 'en' && ui !== 'zh-TW' && envLocale !== 'en' && envLocale !== 'zh-TW') {
53 try {
54 const rows = await $.config.list()
55 const row = rows.find(r => r.key === 'language')
56 if (row && typeof row.value === 'string') language = row.value
57 } catch (_e) { /* settings menu unreadable */ }
58 if (language === null && home) {
59 try {
60 const s = JSON.parse(String(await $.fs.read(home + '/.claude/settings.json')))
61 if (s && typeof s.language === 'string') language = s.language
62 } catch (_e) { /* none */ }
63 }
64 }
65 return resolveLocale({ config: ui, env: envLocale, language, lang })
66}
67
68async function cwdPath($: EngineInterface, p: string): Promise<string> {
69 return p.startsWith('/') ? p : (await $.session.cwd()).replace(/\/+$/, '') + '/' + p
70}
71
72// Open (or retitle) the window; the answer says whether it was drawn. Measured on Claude Code 2.1.302 (docs/plans/evidence/2026-10-17-viewer/README.md): an open that answers the
73// person's typed command is placed at any width; an open from a pressed Button is placed at any width ONLY when it is made in the press's own turn (before the first await);
74// an open from the model's tool call is placed from 144 columns (110 once the person opened this id before) and waits undrawn below that.
75async function openWindow($: EngineInterface, title: string): Promise<boolean> {
76 const r = await $.ui.open({ id: PANE_ID, title, focus: true, closeOnEscape: true, holdToasts: true, rows: WINDOW_ROWS, columns: WINDOW_COLUMNS })
77 return r.isPlaced
78}
79
80// the size the window asks for (a request, not a grant: the engine gives what the layout spares, and a size the owner dragged wins): tall inline above the prompt, wide when docked
81const WINDOW_ROWS = 30
82const WINDOW_COLUMNS = 100
83
84export type ShowOutcome = { ok: true; summary: string; title: string; placed: boolean } | { ok: false; why: string }
85export type ShowOpts = { openFirst?: boolean } // true for a press: open the window before the first await (see openWindow)
86
87const titleOf = (req: ShowRequest): string => (req.kind === 'path' ? req.path : 'git diff ' + req.args.join(' '))
88
89// Do one request: read, remember what the window draws, open it. The returned `summary` is the only text meant for the model.
90export async function show($: EngineInterface, req: ShowRequest, opts: ShowOpts = {}): Promise<ShowOutcome> {
91 const title = titleOf(req)
92 let early: Promise<boolean> | null = null
93 const before = current // what the window showed before a press-opened one: a failed open puts it back
94 if (opts.openFirst === true) {
95 current = { shown: { kind: 'loading' }, title, text: null, locale: current === null ? 'en' : current.locale }
96 $.ui.invalidate('ui.render')
97 early = openWindow($, title)
98 }
99 const fail = async (why: string): Promise<ShowOutcome> => {
100 if (early !== null) {
101 await early.then(() => $.ui.close({ id: PANE_ID })).catch(() => undefined)
102 current = before
103 }
104 return { ok: false, why }
105 }
106 const finish = async (shown: Shown, text: string | null, locale: Locale, summary: string): Promise<ShowOutcome> => {
107 current = { shown, title, text, locale }
108 resetAssist() // a new content: the previous answer and any running call go
109 $.ui.invalidate('ui.render')
110 const placed = await (early ?? openWindow($, title))
111 return { ok: true, summary: placed ? summary : summary + ' ' + WAITING_FOR_MODEL, title, placed }
112 }
113 const locale = await localeOf($)
114 if (req.kind === 'path') {
115 const abs = await cwdPath($, req.path)
116 let st
117 try { st = await $.fs.stat(abs) } catch (_e) { return fail('cannot read ' + req.path) }
118 if (st.kind !== 'file') return fail(req.path + ' is not a file')
119 if (st.size > MAX_FILE_BYTES) return fail(req.path + ' is over the 4 MiB limit')
120 let text: string
121 try { text = String(await $.fs.read(abs)) } catch (_e) { return fail('cannot read ' + req.path) }
122 if (text.includes('\0')) return fail(req.path + ' looks binary')
123 const view = fileView(req.path, text, req.tail === true ? Math.max(1, splitLines(text).length - TAIL_LINES + 1) : req.start, req.end)
124 if (view === null) return finish({ kind: 'empty', what: 'file' }, null, locale, summaryOfEmpty(req.path))
125 return finish(shownFile(view, req.end), text, locale, summaryOfFile(view))
126 }
127 let ran
128 try { ran = await $.process.run(gitDiffArgv(req.args)) } catch (_e) { return fail('git could not run') }
129 if (ran.exitCode !== 0) return fail('git diff failed: ' + (ran.stderr.split('\n')[0] || 'exit ' + ran.exitCode).slice(0, 200))
130 const d: DiffView = diffView(ran.stdout)
131 if (d.files === 0) return finish({ kind: 'empty', what: 'diff' }, null, locale, summaryOfEmpty(title))
132 return finish({ kind: 'diff', view: d }, ran.stdout, locale, summaryOfDiff(req.args, d))
133}
134
135export function shownFile(view: FileView, end: number | null): Shown {
136 const partLines = view.last - view.first + 1
137 const next = nextStart(view)
138 return { kind: 'file', view, prev: prevStart(view, partLines), next: end !== null && next !== null && next > end ? null : next }
139}
140
141// What the owner is told when a window the model asked for stayed undrawn (a terminal narrower than the engine's floor for an unasked pane): the `/show` command is the owner's own
142// open, which is placed at any width.
143export const WAITING_FOR_MODEL = 'The window did not open because the terminal is narrow; tell the user to type /show to open it.'
144
145// A file named by something the owner pressed (the live mod): open it a few lines above `line` (startAbove, so the line has something above it), or from the top. The window opens first (see openWindow); a failure is a toast.
146export async function showPath($: EngineInterface, path: string, line: number | 'end' | null): Promise<void> {
147 const out = await show($, { kind: 'path', path, start: typeof line === 'number' ? startAbove(line) : null, end: null, ...(line === 'end' ? { tail: true } : {}) }, { openFirst: true })
148 if (!out.ok) $.ui.toast(makeVT(current === null ? 'en' : current.locale)('viewer.failed', { why: out.why }))
149}
150
151// `/show` with nothing after it: draw the last window again (the owner's own open, so it is placed at any width)
152export async function reopenWindow($: EngineInterface): Promise<boolean> {
153 if (current === null) return false
154 $.ui.invalidate('ui.render')
155 await openWindow($, current.title)
156 return true
157}
158mods/live/model.ts 1973 lines1// mods/live/model.ts — pure helpers for the live mod (plan P1c). No `$` in here: every file read, every clock
2// read and every UI call stays in register.ts. Nothing in this file derives a number the producer already
3// published: counts, cost, context, the progress numbers and the decision are copied from the envelope / context
4// file / job model. The selections made here: the verdict word (a precedence over fields the producers already
5// published), the project short name, the earliest start and the quietest stalled run.
6// W3a: the per-session files (tasks, attention), the watcher sidecars (decisions, foreman, sources manifest) and the
7// campaign progress receipts are parsed here too; every sidecar carries its scope and a scope that is not the one
8// wanted is an absent file (same rule as checkEnvelope).
9// TUI v2: every user-visible word is an id in locales/{en,zh-TW}.json, resolved through a `t` this file receives as a parameter
10// (never imported as state), so tests call the layout with a fixed `t`. Glyphs, numbers, ids, paths, shas and commands stay literal.
11
12import { T_EN } from './i18n'
13import type { T } from './i18n'
14import * as ui from './ui' // the design system's builders; `ui.kv` etc. keep clear of this file's own legacy `kv` / `row`
15import * as U from './ui'
16import { GLYPHS, PALETTE, STATES, carry, cellWidth, displayWidth, isStale, stateOf } from './ui'
17const GS = GLYPHS.state
18const GT = GLYPHS.structure
19const GC = GLYPHS.chart
20import type { Ctx as UiCtx, Column as UiColumn, FactId, FmtKind, Frag, LineKind, RunSubject, SegRole, Stated, TableListRow as UiTableListRow } from './ui'
21
22
23// ---- the snapshot the tick builds and the band / pane draw (module state in register.ts) ----
24export type LivePaneRow = {
25 stall: boolean // the producer's own stall flag for this run (the Dispatch table draws it as the state)
26 run_id: string
27 role: string | null
28 runner: string | null
29 model: string | null
30 started_at: string | null
31 elapsed_s: number | null
32 phase: string | null
33 rc: number | null
34 final_status: string | null
35 probe_age_s: number | null
36 ended_at: string | null
37 // the producer's own end test (runs-watch computeCounts: phase exited, ended_at or final_status; an rc is an end too) and its own freshness test
38 // (confirmed_live: alive === true and a probe no older than counts.fresh_bound_s). A row the producer never probed is not `fresh`, and a row that
39 // ended without an rc and without a final_status is `ended` and not `fresh`, so it reads ◌ 已停 and never ● 執行中 (design plan §2.5, §3.3 run row 6)
40 ended: boolean
41 fresh: boolean
42 starting: boolean
43}
44
45export type LiveGateRow = {
46 phase: string | null
47 generation: number | null
48 verdict: string | null
49 status: string | null
50}
51
52// one open owner question (autopilot.decision/2 entry, as the job model carries it): the full context the owner needs to answer without scrolling back
53export type LiveDecision = {
54 id: string | null; question: string; background: string | null; options: { label: string; description: string }[]
55 recommendation: string | null; why: string | null; blocks: string | null; not_authorized: string | null; source: string | null; opened_at: string | null
56 stale: boolean; age_s: number | null
57 origin: string | null // `ask_user_question`: hooks/ask-decision.js opened it, the asker's own dialog answers it (the pane never does)
58 orphaned: boolean // the asking session left no turn file: it ended (or crashed) without answering; the watcher derives it, the entry is never removed by it
59}
60
61// `kind`, `fact`, `goto`, `group` and `ts` are stamped by the ui.ts components (the design system, docs/plans/2026-10-13-live-pane-design-system.md §6.1); `kind` and
62// `fact` are required: a line no component made does not type-check.
63export type PaneLine = { toggle?: string; text: string; dim?: boolean; bold?: boolean; warn?: boolean; color?: ThemeKey; segs?: Seg[]; wrap?: boolean; hang?: number; kind: LineKind; fact: FactId; goto?: PaneTab; group?: string; ts?: number; field?: { key: string; placeholder: string; value: string }; bar?: true }
64export type VerdictKind = 'decide' | 'stalled' | 'waiting' | 'running' | 'idle'
65// P4: the sections are DATA, the tab builders turn them into lines (design plan §7). attention = a permission / question the session waits on; the notes say why a
66// source has nothing to show (its writer is not wired); the rest is the source view as read.
67export type PaneSections = {
68 attention: AttentionView | null
69 attentionNotWired: boolean
70 tasks: TasksView | null
71 tasksNote: 'todo_hint' | 'not_wired' | null // why `tasks` is null
72 decisionsNotWired: boolean
73 foreman: ForemanView | null
74}
75export const NO_SECTIONS: PaneSections = { attention: null, attentionNotWired: false, tasks: null, tasksNote: null, decisionsNotWired: false, foreman: null }
76
77// The two band lines of an ok snapshot. Every ok band carries one of five words; the fifth, 待命, is the idle word.
78export type BandView = {
79 kind: VerdictKind
80 key: ThemeKey
81 why: string // the verdict's own reason, always set: the first item under 要你處理 when the verdict asks something of the owner, else the first row of 位置 (§2.2)
82 verdictReason: string | null // the one-phrase reason the wide band draws after a 要你決定 / 疑似卡住 verdict (null for the other verdicts)
83 mark: string
84 verdict: string
85 head: string // "<project> · <phase> · <elapsed> · " (the progress follows it)
86 progress: string
87 progressDim: boolean // no frozen denominator: 現況 adds 「沒有固定總數」 (§3.5, never `N*`)
88 reason: string | null
89 project: string // P7 Now tab row: verdict + project + elapsed; progress and phase are their own lines
90 elapsed: string
91 phase: string
92 slots: Slot[] // P7: the one-line band's slots in priority order (width-independent; layoutBand applies the width table)
93}
94
95export type LiveSnapshot = {
96 // ok | stale | unavailable | unreadable | no-pointer | no-project
97 state: 'ok' | 'stale' | 'unavailable' | 'unreadable' | 'no-pointer' | 'no-project'
98 // the exact band text (an ok snapshot: line 1, then the reason on its own line)
99 text: string
100 band: BandView | null // set for state ok only
101 // the state text of a non-ok snapshot; for an ok one the legacy one-line "session / host / ctx" text (the pane draws the verdict header from `band` and `metrics`)
102 header: string
103 // the context figure of the global header (`22%`, `—`); the two spend figures come from `detail.spend` (undefined = a snapshot built without it)
104 metrics?: { ctx: string }
105 // what is awaited from the human, from the job model's decisions list, oldest first ([] = nothing awaited)
106 pending: LiveDecision[]
107 project_key: string | null
108 root_run_id: string | null
109 // page the Link in the pane points at (null until an envelope was found)
110 link: string | null
111 // pane data, copied from the envelope / the review job model; null = not published
112 rows: LivePaneRow[] | null
113 gates: LiveGateRow[] | null
114 // W3a pane sections, text already built from the sources (empty = nothing to say)
115 sections: PaneSections
116 // P7d: plan-review state + latest code-review round of this project (null = none published)
117 review: ReviewView | null
118 published_at: string | null
119 session_as_of: string | null
120 host_as_of: string | null
121 // P7: the facts the panel's tabs draw (null = the fact is not published: the tab says "no data")
122 detail: PaneDetail
123 // the last RECENT_MAX prompts of this session, each with its reply (null / [] = nothing available; undefined = a snapshot built without the tick)
124 recent?: RecentGroup[] | null
125 // what the session left running in the background: shell commands, Monitor watches, subagents (null / [] = none; undefined = no tick)
126 activity?: ActivityItem[] | null
127 // the logged-in Claude account and its rate-limit windows (undefined = no tick)
128 account?: AccountSnap
129}
130
131export type SpendView = { session: string; host_all: string; host_all_n: number | null; brain: number | null; cap: number | null; mode: string; hourly?: number[] | null }
132export type PaneDetail = {
133 counts: Counts | null // the envelope's dispatch counts (merged over the root set); null = not published
134 stalled: number // stalled runs + a stalled foreman (the band's ⊘ count)
135 now_ms: number | null
136 project: string | null
137 marker: MarkerView | null
138 qc: QcView | null
139 stage: StageWalkView | null
140 decisions: DecisionsView | null
141 load_source: LoadSourceView | null
142 residue: ResidueView | null
143 spend: SpendView | null
144}
145export const NO_DETAIL: PaneDetail = { counts: null, stalled: 0, now_ms: null, project: null, marker: null, qc: null, stage: null, decisions: null, load_source: null, residue: null, spend: null }
146
147// ---- the host-wide spend history (<live>/runs/spend-history.json, schema autopilot.spend-history/1) -> the Spend tab's hourly sparkline ----
148export const SPEND_HISTORY_SCHEMA = 'autopilot.spend-history/1'
149export const SPARK_BARS = GLYPHS.spark.join('')
150const HOUR_MS = 3600 * 1000
151export const SPEND_BUCKETS = 24
152export type SpendSample = { ms: number; usd: number }
153export function readSpendHistory(text: string | null): SpendSample[] | null {
154 if (text === null) return null
155 const parsed = parseJson(text)
156 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== SPEND_HISTORY_SCHEMA || !Array.isArray(parsed.value.samples)) return null
157 const out: SpendSample[] = []
158 for (const x of parsed.value.samples) {
159 if (!isObject(x) || typeof x.at !== 'string' || !finite(x.usd) || x.usd < 0) continue
160 const ms = Date.parse(x.at)
161 if (Number.isFinite(ms)) out.push({ ms, usd: x.usd })
162 }
163 return out.sort((a, b) => a.ms - b.ms)
164}
165
166// The last 24 hourly buckets (oldest first, the current hour last) of spend ADDED per hour. A sample's usd is the cumulative figure since the host's
167// "today" began (scripts/lib/brain-spend.js sums UTC-day rows: its header, `todayPrefix` and `todaySpend`), but the rule here does not depend on where
168// that boundary is: delta = cur >= prev ? cur - prev : cur, so a reset yields the new cumulative value, never a spike or a zero. A baseline more than
169// 1 h older than the sample is unknown (a watcher gap): that sample adds no bar; the very first sample has no baseline and adds none. The delta lands
170// in the bucket of the sample that shows it. Fewer than 2 samples inside the window -> null (no sparkline).
171export const SPEND_BASELINE_MAX_MS = HOUR_MS
172export function hourlySpend(samples: SpendSample[] | null, nowMs: number): number[] | null {
173 if (samples === null) return null
174 const endHour = Math.floor(nowMs / HOUR_MS)
175 const startHour = endHour - (SPEND_BUCKETS - 1)
176 const buckets: number[] = new Array(SPEND_BUCKETS).fill(0)
177 let inWindow = 0
178 samples.forEach((cur, i) => {
179 const h = Math.floor(cur.ms / HOUR_MS)
180 if (h < startHour || h > endHour) return
181 inWindow += 1
182 if (i === 0) return
183 const prev = samples[i - 1]
184 if (cur.ms - prev.ms > SPEND_BASELINE_MAX_MS) return
185 buckets[h - startHour] += cur.usd >= prev.usd ? cur.usd - prev.usd : cur.usd
186 })
187 return inWindow >= 2 ? buckets : null
188}
189
190// `▁▂▃▄▅▆▇█`, one cell per bucket scaled to the peak; an all-zero window is a flat floor
191export function sparkText(values: number[]): string {
192 const peak = Math.max(...values)
193 return values.map(v => SPARK_BARS[peak <= 0 ? 0 : Math.min(SPARK_BARS.length - 1, Math.round((v / peak) * (SPARK_BARS.length - 1)))]).join('')
194}
195
196export const SNAPSHOT_SCHEMA = 'autopilot.runs-live/1'
197export const MODEL_SCHEMA = 'review-job-model/1'
198export const POINTER_SCHEMA = 'autopilot.live-pointer/1'
199export const DEFAULT_VALID_FOR_S = 180
200export const CONTEXT_MAX_AGE_MS = 120000
201export const DEFAULT_REVIEW_PORT = 8787
202export const RUNS_HINT = 'autopilot status runs --watch'
203
204export type Json = Record<string, unknown>
205
206export const isObject = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
207export const isKey = (v: unknown): v is string => typeof v === 'string' && /^[0-9a-f]{16}$/.test(v)
208
209// -> { ok, value }: ok false = not JSON (malformed), never throws.
210export function parseJson(text: string): { ok: true; value: unknown } | { ok: false } {
211 try {
212 return { ok: true, value: JSON.parse(text) }
213 } catch (_e) {
214 return { ok: false }
215 }
216}
217
218// Same rule as src/status/runs-watch.js safeSegment: it names the per-root envelope file and the job directory.
219export function safeSegment(value: string): string {
220 return String(value).replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 96) || '_'
221}
222
223export function scopeKeyOf(projectKey: string, root: string | null): string {
224 return root ? projectKey + '--' + safeSegment(root) : projectKey
225}
226
227export function hhmm(ms: number): string {
228 const d = new Date(ms)
229 return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0')
230}
231
232export const usd = (n: unknown): string => (typeof n === 'number' && Number.isFinite(n) ? '$' + n.toFixed(2) : '$—')
233
234// Longest path-boundary prefix of `real` among the merged runs/paths maps; -> project_key | null.
235export function longestPrefixKey(real: string, maps: Json[]): string | null {
236 let best: { len: number; key: string } | null = null
237 for (const map of maps) {
238 for (const p of Object.keys(map)) {
239 const entry = map[p]
240 if (!isObject(entry) || !isKey(entry.project_key)) continue
241 const base = p.length > 1 ? p.replace(/\/+$/, '') : p
242 const hit = real === base || real.startsWith(base === '/' ? '/' : base + '/')
243 if (hit && (best === null || base.length > best.len)) best = { len: base.length, key: entry.project_key }
244 }
245 }
246 return best === null ? null : best.key
247}
248
249export type EnvelopeCheck = { status: 'missing' | 'malformed' | 'fresh' | 'stale'; envelope: Json | null }
250
251// readEnvelope's contract (src/status/runs-watch.js): a wrong schema or a scope that is not the one wanted is a
252// MISSING file; fresh depends on published_at alone, never on when the mod read the file.
253export function checkEnvelope(text: string | null, want: { project_key: string; root_run_id: string | null }, nowMs: number): EnvelopeCheck {
254 if (text === null) return { status: 'missing', envelope: null }
255 const parsed = parseJson(text)
256 if (!parsed.ok) return { status: 'malformed', envelope: null }
257 const env = parsed.value
258 if (!isObject(env) || env.schema !== SNAPSHOT_SCHEMA || !isObject(env.scope)) return { status: 'missing', envelope: null }
259 const sameRoot = (typeof env.scope.root_run_id === 'string' ? env.scope.root_run_id : null) === want.root_run_id
260 if (env.scope.project_key !== want.project_key || !sameRoot) return { status: 'missing', envelope: null }
261 const publishedMs = typeof env.published_at === 'string' ? Date.parse(env.published_at) : NaN
262 const validFor = typeof env.valid_for_s === 'number' && Number.isFinite(env.valid_for_s) ? env.valid_for_s : DEFAULT_VALID_FOR_S
263 if (!Number.isFinite(publishedMs) || nowMs - publishedMs > validFor * 1000) return { status: 'stale', envelope: env }
264 return { status: 'fresh', envelope: env }
265}
266
267const rowsOf = (env: Json): Json[] | null => (Array.isArray(env.runs) ? env.runs.filter(isObject) : null)
268const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
269const startedMs = (r: Json): number => Date.parse(String(r.started_at || r.fact_at || ''))
270
271// the band's verdict mark and colour come from the design system's state table: the five owner-approved words map onto states (§3.2)
272const VERDICT_MARK = Object.fromEntries((['decide', 'stalled', 'waiting', 'running', 'idle'] as const).map(k => {
273 const st = STATES[stateOf('verdict', k).id]
274 return [k, { mark: st.glyph, key: st.key }]
275})) as Record<VerdictKind, { mark: string; key: ThemeKey | undefined }>
276export const verdictOf = (kind: VerdictKind, t: T): { kind: VerdictKind; mark: string; word: string; key: ThemeKey | undefined } => ({ kind, mark: VERDICT_MARK[kind].mark, word: t('verdict.' + kind), key: VERDICT_MARK[kind].key })
277
278// "<project>": the last directory of a normal repo's git common dir. Any other shape (bare repo, no prefix, a path
279// inside .git, empty) falls back to the first 8 hex of the project key. Pure string work: never git, never a hash.
280export function projectName(identity: unknown, projectKey: string): string {
281 const fallback = projectKey.slice(0, 8)
282 const PREFIX = 'git-common-dir:'
283 if (typeof identity !== 'string' || !identity.startsWith(PREFIX)) return fallback
284 const dir = identity.slice(PREFIX.length).replace(/\/+$/, '')
285 if (!dir.endsWith('/.git')) return fallback
286 const name = dir.slice(0, -'/.git'.length).split('/').pop()
287 return name ? name : fallback
288}
289
290// "38m" / "2h14m" / "1d03h" (ui.dur, the one duration format): now minus the start of this piece of work; no start -> an em dash.
291export function elapsedFrom(startMs: number | null, nowMs: number): string {
292 if (startMs === null || !Number.isFinite(startMs) || !Number.isFinite(nowMs) || nowMs < startMs) return '—'
293 const minutes = Math.floor((nowMs - startMs) / 60000) // the band's elapsed never shows seconds
294 return minutes < 1 ? '0m' : ui.dur(minutes * 60000)
295}
296
297// the earliest start among the scope's runs (null: none has one)
298export function earliestRunMs(env: Json): number | null {
299 let earliest = Infinity
300 for (const r of rowsOf(env) || []) {
301 const ms = Date.parse(String(r.started_at || ''))
302 if (Number.isFinite(ms) && ms < earliest) earliest = ms
303 }
304 return earliest === Infinity ? null : earliest
305}
306
307// "seconds ago" in the same shorthand as the band: 45s / 20m / 3h5m / 2d1h
308export function ageText(s: number): string {
309 if (!Number.isFinite(s) || s < 0) return '—'
310 return ui.dur(s * 1000)
311}
312
313export type JobProgress = { frozen: boolean; percent: number | null; done: number | null; total: number | null }
314
315// frozen: "62.5%(5/8)" (the percent as the job model published it). Not frozen: "3 done" with dim set, so 現況 names the missing total. No count: an em dash.
316export function progressView(p: JobProgress | null, t: T = T_EN): { text: string; dim: boolean } {
317 if (p === null) return { text: '—', dim: false }
318 if (p.frozen && p.percent !== null && p.done !== null && p.total !== null) return { text: t('progress.frozen', { pct: p.percent, done: p.done, total: p.total }), dim: false }
319 if (p.done !== null) return { text: t('progress.unfrozen', { n: p.done }), dim: true }
320 return { text: '—', dim: false }
321}
322
323// The stalled rows are the ones the producer flagged (`stall: true`); the age is the producer's last_event_age_s.
324export function stalledReason(env: Json, t: T = T_EN): string | null {
325 const stalled = (rowsOf(env) || []).filter(r => r.stall === true)
326 if (stalled.length === 0) return null
327 const ages = stalled.map(r => r.last_event_age_s).filter(finite)
328 if (ages.length === 0) return t('reason.stalled_count', { n: stalled.length })
329 return t('reason.stalled_age', { m: Math.floor(Math.max(...ages) / 60) })
330}
331
332// ---- W3a: the sources the band and pane read besides the envelope and the job model ----
333export const TASKS_SCHEMA = 'autopilot.session-tasks/1'
334export const ATTENTION_SCHEMA = 'autopilot.attention/1'
335export const TURN_SCHEMA = 'autopilot.session-turn/1'
336export const TURN_EFFECTIVE_SCHEMA = 'autopilot.session-turn-effective/1'
337export const DECISIONS_SCHEMA = 'autopilot.decisions-sidecar/1'
338export const FOREMAN_SCHEMA = 'autopilot.foreman-activity/1'
339export const SOURCES_SCHEMA = 'autopilot.sources/1'
340export const LOAD_SOURCE_SCHEMA = 'autopilot.load-source/1'
341export const NOT_WIRED_ID = 'nodata.not_wired'
342export const TODO_TOOLS_ID = 'tasks.todo_hint'
343
344// scripts/lib/live-state-dir.js sanitizeSessionId: every scalar outside [A-Za-z0-9_-] becomes one "_", first 64 scalars, empty -> unknown.
345export function sanitizeSid(raw: string): string {
346 if (raw.length === 0) return 'unknown'
347 const kept = Array.from(raw).slice(0, 64).map(ch => (/^[A-Za-z0-9_-]$/.test(ch) ? ch : '_')).join('')
348 return kept.length > 0 ? kept : 'unknown'
349}
350
351export type ScopeWant = { project_key: string; root_run_id: string | null }
352
353// a sidecar names the scope it was built for; any other scope is an absent file (the checkEnvelope rule)
354function scopeMatches(v: Json, want: ScopeWant): boolean {
355 const s = v.scope
356 if (!isObject(s)) return false
357 const root = typeof s.root_run_id === 'string' && s.root_run_id ? s.root_run_id : null
358 return s.project_key === want.project_key && root === want.root_run_id
359}
360
361const isCount = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0
362const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null)
363
364export type TasksView = {
365 total: number; completed: number; in_progress: number
366 current: string | null
367 first_created_ms: number | null
368 rows: { subject: string; status: string }[]
369}
370
371// <live>/tasks/<sid>.json (W1d). Counts are the writer's own (deleted tasks excluded there); another session's file is absent.
372export function readTasks(text: string | null, sid: string): TasksView | null {
373 if (text === null) return null
374 const parsed = parseJson(text)
375 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== TASKS_SCHEMA) return null
376 const v = parsed.value
377 if (typeof v.session_id === 'string' && v.session_id !== sid) return null
378 const c = v.counts
379 if (!isObject(c) || !isCount(c.total) || !isCount(c.completed) || !isCount(c.in_progress)) return null
380 const first = typeof v.first_created_at === 'string' ? Date.parse(v.first_created_at) : NaN
381 const rows = (Array.isArray(v.tasks) ? v.tasks : []).filter(isObject)
382 .map(t => ({ subject: str(t.subject) || '—', status: str(t.status) || 'pending' }))
383 .filter(t => t.status !== 'deleted')
384 return {
385 total: c.total, completed: c.completed, in_progress: c.in_progress,
386 current: isObject(v.current) ? str(v.current.subject) : null,
387 first_created_ms: Number.isFinite(first) ? first : null,
388 rows,
389 }
390}
391
392export type AttentionView = { kind: 'permission' | 'question' | 'idle'; summary: string; since_ms: number | null }
393
394// <live>/attention/<sid>.json (W1e): present only while the session waits. A file of another session / schema is absent.
395export function readAttention(text: string | null, sid: string): AttentionView | null {
396 if (text === null) return null
397 const parsed = parseJson(text)
398 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== ATTENTION_SCHEMA) return null
399 const v = parsed.value
400 if (typeof v.session_id === 'string' && v.session_id !== sid) return null
401 const kind = v.kind
402 if (kind !== 'permission' && kind !== 'question' && kind !== 'idle') return null
403 const since = typeof v.since === 'string' ? Date.parse(v.since) : NaN
404 return { kind, summary: str(v.summary) || '', since_ms: Number.isFinite(since) ? since : null }
405}
406
407export type TurnView = { state: 'active' | 'ended'; since_ms: number | null }
408// the session marker's TTL (scripts/session-mode.js DEFAULT_TTL_HOURS): a turn file older than that is a crashed session's leftover
409export const TURN_TTL_MS = 24 * 3600 * 1000
410
411// <live>/turn/<sid>.json (TURN): active while a prompt is being worked, ended after Stop. Another session / schema, no `since`
412// that parses, or one older than the marker TTL is absent (stale).
413// effectiveText = <live>/turn-effective/<sid>.json (GATEFIX2, watcher-owned): an Escape interrupt fires no Stop, so the watcher reads it
414// from the transcript and publishes `ended` for ONE turn (its `turn_since`). It ends an `active` turn only while the turn file's `since`
415// is that same value, so a newer UserPromptSubmit wins at once. Anything unreadable / foreign leaves the turn as the hook wrote it.
416export function readTurn(text: string | null, sid: string, nowMs: number, effectiveText: string | null = null): TurnView | null {
417 if (text === null) return null
418 const parsed = parseJson(text)
419 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== TURN_SCHEMA) return null
420 const v = parsed.value
421 if (typeof v.session_id === 'string' && v.session_id !== sid) return null
422 if (v.state !== 'active' && v.state !== 'ended') return null
423 const since = typeof v.since === 'string' ? Date.parse(v.since) : NaN
424 if (!Number.isFinite(since) || nowMs - since > TURN_TTL_MS) return null
425 if (v.state === 'active' && effectiveText !== null) {
426 const eff = parseJson(effectiveText)
427 if (eff.ok && isObject(eff.value) && eff.value.schema === TURN_EFFECTIVE_SCHEMA && eff.value.state === 'ended'
428 && (typeof eff.value.session_id !== 'string' || eff.value.session_id === sid) && eff.value.turn_since === v.since) return { state: 'ended', since_ms: since }
429 }
430 return { state: v.state, since_ms: since }
431}
432
433export type Manifest = Record<string, { installed: boolean; enabled: boolean } | undefined>
434
435// autopilot.sources/1 (WATCH-A): sidecar `<live>/runs/sources/<scope_key>.json`, or the job model's own copy.
436export function readManifest(value: unknown, want: ScopeWant): Manifest | null {
437 if (!isObject(value) || value.schema !== SOURCES_SCHEMA || !isObject(value.sources) || !scopeMatches(value, want)) return null
438 const out: Manifest = {}
439 for (const k of Object.keys(value.sources)) {
440 const e = value.sources[k]
441 if (isObject(e) && typeof e.installed === 'boolean' && typeof e.enabled === 'boolean') out[k] = { installed: e.installed, enabled: e.enabled }
442 }
443 return out
444}
445
446// The producer (scripts/render-review-page.js) writes a task-sourced phase as the zh-only `做:<subject>`. Strip that prefix and re-prefix from the locale table so an en session never shows Chinese.
447const TASK_PHASE_PREFIX = '做:'
448function phaseText(ph: { label: string; source: string | null }, t: T): string {
449 return ph.source === 'task' && ph.label.startsWith(TASK_PHASE_PREFIX) ? t('phase.task', { subject: ph.label.slice(TASK_PHASE_PREFIX.length) }) : ph.label
450}
451
452// true / false = the writer is / is not installed AND enabled; null = no manifest, or it does not name this source
453export function liveSource(m: Manifest | null, name: string): boolean | null {
454 if (m === null) return null
455 const e = m[name]
456 return e === undefined ? null : e.installed && e.enabled
457}
458
459// the manifest says none of these writers is live (every one is named, and every one is off)
460export function notWired(m: Manifest | null, names: string[]): boolean {
461 return names.every(n => liveSource(m, n) === false)
462}
463
464export type DecisionRow = { round: number | null; decision: string; irreversible: boolean; writer: string | null; decision_id: string | null; source: string | null; root: string | null; at?: string | null }
465export type LadderView = { rung: string; at: string }
466export type DecisionsView = { rows: DecisionRow[]; count: number; irreversible: number; writers: string[]; undocumented: number; identity: string | null; root: string | null; ladder: LadderView | null }
467
468// <live>/runs/<scope_key>.decisions.json (WATCH-B). The counts are the publisher's own.
469export function readDecisions(text: string | null, want: ScopeWant): DecisionsView | null {
470 if (text === null) return null
471 const parsed = parseJson(text)
472 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== DECISIONS_SCHEMA || !scopeMatches(parsed.value, want)) return null
473 const v = parsed.value
474 if (!isCount(v.count) || !isCount(v.irreversible_count) || !isCount(v.undocumented_dispatches) || !Array.isArray(v.writers_wired)) return null
475 const rows = (Array.isArray(v.rows) ? v.rows : []).filter(isObject).map(r => ({
476 round: Number.isInteger(r.round) ? (r.round as number) : null,
477 decision: str(r.decision) || '—',
478 irreversible: r.irreversible === true,
479 writer: str(r.writer), decision_id: str(r.decision_id), source: str(r.source), root: want.root_run_id,
480 at: typeof r.at === 'string' && Number.isFinite(Date.parse(r.at)) ? r.at : null, // kept for ordering: roots are concatenated, so position is not time across roots
481 }))
482 const scope = v.scope as Json
483 return {
484 rows, count: v.count, irreversible: v.irreversible_count, writers: v.writers_wired.filter((w): w is string => typeof w === 'string'),
485 undocumented: v.undocumented_dispatches, identity: str(scope.repo_identity), root: want.root_run_id,
486 ladder: readLadder(v.ladder),
487 }
488}
489
490// D2: the latest unknown-escalation rung the sidecar publishes (`{ rung: "U0".."U5", at }`); anything else is no ladder.
491export function readLadder(v: unknown): LadderView | null {
492 if (!isObject(v) || typeof v.rung !== 'string' || !/^U[0-5]$/.test(v.rung) || typeof v.at !== 'string' || !Number.isFinite(Date.parse(v.at))) return null
493 return { rung: v.rung, at: v.at }
494}
495
496// ---- P1W SCOPE: one session, several roots (the marker's job root + the campaigns it launched) ----
497// The band reads every root of the set and merges. Live counts, stall rows and proxy decisions are summed; the frozen
498// progress and the phase come from the NEWEST campaign root that has them (campaign roots are ordered oldest -> newest).
499
500// base's scope / sessions / host cost, every fresh envelope's runs concatenated and counts summed (an envelope with no
501// readable counts adds none; when no envelope has counts the base's are kept).
502export function mergeEnvelopes(base: Json, others: Json[]): Json {
503 if (others.length === 0) return base
504 const all = [base, ...others]
505 const runs: Json[] = []
506 let sum: Counts | null = null
507 for (const env of all) {
508 runs.push(...(rowsOf(env) || []))
509 const c = countsOf(env)
510 if (c !== null) sum = sum === null ? { ...c } : { confirmed_live: sum.confirmed_live + c.confirmed_live, exited: sum.exited + c.exited, unknown: sum.unknown + c.unknown }
511 }
512 const merged: Json = { ...base, runs }
513 if (sum !== null) merged.counts = { ...(isObject(base.counts) ? base.counts : {}), ...sum }
514 return merged
515}
516
517const isFrozenProgress = (p: JobProgress | null): p is JobProgress => p !== null && p.frozen && p.done !== null && p.total !== null
518
519// primary = the marker root's job model (or null), campaigns = the campaign roots' job models, oldest -> newest (absent ones left out).
520// Acceptance, gates and sources come from the primary (else the newest campaign); a decision awaited under ANY root is awaited;
521// progress = the newest campaign's frozen progress, phase = the newest campaign's phase, each falling back to the base's own.
522export function mergeJobModels(primary: JobModel | null, campaigns: JobModel[]): JobModel | null {
523 const newestFirst = [...campaigns].reverse()
524 const base: JobModel | null = primary !== null ? primary : (newestFirst[0] ?? null)
525 if (base === null) return null
526 const all = primary !== null ? [primary, ...campaigns] : campaigns
527 const asking = all.find(m => m.needs_decision)
528 const frozen = newestFirst.find(m => isFrozenProgress(m.progress))
529 const phased = newestFirst.find(m => m.phase !== null)
530 return {
531 ...base,
532 needs_decision: asking !== undefined,
533 // every root's page now carries the project's cards (src/status/decision-input.js): one card shows once
534 decisions: all.flatMap(m => m.decisions).filter((d, i, a) => d.id === null || a.findIndex(x => x.id === d.id) === i).sort((a, b) => (Date.parse(a.opened_at ?? '') || 0) - (Date.parse(b.opened_at ?? '') || 0)),
535 conclusion: asking !== undefined ? asking.conclusion : base.conclusion,
536 progress: frozen !== undefined ? frozen.progress : base.progress,
537 phase: phased !== undefined ? phased.phase : base.phase,
538 }
539}
540
541export function mergeDecisions(views: DecisionsView[]): DecisionsView | null {
542 const first = views[0]
543 if (first === undefined) return null
544 if (views.length === 1) return first
545 const writers: string[] = []
546 for (const v of views) for (const w of v.writers) if (!writers.includes(w)) writers.push(w)
547 return {
548 rows: views.flatMap(v => v.rows),
549 count: views.reduce((n, v) => n + v.count, 0),
550 irreversible: views.reduce((n, v) => n + v.irreversible, 0),
551 writers,
552 undocumented: views.reduce((n, v) => n + v.undocumented, 0),
553 identity: views.map(v => v.identity).find(i => i !== null) || null,
554 root: first.root,
555 ladder: views.map(v => v.ladder).filter((l): l is LadderView => l !== null).sort((a, b) => Date.parse(b.at) - Date.parse(a.at))[0] ?? null,
556 }
557}
558
559export type ForemanView = {
560 binding: string
561 agents: { id: string; description: string | null; label: string | null; at_ms: number | null; age_s: number | null; stale: boolean; stamped: boolean; ended: boolean }[]
562 stage: string | null; stage_source: string | null; stage_at_ms: number | null; stage_age_s: number | null
563}
564
565// <live>/runs/<scope_key>.foreman.json (WATCH-B): liveness ages only, never a verdict. Absent file = not wired.
566export function readForeman(text: string | null, want: ScopeWant): ForemanView | null {
567 if (text === null) return null
568 const parsed = parseJson(text)
569 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== FOREMAN_SCHEMA || !scopeMatches(parsed.value, want)) return null
570 const v = parsed.value
571 const ms = (x: unknown): number | null => { const n = typeof x === 'string' ? Date.parse(x) : NaN; return Number.isFinite(n) ? n : null }
572 const agents = (Array.isArray(v.agents) ? v.agents : []).filter(isObject).map(a => ({
573 id: str(a.agent_id) || '?', description: str(a.description), label: str(a.label),
574 at_ms: ms(a.last_activity_at), age_s: finite(a.age_s) ? a.age_s : null, stale: a.stale === true,
575 stamped: a.stamped === true, ended: ms(a.ended_at) !== null,
576 }))
577 return {
578 binding: str(v.binding) || 'session', agents,
579 stage: str(v.stage), stage_source: str(v.stage_source), stage_at_ms: ms(v.stage_at), stage_age_s: finite(v.stage_age_s) ? v.stage_age_s : null,
580 }
581}
582
583export const QC_SCHEMA = 'autopilot.qc-status/1'
584export type QcView = { state: 'ok' | 'owed' | 'not_needed' | 'unknown'; range: string | null; protected_files_count: number; evidence: 'trailer' | 'artifact' | null }
585
586// <live>/runs/<project_key>.qc.json (stage-graph P7c): the pre-push qc-gate decision for HEAD vs its upstream, re-derived by the watcher
587// (scripts/qc-evidence-status.js). Absent / foreign scope / unknown state = null (nothing to say).
588export function readQc(text: string | null, want: ScopeWant): QcView | null {
589 if (text === null) return null
590 const parsed = parseJson(text)
591 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== QC_SCHEMA || !scopeMatches(parsed.value, { project_key: want.project_key, root_run_id: null })) return null
592 const v = parsed.value
593 if (v.state !== 'ok' && v.state !== 'owed' && v.state !== 'not_needed' && v.state !== 'unknown') return null
594 return {
595 state: v.state, range: str(v.range), protected_files_count: isCount(v.protected_files_count) ? v.protected_files_count : 0,
596 evidence: v.evidence === 'trailer' || v.evidence === 'artifact' ? v.evidence : null,
597 }
598}
599
600// the review-slot chip: `QC✓` (evidence present), `QC▲` (protected diff, no evidence: it awaits a person); nothing owed or unknown = no chip
601export function qcChip(q: QcView | null): string | null {
602 if (q === null) return null
603 return q.state === 'ok' ? 'QC' + GS.done : q.state === 'owed' ? 'QC' + GS.need_you : null
604}
605
606// `git-common-dir:<abs path>` -> the path (only an absolute one); anything else -> null
607export function commonDirOf(identity: unknown): string | null {
608 if (typeof identity !== 'string' || !identity.startsWith('git-common-dir:')) return null
609 const dir = identity.slice('git-common-dir:'.length).replace(/\/+$/, '')
610 return dir.startsWith('/') && !dir.split('/').includes('..') ? dir : null
611}
612
613// the same root-name rule as src/status/work-order-progress.js: a root names a directory, so it must be a plain segment
614export const isPlainRoot = (root: string): boolean => /^[A-Za-z0-9._-]+$/.test(root) && root !== '.' && root !== '..'
615
616// Earliest `issued_at` of the controller progress receipts bound to `root` (W1a's binding rule: the receipt's own
617// root_run_id equals the root; a work-order file whose own top-level root_run_id is present and different is unbound).
618export function earliestReceiptMs(texts: string[], root: string): number | null {
619 let best = Infinity
620 for (const text of texts) {
621 const parsed = parseJson(text)
622 if (!parsed.ok || !isObject(parsed.value)) continue
623 const file = parsed.value
624 if (typeof file.root_run_id === 'string' && file.root_run_id !== root) continue
625 const list = isObject(file.controller) && Array.isArray(file.controller.progress_receipts) ? file.controller.progress_receipts : []
626 for (const r of list) {
627 if (!isObject(r) || r.artifact_type !== 'controller_progress_receipt' || r.root_run_id !== root) continue
628 const ms = typeof r.issued_at === 'string' ? Date.parse(r.issued_at) : NaN
629 if (Number.isFinite(ms) && ms < best) best = ms
630 }
631 }
632 return best === Infinity ? null : best
633}
634
635// Start of this piece of work, chosen by campaign-vs-session, not by "has a root" (every plain session carries a root since
636// PLAINROOT): the earliest bound progress receipt (a campaign has one; a session never does), else the tasks file's
637// first_created_at, else the marker's started_at, else the earliest run, else null (shown as an em dash).
638export function startMsOf(root: string | null, env: Json, tasks: TasksView | null, markerStartedAt: unknown, receiptMs: number | null): number | null {
639 if (root !== null && receiptMs !== null) return receiptMs
640 if (tasks !== null && tasks.first_created_ms !== null) return tasks.first_created_ms
641 const m = typeof markerStartedAt === 'string' ? Date.parse(markerStartedAt) : NaN
642 return Number.isFinite(m) ? m : earliestRunMs(env)
643}
644
645// P7b: <live>/load-source.json (machine-wide, not scope-bound): which copy of the plugin Claude Code loads. Watcher-published
646// (src/status/load-source.js); an absent / foreign-schema file reads as null (= no chip).
647export type LoadSourceView = {
648 plugin_version: string | null
649 source: string // "dev" | "cache:<semver>" | "unknown"
650 marketplace: string
651 marketplace_path: string | null
652 behind_upstream: number | null
653 flags: string[]
654 stale_cache_dirs: { dir: string; in_use_pids: string[]; alive: string[] }[]
655}
656export function readLoadSource(text: string | null): LoadSourceView | null {
657 if (text === null) return null
658 const parsed = parseJson(text)
659 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== LOAD_SOURCE_SCHEMA) return null
660 const v = parsed.value
661 const strs = (x: unknown): string[] => (Array.isArray(x) ? x.filter((y): y is string => typeof y === 'string') : [])
662 return {
663 plugin_version: str(v.plugin_version), source: str(v.source) || 'unknown', marketplace: str(v.marketplace) || 'missing', marketplace_path: str(v.marketplace_path),
664 behind_upstream: finite(v.behind_upstream) && Number.isInteger(v.behind_upstream) && v.behind_upstream >= 0 ? v.behind_upstream : null,
665 flags: strs(v.flags),
666 stale_cache_dirs: (Array.isArray(v.stale_cache_dirs) ? v.stale_cache_dirs : []).filter(isObject).map(d => ({ dir: str(d.dir) || '?', in_use_pids: strs(d.in_use_pids), alive: strs(d.alive) })),
667 }
668}
669
670// Narrow the watcher's conservative source with the session's own claude pid when the caller has one: a pid listed in a cache
671// dir's .in_use means THIS session loaded that copy; a pid listed in none means it loaded no cache copy (dev when the dev link
672// is sound, else unknown). How the mod learns its claude pid is [unverified]; register.ts passes null today, which keeps the
673// watcher's any-alive-pid reading.
674export function loadSourceFor(v: LoadSourceView, sessionPid: number | string | null): string {
675 if (sessionPid === null) return v.source
676 const pid = String(sessionPid)
677 for (const d of v.stale_cache_dirs) {
678 if (d.in_use_pids.includes(pid)) return 'cache:' + (d.dir.split('/').filter(x => x !== '').pop() || '?')
679 }
680 if (!v.source.startsWith('cache:')) return v.source
681 return v.flags.includes('dev_link_missing_or_stale') ? 'unknown' : 'dev'
682}
683
684// The hygiene slot's load-source chip: `dev` / `dev ↓3` (behind upstream by 3), `dev ▲` (the marketplace is not this repo's directory),
685// `cache 2.36.36 ▲` (a stale cache copy is what loads), `src ? ▲` (unknown). warn = the chip carries ▲ (the renderer picks the warning colour).
686export function hygieneChip(v: LoadSourceView | null, sessionPid: number | string | null = null): { text: string; warn: boolean } | null {
687 if (v === null) return null
688 const src = loadSourceFor(v, sessionPid)
689 const marketplaceBad = v.flags.includes('marketplace_not_directory') || v.flags.includes('marketplace_not_this_repo')
690 if (src.startsWith('cache:')) return { text: 'cache ' + src.slice('cache:'.length) + ' ' + GS.need_you, warn: true }
691 if (src === 'dev') {
692 const behind = v.behind_upstream !== null && v.behind_upstream > 0 ? ' ' + GT.behind + v.behind_upstream : ''
693 return { text: 'dev' + behind + (marketplaceBad ? ' ' + GS.need_you : ''), warn: marketplaceBad }
694 }
695 return { text: 'src ' + GS.unknown + ' ' + GS.need_you, warn: true }
696}
697
698export type Sources = {
699 tasks: TasksView | null
700 attention: AttentionView | null
701 turn: TurnView | null
702 decisions: DecisionsView | null
703 manifest: Manifest | null
704 foreman: ForemanView | null
705 loadSource?: LoadSourceView | null
706 marker?: MarkerView | null
707 review?: ReviewView | null
708 qc?: QcView | null
709 residue?: ResidueView | null
710 stage?: StageWalkView | null
711 quota?: readonly QuotaWindow[] | null
712 startMs: number | null
713}
714export const NO_SOURCES: Sources = { tasks: null, attention: null, turn: null, decisions: null, manifest: null, foreman: null, startMs: null }
715
716// P1W FOREMAN: a background foreman (a native subagent) leaves no manifest, task or turn behind, so its tool-call stamp is the only
717// sign it works. THE one stall bound: the same 180 s the dispatch stall uses (scripts/dispatch-status.js DEFAULT_STALL_SECS).
718export const FOREMAN_STALL_S = 180
719export type ForemanNow = { fresh: { name: string; age_s: number } | null; stalled: { age_s: number } | null }
720// Agents of the session that wrote a stamp, not ended (SubagentStop) and not older than the marker TTL. Un-ended and quiet under the
721// bound = fresh (the freshest one is named); un-ended and quiet at/over it = stalled (the quietest one sets the age).
722export function foremanNow(f: ForemanView | null, nowMs: number): ForemanNow {
723 const out: ForemanNow = { fresh: null, stalled: null }
724 if (f === null) return out
725 for (const a of f.agents) {
726 if (!a.stamped || a.ended || a.at_ms === null) continue
727 const ageMs = nowMs - a.at_ms
728 if (ageMs > TURN_TTL_MS) continue
729 const age_s = Math.max(0, Math.floor(ageMs / 1000))
730 if (age_s < FOREMAN_STALL_S) {
731 if (out.fresh === null || age_s < out.fresh.age_s) out.fresh = { name: a.description || a.label || a.id, age_s }
732 } else if (out.stalled === null || age_s > out.stalled.age_s) out.stalled = { age_s }
733 }
734 return out
735}
736
737// the band's ⊘ count: the producer's stalled runs plus a stalled foreman
738export function stalledCount(env: Json, foreman: ForemanView | null, nowMs: number): number {
739 return (rowsOf(env) || []).filter(r => r.stall === true).length + (foremanNow(foreman, nowMs).stalled !== null ? 1 : 0)
740}
741
742const waitingMinutes = (sinceMs: number | null, nowMs: number): number | null => (sinceMs === null ? null : Math.max(0, Math.floor((nowMs - sinceMs) / 60000)))
743
744// what the human is being waited on for, from the attention file (permission / question only)
745export function attentionReason(a: AttentionView, nowMs: number, t: T = T_EN): string {
746 const n = waitingMinutes(a.since_ms, nowMs)
747 return t((a.kind === 'permission' ? 'reason.permission' : 'reason.question') + (n === null ? '' : '_waited'), { summary: a.summary, n: n === null ? 0 : n })
748}
749
750// 「(已等 N 天)」: only the model's stale flag, only when a whole day has passed. 「(提問的 session 已結束)」: only the model's orphaned flag (the asker is gone,
751// nobody is waiting on this any more); the entry stays listed, closing it is the owner's `open-decision.js close --id`
752export function staleSuffix(d: LiveDecision | null, t: T = T_EN): string {
753 if (d === null) return ''
754 const orphan = d.orphaned ? t('decision.orphaned') : ''
755 if (!d.stale || d.age_s === null || d.age_s < 86400) return orphan
756 return t('decision.stale_days', { d: Math.floor(d.age_s / 86400) }) + orphan
757}
758
759// 僅自動裁決, worded from the writers the sidecar says are wired; next-pick is the depth-0 writer
760export function writersLabel(writers: string[], t: T = T_EN): string | null {
761 if (writers.includes('next-pick')) return null
762 return writers.length === 0 ? t('proxy.writers_none') : t('proxy.writers_only', { writers: writers.join(t('sep.list')) })
763}
764
765// band line 2 tail: the proxy decisions (only when non-zero) and the dispatches nobody wrote down
766export function proxySegments(d: DecisionsView | null, t: T = T_EN): string[] {
767 if (d === null) return []
768 const out: string[] = []
769 if (d.count > 0) {
770 out.push(t('proxy.decided', { n: d.count, irr: d.irreversible }))
771 const label = writersLabel(d.writers, t)
772 if (label !== null) out.push(label)
773 }
774 if (d.undocumented > 0) out.push(t('proxy.undocumented', { n: d.undocumented }))
775 return out
776}
777
778// Precedence: 1 needs a decision (attention permission / question, or an open decision), 2 stalled (a dispatch run, or an un-ended foreman quiet >= FOREMAN_STALL_S), 3 complete and
779// waiting acceptance (frozen progress done = total, or every session task completed; NO live run in scope and no un-ended fresh foreman), 4 running
780// (a live run, a fresh foreman, a session task in progress, or an active turn), 5 idle (the turn ended: nothing live, no task in progress).
781export function bandView(env: Json, jobModel: JobModel | null, projectKey: string, nowMs: number, src: Sources = NO_SOURCES, t: T = T_EN): BandView {
782 const counts = countsOf(env)
783 const progress = jobModel === null ? null : jobModel.progress
784 const stalled = stalledReason(env, t)
785 const noneLive = counts !== null && counts.confirmed_live === 0
786 const undecided = jobModel === null || (jobModel.acceptance !== 'accepted' && jobModel.acceptance !== 'rejected')
787 const frozenDone = progress !== null && progress.frozen && progress.done !== null && progress.total !== null && progress.done === progress.total
788 const tasksDone = src.tasks !== null && src.tasks.total > 0 && src.tasks.completed === src.tasks.total
789 const fm = foremanNow(src.foreman, nowMs)
790 const waiting = noneLive && undecided && ((frozenDone && jobModel !== null) || tasksDone) && fm.fresh === null
791 const taskRunning = src.tasks !== null && src.tasks.in_progress > 0
792 const turnActive = src.turn !== null && src.turn.state === 'active'
793 const awaiting = src.attention !== null && src.attention.kind !== 'idle' ? src.attention : null
794 let kind: VerdictKind
795 let reason: string | null = null
796 if (awaiting !== null || (jobModel !== null && jobModel.needs_decision)) {
797 kind = 'decide'
798 if (awaiting !== null) reason = attentionReason(awaiting, nowMs, t)
799 else if (jobModel !== null && jobModel.decisions.length > 0) reason = jobModel.decisions[0].question + staleSuffix(jobModel.decisions[0], t)
800 else reason = (jobModel !== null && jobModel.conclusion) || t('reason.decide_fallback')
801 } else if (stalled !== null) {
802 kind = 'stalled'
803 reason = stalled
804 } else if (fm.stalled !== null) {
805 kind = 'stalled'
806 reason = t('reason.foreman_stalled', { m: Math.floor(fm.stalled.age_s / 60) })
807 } else if (waiting) {
808 kind = 'waiting'
809 reason = frozenDone ? t('reason.waiting_verdict') : t('reason.waiting_tasks', { done: (src.tasks as TasksView).completed, total: (src.tasks as TasksView).total })
810 } else if ((counts !== null && counts.confirmed_live > 0) || fm.fresh !== null || taskRunning || turnActive) {
811 // GATEFIX / TURN: a live run, a session task in progress, or an active turn (the session is mid-work); the live run names itself first, then the task.
812 kind = 'running'
813 reason = counts !== null && counts.confirmed_live > 0
814 ? t('reason.running_dispatch', { n: counts.confirmed_live })
815 : fm.fresh !== null
816 ? t('reason.running_foreman', { name: fm.fresh.name, m: Math.floor(fm.fresh.age_s / 60) })
817 : taskRunning
818 ? (src.tasks !== null && src.tasks.current ? t('reason.running_task', { what: src.tasks.current }) : t('reason.running_tasks', { n: (src.tasks as TasksView).in_progress }))
819 : (() => { const n = waitingMinutes((src.turn as TurnView).since_ms, nowMs); return n === null ? t('reason.running_turn') : t('reason.running_turn_min', { n }) })()
820 } else {
821 kind = 'idle'
822 reason = t('reason.idle')
823 if (src.attention !== null && src.attention.kind === 'idle') {
824 const n = waitingMinutes(src.attention.since_ms, nowMs)
825 if (n !== null) reason += ' · ' + t('reason.idle_hold', { n })
826 }
827 }
828 const pick = verdictOf(kind, t)
829 const tail = proxySegments(src.decisions, t)
830 const line2 = [reason, ...tail].join(' · ')
831 const identity = isObject(env.scope) ? env.scope.repo_identity : null
832 // the phase is the job model's `phase.label` (campaign > receipt > marker stage `size·level ▸ stage` + `unit k/N` (the producer's format, scripts/render-review-page.js; tabs.ts and ui.hasStageArrow read that `▸`; it is never drawn into the band, whose position slot reads `size·level·stage`) > task in progress > deliverable); absent / malformed: an em dash, never the process phase.
833 // No writer of a stage live per the sources manifest: 來源未接 (a phase the model really carries is shown whatever the manifest says).
834 const phase = jobModel !== null && jobModel.phase !== null ? phaseText(jobModel.phase, t) : notWired(src.manifest, ['stage', 'progress', 'task_status_input']) ? t(NOT_WIRED_ID) : '—'
835 let prog = progressView(progress, t)
836 if (prog.text === '—') {
837 if (src.tasks !== null && src.tasks.total > 0) prog = { text: t('progress.unfrozen', { n: src.tasks.completed }), dim: true } // task counts have no frozen denominator
838 else if (notWired(src.manifest, ['progress', 'tasks'])) prog = { text: t(NOT_WIRED_ID), dim: false }
839 }
840 const stalledN = (rowsOf(env) || []).filter(r => r.stall === true).length + (fm.stalled !== null ? 1 : 0)
841 const slots = bandSlots({
842 verdict: pick, marker: src.marker ?? null, live: counts === null ? 0 : counts.confirmed_live, stalled: stalledN, review: src.review ?? null, qc: src.qc ?? null,
843 decisions: src.decisions, spend: spendOf(env), loadSource: src.loadSource ?? null, residue: src.residue ?? null, stage: src.stage ?? null, quota: src.quota ?? null, nowMs,
844 reason: kind === 'decide' || kind === 'stalled' ? reason : null,
845 }, t)
846 return {
847 kind,
848 key: pick.key,
849 why: reason ?? '',
850 verdictReason: kind === 'decide' || kind === 'stalled' ? reason : null,
851 mark: pick.mark,
852 verdict: pick.word,
853 head: projectName(identity, projectKey) + ' · ' + phase + ' · ' + elapsedFrom(src.startMs, nowMs) + ' · ',
854 progress: prog.text,
855 progressDim: prog.dim,
856 reason: line2,
857 project: projectName(identity, projectKey),
858 elapsed: elapsedFrom(src.startMs, nowMs),
859 phase,
860 slots,
861 }
862}
863
864export function bandLine1(v: BandView): string {
865 return v.mark + ' ' + v.verdict + ' ' + v.head + v.progress
866}
867
868export function sessionUsd(env: Json, sid: string): { text: string; as_of: string | null } {
869 const sessions = isObject(env.sessions) ? env.sessions : {}
870 const s = Object.prototype.hasOwnProperty.call(sessions, sid) ? sessions[sid] : undefined
871 if (!isObject(s) || !finite(s.session_usd)) return { text: '$—', as_of: null }
872 return { text: usd(s.session_usd), as_of: typeof s.as_of === 'string' ? s.as_of : null }
873}
874
875// context file of THIS sid only, same contract as scripts/lib/live-state-dir.js readLive.
876export function ctxText(text: string | null, nowMs: number): string {
877 if (text === null) return '—'
878 const parsed = parseJson(text)
879 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema_version !== 1) return '—'
880 const writtenMs = typeof parsed.value.written_at === 'string' ? Date.parse(parsed.value.written_at) : NaN
881 if (!Number.isFinite(writtenMs) || nowMs - writtenMs > CONTEXT_MAX_AGE_MS) return '—'
882 const cw = parsed.value.context_window
883 const pct = isObject(cw) ? cw.used_percentage : undefined
884 return finite(pct) ? Math.round(pct) + '%' : '—'
885}
886
887// no usable context value and no writer live per the manifest: 來源未接 (a value that exists is shown whatever the manifest says)
888export function ctxShown(ctx: string, manifest: Manifest | null, t: T = T_EN): string {
889 return ctx === '—' && notWired(manifest, ['context']) ? t(NOT_WIRED_ID) : ctx
890}
891
892// pane header row: what left the band. Session cost and context are this sid's own; host cost is the day's total.
893export function headerText(env: Json, sid: string, ctx: string, t: T = T_EN): string {
894 return t('pane.header', { session: sessionUsd(env, sid).text, host: usd(env.host_today_usd), ctx })
895}
896
897export function paneRows(env: Json, nowMs: number | null = null): LivePaneRow[] | null {
898 const rows = rowsOf(env)
899 if (rows === null) return null
900 const str = (v: unknown) => (typeof v === 'string' && v ? v : null)
901 const bound = isObject(env.counts) && finite(env.counts.fresh_bound_s) ? env.counts.fresh_bound_s : null
902 return rows.map(r => {
903 const rc = Number.isInteger(r.rc) ? (r.rc as number) : null
904 const ended = r.phase === 'exited' || str(r.ended_at) !== null || str(r.final_status) !== null || rc !== null
905 const probe = finite(r.probe_age_s) ? r.probe_age_s : null
906 return {
907 stall: r.stall === true,
908 run_id: String(r.run_id === undefined || r.run_id === null ? '?' : r.run_id),
909 role: str(r.role), runner: str(r.runner), model: str(r.model), started_at: str(r.started_at),
910 elapsed_s: finite(r.elapsed_s) ? r.elapsed_s : null, phase: str(r.phase),
911 rc, final_status: str(r.final_status),
912 probe_age_s: probe, ended_at: str(r.ended_at), ended,
913 fresh: !ended && r.alive === true && probe !== null && (bound === null || probe <= bound),
914 starting: !ended && probe === null && bound !== null && nowMs !== null && Number.isFinite(Date.parse(str(r.started_at) ?? '')) && nowMs - Date.parse(str(r.started_at) as string) <= bound * 1000, // never probed, launched inside the bound as of NOW (elapsed_s is a stale copy in a heartbeat rewrite): ○ not started yet, not ◌ stopped
915 }
916 })
917}
918
919export type JobModel = {
920 acceptance: string
921 gates: LiveGateRow[]
922 needs_decision: boolean
923 conclusion: string | null
924 decisions: LiveDecision[]
925 progress: JobProgress | null
926 phase: { code: string | null; label: string; source: string | null } | null
927 sources_manifest: unknown
928}
929
930// The job page's model.json (review-job-model/1): acceptance axis, gate rows, the decision awaited, the progress
931// numbers and the phase (`{code, label, source}`; only a string `label` counts). Absent / malformed -> null. `needs_decision` is true only when the model says exactly true.
932export function readJobModel(text: string | null): JobModel | null {
933 if (text === null) return null
934 const parsed = parseJson(text)
935 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== MODEL_SCHEMA || !isObject(parsed.value.axes)) return null
936 const m = parsed.value
937 const raw = isObject(m.axes) ? m.axes.acceptance : undefined
938 const acceptance = raw === 'accepted' || raw === 'rejected' ? raw : 'unknown'
939 const gates = (Array.isArray(m.gates) ? m.gates : []).filter(isObject).map(g => ({
940 phase: typeof g.phase === 'string' ? g.phase : null,
941 generation: Number.isInteger(g.generation) ? (g.generation as number) : null,
942 verdict: typeof g.verdict === 'string' ? g.verdict : null,
943 status: typeof g.status === 'string' ? g.status : null,
944 }))
945 const optText = (v: unknown): string | null => (typeof v === 'string' && v !== '' ? v : null)
946 const decisions: LiveDecision[] = (Array.isArray(m.decisions) ? m.decisions : []).filter(isObject).filter(d => typeof d.question === 'string' && d.question !== '').map(d => ({
947 id: optText(d.id),
948 question: d.question as string,
949 background: optText(d.background),
950 options: (Array.isArray(d.options) ? d.options : []).filter(isObject).map(o => ({
951 label: typeof o.label === 'string' ? o.label : '',
952 description: typeof o.description === 'string' ? o.description : '',
953 })).filter(o => o.label !== ''),
954 recommendation: optText(d.recommendation), why: optText(d.why), blocks: optText(d.blocks), not_authorized: optText(d.not_authorized), source: optText(d.source), opened_at: optText(d.opened_at),
955 stale: d.stale === true,
956 age_s: finite(d.age_s) ? d.age_s : null,
957 orphaned: d.orphaned === true,
958 origin: optText(d.origin),
959 }))
960 const p = m.progress
961 const progress: JobProgress | null = isObject(p)
962 ? {
963 frozen: p.frozen === true,
964 percent: finite(p.percent) ? p.percent : null,
965 done: Number.isInteger(p.done) ? (p.done as number) : null,
966 total: Number.isInteger(p.total) ? (p.total as number) : null,
967 }
968 : null
969 const ph = m.phase
970 const phase = isObject(ph) && typeof ph.label === 'string' && ph.label ? { code: typeof ph.code === 'string' ? ph.code : null, label: ph.label, source: typeof ph.source === 'string' ? ph.source : null } : null
971 return { acceptance, gates, needs_decision: m.needs_decision === true, conclusion: typeof m.conclusion === 'string' && m.conclusion ? m.conclusion : null, decisions, progress, phase, sources_manifest: m.sources_manifest }
972}
973
974// Axis words follow the review page's chip mapping (plan A12).
975export const acceptWord = (a: string, t: T = T_EN): string => t(a === 'accepted' ? 'accept.accepted' : a === 'rejected' ? 'accept.rejected' : 'accept.pending')
976
977export type Counts = { confirmed_live: number; exited: number; unknown: number }
978
979export function countsOf(env: Json): Counts | null {
980 const c = env.counts
981 if (!isObject(c) || !Number.isInteger(c.confirmed_live) || !Number.isInteger(c.exited) || !Number.isInteger(c.unknown)) return null
982 return { confirmed_live: c.confirmed_live as number, exited: c.exited as number, unknown: c.unknown as number }
983}
984
985export function executionToast(before: Counts, after: Counts, t: T = T_EN): string | null {
986 if (before.confirmed_live === after.confirmed_live && before.exited === after.exited && before.unknown === after.unknown) return null
987 return t('toast.execution', { r0: before.confirmed_live, r1: after.confirmed_live, e0: before.exited, e1: after.exited, u0: before.unknown, u1: after.unknown })
988}
989
990export function acceptanceToast(before: string, after: string, t: T = T_EN): string | null {
991 return before === after ? null : t('toast.acceptance', { from: acceptWord(before, t), to: acceptWord(after, t) })
992}
993
994// job directory for a scope: the scope's root, else the root of the most recently started row, else "unbound"
995// (the watcher's renderer names an unbound job exactly that).
996export function jobOf(env: Json, root: string | null): string {
997 if (root) return safeSegment(root)
998 let best: { ms: number; root: string } | null = null
999 for (const r of rowsOf(env) || []) {
1000 if (typeof r.root_run_id !== 'string' || !r.root_run_id) continue
1001 const ms = startedMs(r)
1002 const at = Number.isFinite(ms) ? ms : -Infinity
1003 if (best === null || at >= best.ms) best = { ms: at, root: r.root_run_id }
1004 }
1005 return best === null ? 'unbound' : safeSegment(best.root)
1006}
1007
1008export function reviewLink(port: number, projectKey: string, date: string | null, job: string): string {
1009 const base = 'http://localhost:' + port + '/' + projectKey + '/'
1010 return date === null ? base : base + date + '/' + job + '/current/'
1011}
1012
1013export function portOf(text: string | null): number {
1014 if (text === null) return DEFAULT_REVIEW_PORT
1015 const parsed = parseJson(text)
1016 const p = parsed.ok && isObject(parsed.value) ? parsed.value.port : undefined
1017 return Number.isInteger(p) && (p as number) >= 1 && (p as number) <= 65535 ? (p as number) : DEFAULT_REVIEW_PORT
1018}
1019
1020export const stateText = (t: T) => ({
1021 noPointer: t('state.no_pointer', { hint: RUNS_HINT }),
1022 noProject: t('state.no_project', { hint: RUNS_HINT }),
1023 // a repo with no watcher scope still shows its residue reminder: ⚑N from <git-common-dir>/autopilot-residue-auto.json
1024 noProjectWt: (wt: number) => t('state.no_project_wt', { wt: GT.residue, n: wt, hint: RUNS_HINT }),
1025 unreadable: t('state.unreadable'),
1026 stale: (key: string, publishedAt: string | null) => (publishedAt ? t('state.stale_at', { at: publishedAt, hint: RUNS_HINT, key }) : t('state.stale', { hint: RUNS_HINT, key })),
1027 unavailable: (key: string) => t('state.unavailable', { hint: RUNS_HINT, key }),
1028})
1029
1030// ---- W3a pane sections: text built from the sources, drawn by pane.tsx ----
1031const ledgerPath = (source: string | null, common: string | null, root: string | null): string | null => {
1032 if (common === null) return null
1033 if (source === 'ledger_root') return root === null ? null : common + '/autopilot/work-orders/' + root + '/decision-ledger.jsonl'
1034 return common + '/autopilot/ledger/decisions.jsonl'
1035}
1036
1037// the veto verb is decision-ledger.js `veto --ledger <ledger> --id <decision_id>` (its own round report prints the same line)
1038export function vetoStep(r: DecisionRow, common: string | null, root: string | null, t: T = T_EN): { cmd: string } | { note: string } {
1039 if (r.decision_id === null) return { note: t('veto.no_id') }
1040 const path = ledgerPath(r.source, common, r.root !== null ? r.root : root) // a merged view carries rows of several roots: each names its own
1041 if (path === null && r.source === 'ledger_root') return { note: t('veto.no_path') }
1042 return { cmd: 'decision-ledger.js veto ' + (path === null ? '' : '--ledger ' + path + ' ') + '--id ' + r.decision_id }
1043}
1044
1045// "<age> ago" / "<age> 前": the one place a time and its direction word live together (word order differs per language)
1046export const agoText = (s: number, t: T = T_EN): string => t('ago', { age: ageText(s) })
1047
1048export function buildSections(src: Sources, foreman: ForemanView | null): PaneSections {
1049 const m = src.manifest
1050 const a = src.attention
1051 const tk = src.tasks
1052 return {
1053 attention: a !== null && a.kind !== 'idle' ? a : null,
1054 attentionNotWired: a === null && liveSource(m, 'attention') === false,
1055 tasks: tk,
1056 tasksNote: tk !== null ? null : liveSource(m, 'tasks') === true ? 'todo_hint' : liveSource(m, 'tasks') === false ? 'not_wired' : null,
1057 decisionsNotWired: src.decisions === null && notWired(m, ['ledger_engine', 'ledger_depth0']),
1058 foreman,
1059 }
1060}
1061
1062// ---- stage-graph P7d: the review fact (<live>/runs/<project_key>.review.json, schema autopilot.review/1, written by the watcher) ----
1063// `plan` is the plan-review state of this repo (dispatch-plan-review.js), `code` the latest hetero-review-loop round summary;
1064// either may be null. The file is project-scoped, so a project_key that is not the wanted one is an absent file.
1065export const REVIEW_SCHEMA = 'autopilot.review/1'
1066export type ReviewSeat = { id: string; family: string | null; status: string | null; verdict?: string | null }
1067export type PlanReviewView = { logical_plan_id: string | null; generation: number; max_generations: number | null; terminal: boolean; verdict: string | null; seats: ReviewSeat[]; updated_at: string | null }
1068export type CodeReviewView = { phase: string | null; generation: number | null; base: string | null; head: string | null; seats: ReviewSeat[]; converged: boolean; at: string | null }
1069export type ReviewView = { plan: PlanReviewView | null; code: CodeReviewView | null }
1070
1071function reviewSeats(v: unknown, withVerdict: boolean): ReviewSeat[] {
1072 if (!Array.isArray(v)) return []
1073 return v.filter(isObject).map(s => ({ id: str(s.id) || '—', family: str(s.family), status: str(s.status), ...(withVerdict ? { verdict: str(s.verdict) } : {}) }))
1074}
1075
1076export function readReview(text: string | null, projectKey: string): ReviewView | null {
1077 if (text === null) return null
1078 const parsed = parseJson(text)
1079 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== REVIEW_SCHEMA || parsed.value.project_key !== projectKey) return null
1080 const v = parsed.value
1081 const p = isObject(v.plan) ? v.plan : null
1082 const c = isObject(v.code) ? v.code : null
1083 const plan: PlanReviewView | null = p === null || !Number.isInteger(p.generation) ? null : {
1084 logical_plan_id: str(p.logical_plan_id), generation: p.generation as number, max_generations: Number.isInteger(p.max_generations) ? (p.max_generations as number) : null,
1085 terminal: p.terminal === true, verdict: str(p.verdict), seats: reviewSeats(p.seats, false), updated_at: str(p.updated_at),
1086 }
1087 const code: CodeReviewView | null = c === null ? null : {
1088 phase: str(c.phase), generation: Number.isInteger(c.generation) ? (c.generation as number) : null, base: str(c.base), head: str(c.head),
1089 seats: reviewSeats(c.seats, true), converged: c.converged === true, at: str(c.at),
1090 }
1091 return plan === null && code === null ? null : { plan, code }
1092}
1093
1094// The review round the band and the Review tab name: `R<n>`, n = the code-review round when there is one, else the plan-review generation; null = none.
1095export function reviewRound(r: ReviewView | null): number | null {
1096 if (r === null) return null
1097 return r.code !== null && r.code.generation !== null ? r.code.generation : r.plan !== null ? r.plan.generation : null
1098}
1099
1100// The band's review slot text: `↺ R<n>`; null = no slot.
1101export function reviewSlot(r: ReviewView | null): string | null {
1102 const n = reviewRound(r)
1103 return n === null ? null : GT.round + ' R' + n
1104}
1105
1106const short = (sha: string | null): string => (sha === null ? '—' : sha.slice(0, 8))
1107
1108// ================= stage-graph P7: the one-line band (contract ②) and the panel's facts =================
1109// Colours are theme keys used as TEXT colour only (owner decision 5): no backgroundColor, no inverse, no raw colour.
1110export type ThemeKey = 'claude' | 'warning' | 'error' | 'success' | 'suggestion' | 'inactive' | 'subtle' | 'merged'
1111export type SlotId = 'verdict' | 'position' | 'unit' | 'dispatch' | 'review' | 'decisions' | 'spend' | 'quota' | 'hygiene'
1112// tag: which part the width table may drop or shorten (age, k/N, 族, the bar, the stage text)
1113export type SegTag = 'age' | 'kn' | 'fam' | 'bar' | 'stage' | 'live' | 'stalled' | 'chip' | 'wt' | 'walk' | 'dot' | 'reason' | 'round' | 'qc' | 'amt' | 'pct' | 'bar10' | 'bar5' | 'bar3' | 'qx'
1114export type Seg = { text: string; color?: ThemeKey; bold?: boolean; dim?: boolean; tag?: SegTag; slot?: SlotId; role?: SegRole; here?: boolean; fmt?: FmtKind; fact?: FactId; press?: string } // slot: set by layoutBand on the band line (the Button it presses); a separator has none
1115export type Slot = { id: SlotId; segs: Seg[] }
1116
1117// displayWidth / cellWidth live in ui.ts (the design system owns the width rules); displayWidth is re-exported for the band and the tests.
1118export { displayWidth }
1119
1120// the longest prefix of `text` that fits `width` cells, ending in `…` when it was cut (width < 1 -> empty)
1121export function truncateToWidth(text: string, width: number): string {
1122 if (width < 1) return ''
1123 if (displayWidth(text) <= width) return text
1124 let out = ''
1125 let w = 0
1126 for (const ch of text) {
1127 const cw = cellWidth(ch.codePointAt(0) as number)
1128 if (w + cw > width - 1) break
1129 out += ch
1130 w += cw
1131 }
1132 return out + '…'
1133}
1134
1135// ---- marker (§2.9 fields) ----
1136export type UnitView = { kind: string; index: number; total: number; label: string }
1137export type MarkerView = {
1138 size: string | null; urgent: boolean; bug: boolean; high_risk: boolean; level: string | null
1139 stage: string | null; stage_set_at_ms: number | null; unit: UnitView | null; review_families: string[]
1140}
1141const SIZES = ['XS', 'S', 'M', 'L', 'XL']
1142
1143// The session marker's stage-graph fields (scripts/session-mode.js §2.9, written by stage-advance.js). A field of the wrong type reads as absent.
1144export function readMarker(m: Json | null): MarkerView | null {
1145 if (m === null) return null
1146 const u = m.unit
1147 const pos = (x: unknown): x is number => typeof x === 'number' && Number.isInteger(x) && x >= 1
1148 const unit: UnitView | null = isObject(u) && typeof u.kind === 'string' && u.kind && pos(u.index) && pos(u.total)
1149 ? { kind: u.kind, index: u.index, total: u.total, label: typeof u.label === 'string' ? u.label : '' }
1150 : null
1151 const at = typeof m.stage_set_at === 'string' ? Date.parse(m.stage_set_at) : NaN
1152 return {
1153 size: typeof m.size === 'string' && SIZES.includes(m.size) ? m.size : null,
1154 urgent: m.urgent === true, bug: m.bug === true, high_risk: m.high_risk === true,
1155 level: typeof m.level === 'string' && m.level ? m.level : null,
1156 stage: str(m.stage), stage_set_at_ms: Number.isFinite(at) ? at : null, unit,
1157 review_families: Array.isArray(m.review_families) ? m.review_families.filter((f): f is string => typeof f === 'string' && f !== '') : [],
1158 }
1159}
1160
1161// ---- D3 residue / D4 stage walk / D1 spend ----
1162export const RESIDUE_SCHEMA = 'autopilot.residue/1'
1163// Residue auto-reap R4 (docs/plans/evidence/2026-10-09-residue-auto-reap/contract.md): the band's `wt N` and the Hygiene tab show
1164// needs_human_*, the residue a person must act on. Fields absent from an older fact read as 0 / null / [].
1165export type NeedsHumanEntry = { kind: string; target: string; class: string; age_days: number | null; bytes: number | null; reason: string | null; command: string | null }
1166export type ResidueView = {
1167 reapable: number; by_class: Record<string, number>; at: string | null
1168 needs_human_count: number; needs_human_bytes: number | null; needs_human: NeedsHumanEntry[]
1169 auto_ran_at: string | null; auto_removed_count: number | null; auto_archived_count: number | null
1170}
1171// the producer's own list of what a person must act on (path, branch or ref names the target); at most 20 entries are read
1172function readNeedsHuman(list: unknown): NeedsHumanEntry[] {
1173 const rows: NeedsHumanEntry[] = []
1174 if (!Array.isArray(list)) return rows
1175 for (const e of list) {
1176 if (!isObject(e)) continue
1177 const target = str(e.path) ?? str(e.branch) ?? str(e.ref)
1178 if (target === null) continue
1179 rows.push({
1180 kind: str(e.kind) ?? '—', target, class: str(e.class) ?? '—',
1181 age_days: typeof e.age_days === 'number' && Number.isFinite(e.age_days) ? e.age_days : null,
1182 bytes: isCount(e.bytes) ? e.bytes : null, reason: str(e.reason), command: str(e.command),
1183 })
1184 if (rows.length >= 20) break
1185 }
1186 return rows
1187}
1188export function readResidue(text: string | null, projectKey: string): ResidueView | null {
1189 if (text === null) return null
1190 const parsed = parseJson(text)
1191 if (!parsed.ok || !isObject(parsed.value) || parsed.value.schema !== RESIDUE_SCHEMA || parsed.value.project_key !== projectKey) return null
1192 const v = parsed.value
1193 if (!isCount(v.reapable_worktrees)) return null
1194 const by: Record<string, number> = {}
1195 if (isObject(v.by_class)) for (const k of Object.keys(v.by_class)) if (isCount(v.by_class[k])) by[k] = v.by_class[k] as number
1196 const rows = readNeedsHuman(v.needs_human)
1197 return {
1198 reapable: v.reapable_worktrees, by_class: by, at: str(v.at),
1199 needs_human_count: isCount(v.needs_human_count) ? v.needs_human_count : 0,
1200 needs_human_bytes: isCount(v.needs_human_bytes) ? v.needs_human_bytes : null,