SLOPSHOPPER

harness

Harness — a lightweight reasoning floor. Pass a raw request; a fixed six-stage engine runs Plan(opus) → SetGoal(opus, adversarial critic) →…

panebandcommandtoaststatusprocess
★ 3v1.38.2MITupdated 2026-10-26newkayak12/claude-skills/harness
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · harness
│ ┃ Harness ✕ › fix the failing auth test and add an audit log call │ ┃ ╭─────────────────────────────────────────── │ ┃ │ Harness status ⏺ Read(src/auth.ts) │ ┃ │ No gate configured: ⎿ Read 6 lines │ ┃ │ .claude/harness-gate.json is not in this ⏺ Update(src/auth.ts) │ ┃ │ project. ⎿ Added 2 lines, removed 1 line │ ┃ │ ⏺ Bash(bun test) │ ┃ │ 1: Now 2: Flow 3: Findings 4: ● Gate ⎿ 3 pass, 1 fail │ ┃ │ [ ] run · 1-4 tab · Esc or [ q ] closes │ ┃ ╰─────────────────────────────────────────── ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /harness-status │ ⎿ harness: pane opened │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Harness
╭──────────────────────────────────────────────────────────╮ │ Harness status │ │ No gate configured: .claude/harness-gate.json is not in │ │ this project. │ │ │ │ 1: Now 2: Flow 3: Findings 4: ● Gate rules │ │ [ ] run · 1-4 tab · Esc or [ q ] closes │ ╰──────────────────────────────────────────────────────────╯
README

harness

English · 한국어

A reasoning floor for substantial requests. Not a quality maximizer — a filter that removes repetition and below-threshold answers by forcing every request through six staged roles with the judge separated from the actor. Planning and judging are pinned to Opus; code execution and deterministic verification are provider-routed to the local Codex CLI when it is available.

Plan(opus) → SetGoal(opus) → Implement(Codex when enabled) → Test(Codex when enabled) → QualityGate(opus, loop) → Report(sonnet)

The plugin also ships an opt-in PreToolUse edit gate, so a project can require harness engagement before anyone edits the paths it cares about.

Install & Uninstall

/plugin install harness@newkayak12-claude-skills
/plugin uninstall harness@newkayak12-claude-skills

trophy rides along. From this version, the first interactive session after you install or update this plugin installs trophy (achievements) once, in user scope, if you don't have it. Nothing is sent until you say yes; uninstalling trophy is respected (it is never reinstalled). To opt out beforehand: mkdir -p ~/.claude/plugins/.newkayak12-trophy-ride.done. Needs sh (Windows without one is not covered).

Marketplace install alone enforces nothing — it makes the skills available. Run the install skill inside a target project to make governance ambient (see Installing into a project).

Orchestration paths

PathWhenHow
Graph (default)graph-engineering MCP connectedgraph:orchestrate — the graph engine owns the flow; the main session only loops graph_next / graph_run / graph_submit. No transport subagents, no polling. Open with allocation: "balanced" for stages to actually be distributed — omit it and it falls back to legacy ordered, running everything in one session.
Workflow engineGraph MCP absent, Workflow tool availableWorkflow({ scriptPath: "harness/engine/pipeline.js", ... })
Agent teamNeitherengine/fallback.md

The graph engine exists because the Workflow path had to spend a subagent per Implement/Test node just to drive a CLI through Bash, and a subagent waiting on a process can only poll. Measured on one real run the transport layer cost more than the reasoning layer (6.87M vs 2.06M input tokens, zero edits by the transport). See graph/README.md.

Which skill do I want?

I want to…Skill
Get a substantial request planned, executed, verified, and gated before it comes backharness
Connect or verify the graph-owned default orchestration pathgraph:install
Make the harness ambient in a project — gate, hook, conventions, CLAUDE.md block; optionally derive conventions from a reference project via develop:like-my-codeinstall
Take harness governance back out of a projectremove
Refresh this project's installed harness copies after a plugin version bumpupdate
Delegate an Implement/Test stage to the local Codex CLI from any install layoutcodex-control

Skills

harness

The engine entry point. Hands the raw request to engine/pipeline.js, which plans, authors and critiques its own goal-spec, executes each subgoal with skill-equipped executors, verifies each one with a separate deterministic Test agent, and gates both the subgoals and the assembled whole before writing a report. Reach for it when the bar is "verified, not plausible". Not for trivial edits or Q&A — the six stages cost more than the answer is worth there.

Run the harness on this: our order-sync job silently drops rows when the upstream page
size changes. Fix it properly and prove each part independently before reporting.

Invocation, mode B (the default):

Workflow({ scriptPath: "harness/engine/pipeline.js", args: {
  request: "<the request>",
  context: "<optional constraints>",
  max_retries: 2,
  codex_provider: "off"      // default "off"; "auto" | "required" opt in to Codex
}})

Returns report, all_passed, failed[], and goal_gate — relayed to you as-is, failures included. Beyond the three statically mounted skills (agents:agent-task-decomposer at Plan, think:devils-advocate at the spec critic and QualityGate, completion:verification-before-completion at Test), SetGoal may map harness-aware repo skills (write:plans, planning:executing-plans, agents:subagent-driven-development, develop:test-driven-development, write:writing-skills, agents:dispatching-parallel-agents, think:brainstorming) onto subgoals. All optional; a run using none of them is valid.

install

Scaffolds project-owned harness governance so enforcement does not depend on the plugin staying installed. Judgment (gate patterns, embedding choice, conventions, the CLAUDE.md block) stays with the skill; the deterministic file work runs through install.mjs. Everything is idempotent and non-destructive — existing files are reported kept, never overwritten. It does not run the engine; use the harness skill for that.

이 프로젝트에 하네스 설치하고 게이트 켜줘 — Kotlin 소스만 게이트 대상으로.
node "<plugin>/skills/install/install.mjs" '{
  "projectDir": "<abs project root>",
  "gate": { "patterns": ["src/.*\\.kt$"], "window_hours": 2 },
  "embed": { "runtime": true, "skills": [ { "name": "...", "src": "<abs>" } ] }
}'

Omit gate to skip the gate write, embed to skip standalone embedding. After a plugin version bump, re-run with "refresh": true — it re-copies only plugin-owned files (goal-gate.mjs, .claude/harness/**) and never touches your gate, conventions, CLAUDE.md, or settings.json.

remove

Uninstalls project-local harness governance: the hook, its settings.json registration, .claude/harness-gate.json, .claude/.harness-last-decision.json, .claude/harness/, .claude/.harness-markers/, the fenced CLAUDE.md block, and the .gitignore block between # harness:begin and # harness:end (deleted as a whole). .claude/conventions/ is project-owned and is preserved by default — purging it requires explicit confirmation. A malformed settings.json or unmatched CLAUDE markers are left in place and reported for manual cleanup rather than deleted to force completion. Harness lines in .gitignore outside that block are reported legacy-left and kept; a broken or duplicate # harness:begin / # harness:end marker gives marker-error and the file is untouched.

Uninstall the harness from this project, but keep .claude/conventions/ — we've edited those.
node "<plugin>/skills/remove/remove.mjs" '{
  "projectDir": "<abs project root>",
  "purgeConventions": false
}'

Idempotent: a second run reports absent rather than failing.

update

Refreshes a project's installed harness copies after the plugin was bumped. It detects the install mode from disk (.claude/harness/ present → embedded), re-derives the embed config from what is embedded, and runs install.mjs with "refresh": true — no new script. Plugin-owned copies (goal-gate.mjs, .claude/harness/**) are reported refreshed or unchanged; your gate, conventions, CLAUDE.md block, and settings.json are never touched. An embed source it cannot resolve stops the run and is named.

하네스 플러그인 올렸는데 이 프로젝트 복사본도 최신으로 맞춰줘.

Maintainers cutting a patch release of this source use node _repo/scripts/patch-harness.mjs (see the repo CLAUDE.md Update Workflow); it is not a user skill.

codex-control

The adapter-discovery contract used by Codex-enabled Implement/Test stages, so delegation works without assuming the project embedded .claude/harness/**. It resolves the first existing codex-exec-adapter.mjs, and when none exists it records Codex as unavailable and lets the stage continue on the normal Claude path.

Harness Implement stage needs to run Codex from plugin mode — resolve the adapter first.

Resolution order:

#LayoutPath
1Explicit argargs.codex_adapter_path
2Repo-localharness/engine/codex-exec-adapter.mjs
3Embedded install.claude/harness/engine/codex-exec-adapter.mjs
4Plugin modederived from the scriptPath in the project's CLAUDE.md Harness block

Run contract: always --detect before delegating; separate Codex processes for Implement and Test; Implement may use --sandbox workspace-write; Test prompts are verification-only and must never edit implementation files or trust the Implement narrative without command/file evidence.

How it works

  1. You pass a raw request. Workflow({ scriptPath: "harness/engine/pipeline.js", args: { request: "..." } })
  2. The engine plans and authors the goal-spec itself (Opus, with an adversarial critic pass), so spec quality doesn't depend on the main-session model. Schema: goal-spec.md.
  3. Each subgoal loops Implement → Test → QualityGate (bounded by max_retries): executors invoke this repo's skills; a separate Test agent produces deterministic evidence (runs commands, reads artifacts); a separate Opus judge gates on evidence.
  4. A goal-level gate scores the assembled whole against the goal (0-100 match_pct, pass requires >= 90%; below threshold triggers a repair pass and re-gate), then a Report stage synthesizes.

With codex_provider: "auto" or "required", Codex is the default route for every Implement/Test stage: a minimal Sonnet controller resolves the adapter via codex-control, runs a separate local codex exec --json process, and converts its output into the normal HANDOFF or evidence JSON — it must not redo the work itself on success. auto may explicitly degrade to Sonnet on route failure; required reports provider failure instead. off forces plain Sonnet. implement_provider / test_provider in the goal-spec are trace hints, not prerequisites.

Modes

  • B (default): raw request + the fixed engine.
  • DW-off fallback: when Dynamic Workflow is disabled or the Workflow tool is absent, form a role-isolated Agent Team and run the same six roles through the file-backed fallback contract (engine/fallback.md). The team lead only coordinates; Implement, Test, and QualityGate remain separate teammates exchanging file paths through a run directory, and engine/fallback-check.mjs is the objective done-signal.
  • M (meta): the harness generates a bespoke Workflow when the request needs control flow the fixed stages can't express (tournament, escalation, loop-until-dry) — it copies templates/meta-skeleton.js, rewrites only the [META] Work block, and runs it. The skeleton's contract (judge ≠ actor, provider routing, bounded loops, deterministic Test, goal-level gate) stays verbatim.
  • A (manual): you author the bespoke Workflow yourself — see templates/.

When the active orchestrator is Codex itself, do not recurse through codex, codex-exec-adapter.mjs, or codex-runner.mjs — run the six-stage contract directly with native Codex tools per the repository AGENTS.md.

Installing into a project

Marketplace install alone enforces nothing. Run the install skill (skills/install/SKILL.md) from the target project to make governance ambient — it scaffolds project-owned copies (never overwrites existing files):

  • .claude/harness-gate.json — activates the edit gate on confirmed path patterns
  • .claude/hooks/goal-gate.mjs + a merged .claude/settings.json PreToolUse entry — the self-contained gate hook, committed so it enforces team-wide without depending on the plugin install (engine still lives in the plugin — see the install skill's gap note)
  • .claude/conventions/{coding,verification,boundaries}.md — default ruleset the engine reads (SetGoal → acceptance/test, Implement → follows) If you have a reference project, install can fill coding.md/boundaries.md from it via develop:like-my-code (skipped when develop is absent)
  • a fenced ## Harness section appended to the project's CLAUDE.md
  • a # harness:begin / # harness:end block in .gitignore: install adds line by line only the missing ones of .claude/.harness-markers/, .harness-run/, .claude/.harness-last-decision.json and .claude/settings.local.json

The project owns the copies afterward. Lifecycle skills only change them when explicitly invoked: install with refresh:true refreshes plugin-owned copies, and remove cleans up the installation.

Enforcement is an opt-in PreToolUse gate (hooks/): a project lists gated paths in .claude/harness-gate.json, and Write|Edit|MultiEdit|NotebookEdit there — or a Bash command that writes there — requires harness engagement. Engagement is a record (a Workflow/graph/teams tool call that ran, an open broker node, a fallback run with plan, goal-spec and a sound critique on disk, or a live marker), never a string in the transcript. Fail-open everywhere (v0 lesson).

  • Markers engage. A live marker in .claude/.harness-markers/ engages the gate (parallel subagents; teams writes one into each package worktree); a marker with a future timestamp is ignored.
  • Always gated. .claude/harness-gate.json, .claude/settings.json and settings.local.json, .claude/hooks/ and .claude/.harness-markers/ are gated whatever patterns says. The one exemption is node <harness plugin>/skills/remove/remove.mjs ['<json>'] run from the installed plugin; the project copy of the hook never exempts it.
  • Read-only commands. grep, egrep, fgrep, rg, cat, head, tail, less, wc, ls and echo (and git log|show|diff|status) that own the whole simple command write nothing, so a write verb or path inside them is not judged. A command containing $(…) or backticks is not exempt.
  • Imports. A static relative import (import { f } from './lib.mjs') is not a write and its specifier is not a written path. A node: or package import, or a dynamic import(), still counts.

Lifecycle helpers

  • harness:remove removes the installed hook, registration, gate, embedded runtime, marker cache, CLAUDE.md block, and the .gitignore block (legacy-left lines kept, marker-error leaves the file untouched). Project-owned conventions are preserved unless their removal is explicitly requested.
  • harness:update refreshes a project's installed copies after a plugin bump by running install.mjs with "refresh": true; user-owned files are never touched.

Mod (Claude Code live UI)

harness ships a small mod: a status line with the open runs per stage, a three-row band above the prompt for the run that is going, and a pane with the run, its critique rounds, its units and the gate. It is early access and optional. The gate itself is the command hook and works without it, and the mod does not change how it decides.

Version. Modules load on Claude Code 2.1.292 and newer. The module API is early access and may change between releases. An older build skips the module: 2.1.284 was checked, it prints one stderr line (hooks module not loaded: …) and the command hooks, MCP and CLIs work unchanged. If a build says modules are not turned on for installed plugins, set CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1.

Where it runsMod
Interactive terminalon
Desktop app, Code tabon
claude -p and headless adaptersoff (no UI surface)
Codex, or no pluginnot applicable, nothing is lost

Features

  • Status line: open runs per stage, Plan(6) / Implement(11). It counts this worktree's fallback-check --list rows (other worktrees belong to other sessions). A run untouched for 12 h is left out; with nothing open the line is empty. Gate decisions are not shown here; open /harness-status.
  • Band above the prompt: three rows for the leading harness run (harness runs only; graph runs are the graph mod's). Row 1 says what it is doing, ⚑ first when it waits on you, with the question; row 2 is the stage rail; row 3 is cost and time. +N counts the other open runs. Hidden when nothing is open. A [ open ] button at the end of row 1 opens the pane when clicked.
  • /harness-status opens the pane on the run's Now tab (on Gate rules when no run is open); Esc or q closes it, and typing /harness-status again closes it while the pane has focus (any other /command typed there runs). Head of the pane: Now (the stage or subgoal at work, dim when it is the canned sentence of the stage, with round n of max while the critique loops and the time in this stage), last step and You (what the run needs from you, or "nothing needed" and what comes next). Under them, the rail: every critique round is a step, ✘ Critique then ✔ SetGoal again, up to the round cap. Tabs are Now, Flow, Findings and Gate rules (keys 1-4; the selected one is bright with a dot). With two or more runs, [ and ] switch runs from the keyboard (no click first) and stop at the first and the last; the tab row says how many more there are.
  • Now shows the findings of the newest critique round, worst first, and a +n: … line for the rest.
  • Flow draws each stage in order. A subgoal opens into its gate verdicts: a rejected attempt shows its reason (↳ …) and the retry sits one level under it. A rejected critique (sound:false) and a failing goal gate show theirs too.
  • Findings lists every critique round: its verdict, then its findings by severity (blocker, major, minor, nit), with a total over all rounds on top.
  • Gate rules: the gated patterns, the engagement window, the last decision (allow or deny, tool, target, age, reason) and how to engage the harness. Without a gate config it says so.
  • /harness-status demo [minimal|full|parallel|narrow|off] draws fictional runs instead of the live ones (for a screenshot or a look at the layout); demo off returns. The status line keeps counting the live runs.
  • Where the data comes from. The run view reads .harness-run/<run>/ in the session folder (plan, goal spec, critique, gate files and the subgoal folders) read-only, and follows the newest live run, else the newest run. The last decision comes from .claude/.harness-last-decision.json, written by the gate hook. It is a local runtime file, gitignored by install, and removed by remove. A gate config that cannot be read shows an invalid-config notice under Gate rules.
  • Gate deny push. When the gate denies a call while you are away, the mod sends its deny line (⛔ goal gate blocked <Tool>: <path> …, or the harness-and-teams routing line) as a PushNotification. If it is not sent (you are at the terminal), or the same path was pushed in the last 10 minutes, the same line is a toast. Denies from before the session started are ignored; any failure is silent.
  • Run push. Same push, same toast fallback, for what happens in a run: harness <run>: <kind> — <stage/subgoal> (<attempt>/<max>). Kinds: rejected (02-critique.json sound:false; a subgoal's gate-<n>.json or 04-goal-gate.json failing before the report), failed (a subgoal's result.json passed:false, or a failing goal gate once 05-report.md exists) and complete (05-report.md written with no failure; graph runs are pushed by the graph mod). Once per run, stage or subgoal, kind and attempt; only files written after the session started; interactive sessions only; any failure is silent.
  • Language. English by default; Korean when Claude Code's language setting is Korean.

Known limitations: the status reads the gate config relative to the session's working directory. A session that started with no UI surface (headless or SDK-hosted) keeps the mod off even if a client attaches later; start a new session to get it (a reload of an unchanged mod does not re-fire session.start).

Screenshots

Captured from a live Claude Code 2.1.293 terminal session.

band The band while a run waits on you: ⚑, the question, the rail, cost and time, +1 run for the other one, and the [ open ] button that opens the pane. Glance at it to know whether the run needs you.

pane-now The /harness-status Now tab of a run in its critique loop: what it is doing, the last step, what it needs from you, and the rail with the rejected rounds. It shows when you open the pane, and [ / ] switch runs.

pane-findings The Findings tab (key 3): each critique round with its findings by severity, so you see why a round was rejected without reading the files.

gate-denial The gate hook denying an Edit to a gated path before the harness is engaged.

The mod also publishes each fallback run's outcome (pass on a report with no failure, reject on a failed goal gate after the report, fail on a failed subgoal; no ids) as the state value harness.outcome, for the trophy plugin's opt-in counts.

Status

  • v1.38.2 — /harness-status draws on terminal, desktop, mobile and vscode; the key input shows only where the surface carries one (mobile keeps the buttons).
  • v1.38.1 — the harness skill page gains an Output Template and a Related Skills section; no engine change.
  • v1.38.0 — /harness-status says what the run is doing now, what it did last and whether it waits on you; the stage rail shows the critique loop with "round n of max", findings are listed by severity across rounds, and [ ] switch runs and stop at the ends. A run whose critique cap ran out no longer reads "critique" after it moved on. The band shows harness runs only and says the elapsed time once; the status line counts from the run's own stages. A failure toast says why and what happens next (retry n/m, needs you, gave up).
  • v1.37.0 — /harness-status (was /harness-gate): a Now line, Flow (stages, each reject's reason with the retry under it, a rejected critique too) and Detail (per-subgoal results, every gate verdict, goal-gate match, gate rules). Closes on Esc, q or the command again.
  • v1.36.0 — the mod publishes each run's outcome (pass, reject or fail, once per run and outcome) as its own outcome state for trophy to count; no ids, and the harness works the same without trophy.
  • v1.35.0 — the mod sends a push notification (toast when it cannot) when the gate denies (once per path per 10 min) and on run rejects, failures and completions; graph runs are left to the graph mod.
  • v1.34.1 — Codex uses a schema-compatible hook overlay while preserving the goal gate for edits and nested run entry calls; Claude hooks are unchanged. A non-entry Skill call exits the gate at once again, as before the overlay (it no longer refreshes engagement markers). Codex apply_patch renames (*** Move to:) are judged by their target path. The Codex overlay leaves out the SessionStart trophy install hook on purpose (trophy is Claude-only).
  • v1.34.0 — a project goal-gate copy defers to the plugin when the harness plugin is enabled (no stale copy can judge); the plan prompt no longer lists the unpublished assist plugin
  • v1.33.0 — no harness inside a harness: a subagent (agent_id) or run node (HARNESS_NODE=1) blocked by the goal gate is told to stop and report to its caller, and its call to an entry skill (harness, graph:orchestrate, teams:orchestrate/develop/sprint/document/plan/qa) is denied; every deny says so; a project goal-gate copy that differs from the plugin's raises one toast to run harness:update
  • v1.32.0 — when teams is installed too, a goal-gate deny routes by kind (simple development → graph, else the harness skill; spec, planning, QA, several areas or unsure → teams:orchestrate), with one toast for the conflict
  • v1.31.2 — fallback: COMPLETE with
Source 5 files
hooks/mod.tsx 798 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Decision, HarnessRow, PaneTab, RunInfo, RunSub, StageKey } from '../types'
5import { MARK, TINT, bar, cap, fmt, isKorean, tabs } from './draw'
6import type { Mark } from './draw'
7import { DEMO_NOW, bandLines, cells, demoRows, footerFits, innerWidth, paneContent, paneHead, parseDemoArg, renderLines, tabRowPlan } from './harness-draw'
8import type { PaneCtx, TabLabels } from './harness-draw'
9import type { RowFailure } from './status'
10import {
11  cycleRun, failureToast, failuresOf, flowLines, frozenOrder, listArgv, markLooked, openTab, otherRunLabel, parseRow, parseRows,
12  paneKey, paneSlash, pickRun, reasonFor, runPosition, shownRows, showArgv, spinnerPlan, stageStatus,
13} from './status'
14
15const last = atom({ plugin: 'harness', key: 'last' } as const, null as Decision | null)
16const armed = atom({ plugin: 'harness', key: 'armed' } as const, false)
17const patterns = atom({ plugin: 'harness', key: 'patterns' } as const, [] as string[])
18const windowHours = atom({ plugin: 'harness', key: 'windowHours' } as const, 2)
19// the config file exists but is not JSON
20const broken = atom({ plugin: 'harness', key: 'broken' } as const, false)
21const run = atom({ plugin: 'harness', key: 'run' } as const, null as RunInfo | null)
22const lang = atom({ plugin: 'harness', key: 'lang' } as const, 'en' as 'en' | 'ko')
23// the open runs of `fallback-check --list --json`: the last good list; [] until the first read answers
24const rows = atom({ plugin: 'harness', key: 'rows' } as const, [] as HarnessRow[])
25// the run the pane shows, by slug; null (or a slug no longer open): opening order decides
26const selected = atom({ plugin: 'harness', key: 'selected' } as const, null as string | null)
27// per slug, the rejects the person has seen
28const looked = atom({ plugin: 'harness', key: 'looked' } as const, {} as Record<string, number>)
29// the spinner's frame counter
30const spin = atom({ plugin: 'harness', key: 'tick' } as const, 0)
31const paneTab = atom({ plugin: 'harness', key: 'paneTab' } as const, 'now' as PaneTab)
32const demo = atom({ plugin: 'harness', key: 'demo' } as const, null as 'minimal' | 'full' | 'parallel' | 'narrow' | null)
33
34const PANE = 'harness-status'
35const CONFIG = '.claude/harness-gate.json'
36const DECISION = '.claude/.harness-last-decision.json'
37const TEAMS_CONFIG = '.claude/teams-dispatch.json'
38const TICK_MS = 5000
39const SPIN_MS = 800 // a spinner frame; faster than the 5 s tick, and only while a shown run acts
40const LIST_TIMEOUT_MS = 10_000
41const PUSH_GAP_MS = 10 * 60 * 1000
42const RUNS = '.harness-run'
43const LIVE_MS = 2 * 60 * 60 * 1000
44const MAX_READ = 4 * 1024 * 1024
45const PASS_PCT = 90 // the pass bar of the run checker (engine fallback check)
46const BAR = 24
47const LINE_MAX = 24 // flow lines / detail lines drawn before "+n more"
48const RUN_STAGES: StageKey[] = ['plan', 'setgoal', 'critique', 'implement', 'gate', 'report']
49
50const en = {
51  paneTitle: 'Harness status', tabNow: 'Now', tabFlow: 'Flow', tabFindings: 'Findings', tabRules: 'Gate rules', tabRulesShort: 'Rules',
52  prev: 'prev', next: 'next', keysLead: '[ ] run · 1-4 tab · Esc or', keysTail: 'closes', demoOn: 'demo: {name}', demoOff: 'demo off', demoFiles: 'The demo has no run files.',
53  stagePlan: 'Plan', stageSetgoal: 'SetGoal', stageCritique: 'Critique', stageImplement: 'Implement/Test', stageGate: 'Gate', stageReport: 'Report',
54  tryNo: 'attempt {n}', resPassed: 'passed · {n} tries', resFailed: 'failed · {n} tries', resNone: 'not judged yet', stalled: 'stalled: the retry changed nothing',
55  gateRejected: 'gate {n}: rejected', gatePassed: 'gate {n}: passed', critiqueRejected: 'Critique rejected', rules: 'Gate rules',
56  goalGate: 'Goal gate', passBar: '{pct}% (pass ≥ {bar})', more: '+{n} more',
57  noRun: 'No harness run in this folder.', closeBtn: 'q', bandOpen: 'open',
58  cmdDesc: 'Open or close the harness status pane: run flow and detail, why the gate denied the last call', paneOpened: 'pane opened', paneClosed: 'pane closed',
59  noGate: 'No gate configured: .claude/harness-gate.json is not in this project.',
60  badGate: 'Gate config .claude/harness-gate.json could not be read (invalid JSON).',
61  gated: 'Gated patterns ({n}): {list}', window: 'Engagement window: {h} h',
62  noDecision: 'No gated call decided yet.', lastDecision: 'Last decision: {decision} ({tool} {target}, {ago})', reason: 'Reason: {reason}',
63  agoMin: '{n} min ago', agoHour: '{n} h ago',
64  // the deny message of the gate hook, after the gated paths
65  engage:
66    'Engage the harness before editing it: invoke the harness skill and follow its Process - ' +
67    'the graph MCP, the Workflow engine, or an Agent Team fallback run whose plan, goal-spec and ' +
68    'sound critique are on disk. A mention in text does not engage it.',
69}
70
71// one table, two languages; the type keeps the keys identical
72export const STRINGS: Record<'en' | 'ko', Record<keyof typeof en, string>> = {
73  en,
74  ko: {
75    paneTitle: '하네스 상태', tabNow: '지금', tabFlow: '흐름', tabFindings: '발견', tabRules: '게이트 규칙', tabRulesShort: '규칙',
76    prev: '이전', next: '다음', keysLead: '[ ] 실행 · 1-4 탭 · Esc 또는', keysTail: '로 닫기', demoOn: '데모: {name}', demoOff: '데모 끝', demoFiles: '데모에는 실행 파일이 없습니다.',
77    stagePlan: '계획', stageSetgoal: '목표 설정', stageCritique: '비평', stageImplement: '구현/테스트', stageGate: '게이트', stageReport: '보고',
78    tryNo: '{n}번째 시도', resPassed: '통과 · {n}회 시도', resFailed: '실패 · {n}회 시도', resNone: '아직 판정 전', stalled: '멈춤: 재시도로 달라진 것이 없음',
79    gateRejected: '게이트 {n}: 반려', gatePassed: '게이트 {n}: 통과', critiqueRejected: '비평 반려', rules: '게이트 규칙',
80    goalGate: '목표 게이트', passBar: '{pct}% (통과 ≥ {bar})', more: '+{n}건 더',
81    noRun: '이 폴더에 하네스 실행이 없습니다.', closeBtn: 'q', bandOpen: '열기',
82    cmdDesc: '하네스 상태 창 열기/닫기: 실행 흐름과 상세, 게이트가 마지막 호출을 막은 이유', paneOpened: '창을 열었습니다', paneClosed: '창을 닫았습니다',
83    noGate: '게이트 설정 없음: 이 프로젝트에 .claude/harness-gate.json 이 없습니다.',
84    badGate: '게이트 설정 .claude/harness-gate.json 을 읽을 수 없습니다 (JSON 오류).',
85    gated: '게이트 대상 ({n}): {list}', window: '개입 유효 시간: {h}시간',
86    noDecision: '아직 판정한 게이트 호출이 없습니다.', lastDecision: '마지막 판정: {decision} ({tool} {target}, {ago})', reason: '이유: {reason}',
87    agoMin: '{n}분 전', agoHour: '{n}시간 전',
88    engage:
89      '편집 전에 하네스를 켜세요: harness 스킬을 호출해 Process를 따르면 됩니다 - ' +
90      'graph MCP, Workflow 엔진, 또는 계획·목표 명세·통과한 비평이 디스크에 있는 Agent Team 대체 실행. ' +
91      '글로 언급하는 것만으로는 켜지지 않습니다.',
92  },
93}
94
95type Key = keyof typeof en
96type S = (key: Key, vars?: Record<string, string | number>) => string
97const strings = (l: 'en' | 'ko'): S => (key, vars) => fmt(STRINGS[l][key], vars)
98
99// an unparseable or partial decision file is no decision
100function parseDecision(text: string): Decision | null {
101  try {
102    const d = JSON.parse(text) as Partial<Decision> | null
103    if (d === null || typeof d !== 'object') return null
104    if (typeof d.ts !== 'number' || typeof d.tool !== 'string' || typeof d.target !== 'string') return null
105    if (d.decision !== 'allow' && d.decision !== 'deny') return null
106    return { ts: d.ts, session_id: d.session_id, tool: d.tool, target: d.target, decision: d.decision, reason: typeof d.reason === 'string' ? d.reason : '' }
107  } catch {
108    return null
109  }
110}
111
112const ago = (s: S, ms: number) => {
113  const m = Math.max(0, Math.round(ms / 60000))
114  return m < 60 ? s('agoMin', { n: m }) : s('agoHour', { n: Math.round(m / 60) })
115}
116
117type Ent = { name: string; kind: string; size: number; mtimeMs: number }
118const asRecord = (v: unknown): Record<string, unknown> | undefined =>
119  typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined
120
121// a list failure means nothing is there
122async function ls($: EngineInterface, path: string): Promise<Ent[]> {
123  try {
124    return (await $.fs.list(path)) as Ent[]
125  } catch {
126    return []
127  }
128}
129
130// a missing, oversized or unparseable file is no file
131async function readJson($: EngineInterface, path: string, ent?: Ent): Promise<Record<string, unknown> | undefined> {
132  if (ent !== undefined && ent.size > MAX_READ) return undefined
133  try {
134    return asRecord(JSON.parse(await $.fs.read(path)))
135  } catch {
136    return undefined
137  }
138}
139
140const firstLine = (v: unknown) => (typeof v === 'string' ? (v.split('\n')[0] ?? '').trim().slice(0, 120) : '')
141
142// the highest n of <prefix>-<n>.<ext> among the names, 0 when none
143const maxN = (names: string[], prefix: string) =>
144  Math.max(0, ...names.map(n => Number(new RegExp(`^${prefix}-(\\d+)\\.`).exec(n)?.[1] ?? 0)))
145
146const records = (v: unknown) =>
147  (Array.isArray(v) ? (v as unknown[]) : []).map(asRecord).filter((r): r is Record<string, unknown> => r !== undefined && typeof r.id === 'string')
148
149// The files of one run, .harness-run/<slug>/ (the Flow and Gate rules tabs); no slug: the newest live run, else the
150// newest by time. Which runs are open, and which one the pane shows, is the node list's and status.ts's call. Why a
151// stage failed is the node's too: `failures` are the row's, and reasonFor reads them. Read only.
152async function scanRun($: EngineInterface, slug: string | null, failures: readonly RowFailure[]): Promise<RunInfo | null> {
153  const now = await $.clock.now()
154  const cands: { slug: string; files: Ent[]; subs: Record<string, Ent[]>; time: number; finished: boolean }[] = []
155  for (const d of await ls($, RUNS)) {
156    if (d.kind !== 'dir' || d.name === 'broker') continue
157    const base = `${RUNS}/${d.name}`
158    const files = await ls($, base)
159    const subs: Record<string, Ent[]> = {}
160    if (files.some(f => f.name === 'subgoals' && f.kind === 'dir')) {
161      for (const sg of await ls($, `${base}/subgoals`)) if (sg.kind === 'dir') subs[sg.name] = await ls($, `${base}/subgoals/${sg.name}`)
162    }
163    // a run's time counts its subgoal files too
164    const all = [...files, ...Object.values(subs).flat()].filter(f => f.kind === 'file')
165    cands.push({
166      slug: d.name, files, subs,
167      time: Math.max(0, ...all.map(f => f.mtimeMs)),
168      finished: files.some(f => f.name === '05-report.md'),
169    })
170  }
171  const isLive = (c: (typeof cands)[number]) => !c.finished && now - c.time < LIVE_MS
172  const newest = (list: typeof cands) => [...list].sort((a, b) => b.time - a.time)[0]
173  const pick = cands.find(c => c.slug === slug) ?? newest(cands.filter(isLive)) ?? newest(cands)
174  if (pick === undefined) return null
175
176  const base = `${RUNS}/${pick.slug}`
177  const has = (name: string) => pick.files.some(f => f.name === name)
178  const get = (name: string) => (has(name) ? readJson($, `${base}/${name}`, pick.files.find(f => f.name === name)) : Promise.resolve(undefined))
179  const manifest = await get('manifest.json')
180  const spec = await get('02-goal-spec.json')
181  const critique = await get('02-critique.json')
182  const gate = await get('04-goal-gate.json')
183
184  // subgoal ids: the manifest's order, then the spec's, then any directory
185  const fromManifest = records(manifest?.subgoals).sort((a, b) => Number(a.order ?? 0) - Number(b.order ?? 0))
186  const fromSpec = records(spec?.subgoals)
187  const titles = new Map(fromSpec.map(r => [String(r.id), typeof r.title === 'string' ? r.title : '']))
188  const ids = [...new Set([...fromManifest.map(r => String(r.id)), ...fromSpec.map(r => String(r.id)), ...Object.keys(pick.subs)])]
189
190  const subs: RunSub[] = []
191  let doing: RunInfo['now'] | undefined
192  for (const id of ids) {
193    const sub = pick.subs[id] ?? []
194    const names = sub.map(f => f.name)
195    const impl = maxN(names, 'impl')
196    const test = maxN(names, 'test')
197    const gn = maxN(names, 'gate')
198    const dir = `${base}/subgoals/${id}`
199    const result = names.includes('result.json') ? await readJson($, `${dir}/result.json`, sub.find(f => f.name === 'result.json')) : undefined
200    const lastGate = gn > 0 ? await readJson($, `${dir}/gate-${gn}.json`, sub.find(f => f.name === `gate-${gn}.json`)) : undefined
201    const attempt = Math.max(1, impl, test, gn)
202    const title = titles.get(id) ?? ''
203    // every verdict, so a reject keeps its reason after the retry
204    const gates: RunSub['gates'] = []
205    for (let n = 1; n <= gn; n++) {
206      const g = n === gn ? lastGate : await readJson($, `${dir}/gate-${n}.json`, sub.find(f => f.name === `gate-${n}.json`))
207      if (g !== undefined) gates.push({ n, pass: g.pass === true, reason: g.pass === true ? '' : reasonFor(failures, `${pick.slug}|gate|${id}|${n}`) })
208    }
209    let state: Mark = impl > 0 ? 'running' : 'pending'
210    if (result?.passed === true) state = 'done'
211    else if (result?.passed === false) state = 'failed'
212    subs.push({
213      id, title, state,
214      reason: state === 'failed' && typeof lastGate?.reason === 'string' ? lastGate.reason : '',
215      tries: Math.max(Number(result?.attempts ?? 0) || 0, attempt),
216      gates, stalled: result?.stalled === true,
217    })
218    // what the first unfinished subgoal is doing
219    if (doing === undefined && result === undefined) {
220      if (impl === 0) doing = { kind: 'implement', id, title, attempt }
221      else if (test < impl) doing = { kind: 'test', id, title, attempt }
222      else if (gn < test) doing = { kind: 'gate', id, title, attempt }
223      else if (lastGate?.pass === false) doing = { kind: 'retry', id, title, attempt: gn + 1 }
224      else doing = { kind: 'gate', id, title, attempt }
225    }
226  }
227
228  const match = typeof gate?.match_pct === 'number' ? gate.match_pct : null
229  const goalPass = gate === undefined ? null : typeof gate.pass === 'boolean' ? gate.pass : match !== null && match >= PASS_PCT
230  const implDone = subs.length > 0 && subs.every(x => x.state === 'done' || x.state === 'failed')
231  const raw: { done: boolean; failed?: boolean }[] = [
232    { done: has('01-plan.md') },
233    { done: spec !== undefined },
234    { done: critique !== undefined && critique.sound !== false, failed: critique?.sound === false },
235    { done: implDone, failed: implDone && subs.some(x => x.state === 'failed') },
236    { done: gate !== undefined, failed: goalPass === false },
237    { done: has('05-report.md') },
238  ]
239  // done up to the first stage that is not; that one runs (or has failed), the rest wait
240  let reached = false
241  const stages = RUN_STAGES.map((key, i) => {
242    const r = raw[i]!
243    let state: Mark = 'pending'
244    if (r.failed) state = 'failed'
245    else if (r.done) state = 'done'
246    else if (!reached) state = 'running'
247    if (state === 'running' || state === 'failed') reached = true
248    return { key, state }
249  })
250  const current = stages.find(g => g.state === 'running' || g.state === 'failed')
251  const nowInfo: RunInfo['now'] =
252    pick.finished || current === undefined
253      ? { kind: 'done' }
254      : current.key === 'implement' && doing !== undefined
255        ? doing
256        : { kind: 'stage', stage: current.key }
257
258  return {
259    slug: pick.slug,
260    title: firstLine(manifest?.request) || firstLine(spec?.goal) || pick.slug,
261    live: isLive(pick), finished: pick.finished, stages, subs,
262    done: subs.filter(x => x.state === 'done').length, total: subs.length,
263    now: nowInfo, match, pass: goalPass,
264    critique: { sound: typeof critique?.sound === 'boolean' ? critique.sound : null, reason: critique?.sound === false ? reasonFor(failures, `${pick.slug}|critique`) : '' },
265    goalReason: goalPass === false ? reasonFor(failures, `${pick.slug}|goal`) : '',
266    lastMs: pick.time,
267  }
268}
269
270// The events to show: each failure the node gives (`failures` of an open run's row, and of a run finished since the
271// session started, which --list leaves out so `--show` is asked, once) written after `start`, and `complete` for a
272// finished run with no failure that gave up. The node decides reason, next step and severity (status.ts failureToast
273// words them); nothing here reads a run file for them. A key shown once is not shown again (the severity is part of the
274// key: a goal gate retry and its later gave-up share the node's key). Read only.
275// `outcome` is the run outcome trophy counts: gave up on a subgoal is fail, on the goal gate reject, a clean report pass
276type RunOutcome = 'pass' | 'reject' | 'fail'
277type RunEvent = { key: string; run: string; text: string; pushText: string | null; timeoutMs?: number; outcome?: RunOutcome }
278const GAVE_UP_OUTCOME: Record<string, RunOutcome> = { result: 'fail', goal: 'reject' } // by the kind in the node's key `<run>|<kind>|…`
279
280const failureEvent = (run: string, f: RowFailure): RunEvent => {
281  const outcome = f.severity === 'gave up' ? GAVE_UP_OUTCOME[f.key.split('|')[1] ?? ''] : undefined
282  return { key: `${f.key}|${f.severity}`, run, ...failureToast(run, f), ...(outcome ? { outcome } : {}) }
283}
284
285// one finished run, as the node shows it; no answer (non-zero exit, timeout, not a row) is null
286async function showRun($: EngineInterface, dir: string): Promise<HarnessRow | null> {
287  try {
288    const out = await $.process.run(showArgv($.plugin.root, dir), { timeoutMs: LIST_TIMEOUT_MS })
289    return out.exitCode === 0 ? parseRow(out.stdout) : null
290  } catch {
291    return null
292  }
293}
294
295async function runEvents($: EngineInterface, start: number, open: readonly HarnessRow[], asked: Set<string>): Promise<RunEvent[]> {
296  const out: RunEvent[] = []
297  const add = (row: HarnessRow) => {
298    for (const f of failuresOf(row)) if (f.at > start) out.push(failureEvent(row.slug, f))
299  }
300  for (const row of open) add(row)
301  const cwd = await $.session.cwd()
302  for (const d of await ls($, RUNS)) {
303    // graph runs (broker/) are pushed by the graph mod, which sees their rejects too
304    if (d.kind !== 'dir' || d.name === 'broker' || asked.has(d.name)) continue
305    const report = (await ls($, `${RUNS}/${d.name}`)).find(f => f.name === '05-report.md')
306    if (report === undefined || report.mtimeMs <= start) continue
307    const row = await showRun($, `${cwd}/${RUNS}/${d.name}`)
308    if (row === null) continue // asked again next tick
309    asked.add(d.name)
310    add(row)
311    if (!failuresOf(row).some(f => f.severity === 'gave up')) {
312      out.push({ key: `${d.name}|complete`, run: d.name, text: `harness ${d.name}: complete — Report (1/1)`, pushText: null, outcome: 'pass' })
313    }
314  }
315  return out
316}
317
318// The open runs from the node CLI (rule 6: the path through $.plugin.root). A non-zero exit, a timeout, a throw or
319// output that is not a list is no answer: null, and the caller keeps its last good list.
320async function loadRows($: EngineInterface): Promise<HarnessRow[] | null> {
321  try {
322    const out = await $.process.run(listArgv($.plugin.root, await $.session.cwd()), { timeoutMs: LIST_TIMEOUT_MS })
323    return out.exitCode === 0 ? parseRows(out.stdout) : null
324  } catch {
325    return null
326  }
327}
328
329// The slug order `[` / `]` walk, fixed until a run opens or closes, or the pane opens from closed or the demo changes
330// (then null: opening order decides again). A cache a reload may lose: the order is then worked out once more.
331let frozen: string[] | null = null
332
333// What the pane and band draw: the live rows, or the demo's; in the frozen opening order.
334async function view($: EngineInterface) {
335  const name = await read($, demo)
336  const open = name === null ? await read($, rows) : demoRows(name)
337  const ordered = frozenOrder(open, await read($, looked), frozen)
338  frozen = ordered.map(r => r.slug)
339  const sel = await read($, selected)
340  return { demo: name, ordered, sel, picked: pickRun(ordered, sel), nowMs: name === null ? await $.clock.now() : DEMO_NOW }
341}
342
343async function paneOpen($: EngineInterface): Promise<boolean> {
344  try {
345    return (await $.ui.panes()).some((p: { id: string }) => p.id === PANE)
346  } catch {
347    return false // panes unreadable: closed
348  }
349}
350
351// The one place the pane is opened from closed, for the command and the band's button alike: the run opening order
352// picks is the run shown from here on, by slug (marking its reject as seen must not move it). Open already: no-op.
353async function openPane($: EngineInterface): Promise<void> {
354  if (await paneOpen($)) return
355  frozen = null // a pane opened from closed orders again: an unseen reject leads
356  const v = await view($)
357  await update($, selected, () => v.picked?.slug ?? null)
358  await update($, paneTab, () => openTab(v.picked !== null))
359  await update($, looked, l => markLooked(l, v.picked))
360  await $.ui.open({ id: PANE, title: 'Harness', focus: true, closeOnEscape: true })
361  await refreshRun($)
362  await kick?.()
363}
364
365// Set at session.start of a session that has a surface, to look at the spinner again with that session's engine (a
366// timer is started from it, not from a command or a draw); no surface, never set, no timer. A cache a reload may lose.
367let kick: (() => Promise<void>) | null = null
368let spinner: { cancel: () => void } | null = null
369
370// The files of the run the Flow and Gate rules tabs show; the demo and no run have none.
371async function refreshRun($: EngineInterface) {
372  try {
373    const v = await view($)
374    const found = v.demo !== null || v.picked === null ? null : await scanRun($, v.picked.slug, failuresOf(v.picked))
375    await update($, run, () => found)
376  } catch {
377    // an unreadable run dir leaves the last run as it was
378  }
379}
380
381// The open runs, read again: the node list, then the run files. Every failure leaves what was there. Returns the live
382// list when the node answered (the status line counts it, also in the demo, which draws demo rows instead), else null.
383async function refresh($: EngineInterface): Promise<HarnessRow[] | null> {
384  let live: HarnessRow[] | null = null
385  try {
386    live = await loadRows($)
387    if (live !== null && (await read($, demo)) === null) await update($, rows, () => live!)
388    await refreshRun($)
389    // a reject that lands while the pane shows the run has been seen
390    if (await paneOpen($)) {
391      const shown = (await view($)).picked
392      await update($, looked, l => markLooked(l, shown))
393    }
394  } catch {
395    // an unreadable list or run dir leaves the last one as it was
396  }
397  await kick?.()
398  return live
399}
400
401// The faster interval: only while a run on screen acts (a pane or the band shows it) and a surface exists; it ends as
402// soon as the run waits, stalls or ends, or the pane and band are gone.
403async function syncSpinner($: EngineInterface) {
404  try {
405    const v = await view($)
406    const shown = shownRows(v.ordered, v.sel, await paneOpen($))
407    const { run: go } = spinnerPlan(shown, (await $.session.surfaces()).length, shown.length > 0)
408    if (go && spinner === null) spinner = $.clock.every(SPIN_MS, () => step($))
409    else if (!go && spinner !== null) {
410      spinner.cancel()
411      spinner = null
412    }
413  } catch {
414    // a failed check leaves the timer as it was
415  }
416}
417async function step($: EngineInterface) {
418  await syncSpinner($)
419  if (spinner !== null) await update($, spin, n => n + 1)
420}
421
422// `[` and `]`: the next run by slug, marked as looked at; one run or none, nothing changes
423async function cycle($: EngineInterface, by: 1 | -1) {
424  const v = await view($)
425  const slug = cycleRun(v.ordered, v.sel, by)
426  if (slug === (v.picked?.slug ?? null)) return // at an end (or one run): nothing changes
427  await update($, selected, () => slug)
428  await update($, looked, l => markLooked(l, pickRun(v.ordered, slug)))
429  await refreshRun($)
430  await kick?.()
431}
432
433export const register: Register = on => {
434  on('session.start', async ($, e, next) => {
435    if ((await $.session.surfaces()).length === 0) return next(e)
436    // a second session.start (a cleared session) starts over: the old interval ends
437    spinner?.cancel()
438    spinner = null
439    frozen = null
440    kick = () => syncSpinner($)
441
442    // a failure that needs you or gave up is pushed as well as toasted; a push not sent or thrown costs nothing more
443    async function push(message: string) {
444      try {
445        await $.tool.call({ tool: 'PushNotification', message, status: 'proactive' } as never)
446      } catch {
447        // a failed push is a push not sent
448      }
449    }
450
451    const startMs = await $.clock.now()
452    // the newest decision timestamp seen; null until the first poll, which only sets the baseline
453    let seenTs: number | null = null
454    // a deny is pushed (one per path per 10 min); a push not sent, or one skipped, is the toast
455    const pushed = new Map<string, number>()
456    async function notifyDeny(target: string, message: string) {
457      let sent = false
458      try {
459        const now = await $.clock.now()
460        const at = pushed.get(target)
461        if (at === undefined || now - at >= PUSH_GAP_MS) {
462          pushed.set(target, now)
463          // PushNotification's result: { message, pushSent?, localSent?, disabledReason? } (user_present at the terminal)
464          const out = (await $.tool.call({ tool: 'PushNotification', message: message.slice(0, 200), status: 'proactive' } as never)) as { result?: unknown }
465          const r = asRecord(out?.result)
466          sent = r?.pushSent === true || r?.localSent === true
467        }
468      } catch {
469        // a failed push is a push not sent
470      }
471      if (!sent) $.ui.toast(message, { timeoutMs: 8000 })
472    }
473
474    // failures and completions of runs, once each, none from before the session started
475    const told = new Set<string>()
476    // one published outcome per (run, outcome): several failed subgoals or a re-written goal gate count once
477    const published = new Set<string>()
478    // finished runs `--show` has answered for
479    const asked = new Set<string>()
480    async function notifyRuns() {
481      try {
482        for (const ev of await runEvents($, startMs, await read($, rows), asked)) {
483          if (told.has(ev.key)) continue
484          told.add(ev.key)
485          const run = ev.run
486          if (ev.outcome !== undefined && !published.has(`${run}|${ev.outcome}`)) {
487            published.add(`${run}|${ev.outcome}`)
488            try {
489              await $.state.set({ plugin: 'harness', key: 'outcome' }, { system: 'harness', outcome: ev.outcome, at: await $.clock.now() })
490            } catch {
491              // fail open: a lost outcome never costs the push
492            }
493          }
494          if (ev.timeoutMs === undefined) $.ui.toast(ev.text)
495          else $.ui.toast(ev.text, { timeoutMs: ev.timeoutMs })
496          if (ev.pushText !== null) await push(ev.pushText)
497        }
498      } catch {
499        // fail open: a read error is no event
500      }
501    }
502
503    async function tick() {
504      try {
505        // the status line: the node's open runs per stage; no answer is no status; the gate's decisions live in /harness-status
506        const live = await refresh($)
507        $.ui.status(live === null ? undefined : stageStatus(live))
508        await notifyRuns()
509        if (!(await $.fs.exists(CONFIG))) {
510          await update($, armed, () => false)
511          await update($, last, () => null)
512          await update($, broken, () => false)
513          return
514        }
515        let cfg: { patterns?: unknown; window_hours?: unknown }
516        try {
517          cfg = JSON.parse(await $.fs.read(CONFIG)) as typeof cfg
518        } catch (err) {
519          if (err instanceof SyntaxError) await update($, broken, () => true)
520          throw err
521        }
522        await update($, broken, () => false)
523        const list = Array.isArray(cfg.patterns) ? cfg.patterns.map(String) : []
524        const hours = Number(cfg.window_hours) > 0 ? Number(cfg.window_hours) : 2
525        let decision: Decision | null = null
526        if (await $.fs.exists(DECISION)) decision = parseDecision(await $.fs.read(DECISION))
527        await update($, patterns, () => list)
528        await update($, windowHours, () => hours)
529        await update($, armed, () => true)
530        await update($, last, () => decision)
531        if (decision) {
532          if (seenTs !== null && decision.ts > seenTs && decision.decision === 'deny') {
533            // teams' dispatch gate has no toast of its own, so this is the one toast when the gates meet
534            const meet = await $.fs.exists(TEAMS_CONFIG)
535            await notifyDeny(
536              decision.target,
537              meet
538                ? `⛔ harness and teams gates both blocked ${decision.tool}: ${decision.target} — simple dev: graph/harness; spec, planning, QA or unsure: teams:orchestrate`
539                : `⛔ goal gate blocked ${decision.tool}: ${decision.target} — finish the harness run, don't script around it`,
540            )
541          }
542          seenTs = Math.max(seenTs ?? 0, decision.ts)
543        } else if (seenTs === null) seenTs = 0
544      } catch {
545        // a read error leaves the gate state as it was
546      }
547    }
548
549    // Claude Code's own language setting, read once per session
550    try {
551      const language = (await $.settings.read()).language
552      await update($, lang, () => (isKorean(language) ? 'ko' : 'en'))
553    } catch {
554      // unreadable settings: English
555    }
556    await $.command.register({ name: 'harness-status', description: STRINGS[await read($, lang)].cmdDesc, argumentHint: 'demo [minimal|full|parallel|narrow|off]' })
557    // a project hook copy that differs from this plugin's own is out of date (installed once, never refreshed)
558    try {
559      const copy = '.claude/hooks/goal-gate.mjs'
560      if ((await $.fs.exists(copy)) && (await $.fs.read(copy)) !== (await $.fs.read(`${$.plugin.root}/hooks/goal-gate.mjs`))) {
561        $.ui.toast('⚠ project goal gate is out of date — run harness:update', { timeoutMs: 8000 })
562      }
563    } catch {
564      // unreadable: say nothing
565    }
566    await tick()
567    const first = openTab((await view($)).picked !== null)
568    await update($, paneTab, () => first)
569    $.clock.every(TICK_MS, tick)
570
571    return next(e)
572  })
573
574  // The command opens the pane on the run to look at (Now), or on the gate rules when no run is open; again, it
575  // closes it. Esc and q close it too (closeOnEscape, the close button). `demo [name|off]` draws the fixtures instead
576  // of the live runs. The answer is one line: the headless reply.
577  on('command.run', { command: 'harness-status' }, async ($, e) => {
578    const text = STRINGS[await read($, lang)]
579    const want = parseDemoArg(e.args ?? '', await read($, demo))
580    const isOpen = await paneOpen($)
581    if (want === null && isOpen) {
582      await $.ui.close({ id: PANE })
583      await kick?.()
584      return { text: text.paneClosed }
585    }
586    if (want !== null) {
587      await update($, demo, () => (want === 'off' ? null : want))
588      await update($, selected, () => null)
589      frozen = null
590      await refresh($)
591    }
592    if (want === 'off') return { text: text.demoOff }
593    if (isOpen) {
594      // a demo switch while open: the run shown is picked again, by slug
595      const v = await view($)
596      await update($, selected, () => v.picked?.slug ?? null)
597      await refreshRun($)
598      await kick?.()
599    } else await openPane($)
600    return { text: want === null ? text.paneOpened : fmt(text.demoOn, { name: want }) }
601  })
602
603  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
604    const { Box, Button, Input, Text } = $.ui.resolve(e)
605    const ui = { Box, Text, Button }
606    const s = strings(await read($, lang))
607    const v = await view($)
608    const r = v.picked
609    const files = await read($, run)
610    const ri = files !== null && r !== null && files.slug === r.slug ? files : null
611    const tab = await read($, paneTab)
612    const now = v.nowMs
613    const closeBtn = <Button key="close" role="dismiss" label={s('closeBtn')} hotkey="q" onPress={() => $.ui.close({ id: PANE })} />
614    const labels = Object.fromEntries(
615      (['now', 'flow', 'findings', 'rules'] as const).map(k => [k, { label: s(`tab${cap(k)}` as Key), short: s(k === 'rules' ? 'tabRulesShort' : (`tab${cap(k)}` as Key)) }]),
616    ) as TabLabels
617    const ctx: PaneCtx = {
618      width: innerWidth(e.props.bodyColumns), nowMs: now, tick: await read($, spin),
619      pos: runPosition(v.ordered, v.sel), other: otherRunLabel(v.ordered, v.sel), tab,
620    }
621    const plan = tabRowPlan(ctx, labels)
622    const tabRow = tabs(ui, plan.items, tab, k => update($, paneTab, () => k as PaneTab))
623    // `[` and `]` cannot be a Button hotkey (one digit or lowercase letter; the engine refuses them): the pane's Input has
624    // the focus ring when the pane is opened with focus (the moment hotkeys are armed), takes every printable key, and
625    // status.ts paneKey reads the last one; prev / next are Buttons for the pointer. The same Input takes a typed
626    // `/command` (card 55): held until Enter (paneKey fires no key on text holding `/`), then paneSlash maps it:
627    // `/harness-status` closes the pane, `/name args` runs that command. $.command.run is not awaited: awaited inside
628    // onSubmit the host cuts the hook at its 10s budget.
629    const onKey = async (text: string) => {
630      const key = paneKey(text)
631      if (key === null) return
632      if (key.kind === 'step') await cycle($, key.by)
633      else if (key.kind === 'tab') await update($, paneTab, () => key.tab)
634      else await $.ui.close({ id: PANE })
635    }
636    const onSubmit = async (text: string) => {
637      const slash = paneSlash(text)
638      if (slash === null) return
639      if (slash.kind === 'close') await $.ui.close({ id: PANE })
640      else void $.command.run({ command: slash.command, args: slash.args }).catch(() => {})
641    }
642    // prev/next join the keys row only where harness-draw's footerFits says they fit (the keys stay one row; [ and ] still step)
643    const steps =
644      footerFits({ lead: s('keysLead'), tail: s('keysTail'), prev: s('prev'), next: s('next') }, ctx.width, v.ordered.length).steps ? (
645        <Box columnGap={2} flexShrink={1} overflow="hidden">
646          <Button key="prev" plain label={s('prev')} onPress={() => cycle($, -1)} />
647          <Button key="next" plain label={s('next')} onPress={() => cycle($, 1)} />
648        </Box>
649      ) : null
650
651    // the gate's own rules and its last decision (the part of the pane that answers a deny)
652    const rules = async () => {
653      if (!(await read($, armed))) return <Text>{s((await read($, broken)) ? 'badGate' : 'noGate')}</Text>
654      const list = await read($, patterns)
655      const hours = await read($, windowHours)
656      const d = await read($, last)
657      return (
658        <Box flexDirection="column">
659          <Text>{s('gated', { n: list.length, list: list.join(', ') })}</Text>
660          <Text>{s('window', { h: hours })}</Text>
661          {d === null ? (
662            <Text>{s('noDecision')}</Text>
663          ) : (
664            <Box flexDirection="column">
665              <Text>{s('lastDecision', { decision: d.decision, tool: d.tool, target: d.target, ago: ago(s, now - d.ts) })}</Text>
666              <Text>{s('reason', { reason: d.reason })}</Text>
667            </Box>
668          )}
669          <Text>{s('engage')}</Text>
670        </Box>
671      )
672    }
673
674    // Now and Findings are drawn from the row (harness-draw); Flow and Gate rules read the run's files
675    const kind = tab === 'rules' ? 'detail' : 'flow'
676    let body
677    if (r === null) {
678      body = tab === 'rules' ? await rules() : <Text>{s('noRun')}</Text>
679    } else if (tab === 'now' || tab === 'findings') {
680      body = renderLines(ui, paneContent(r, ctx))
681    } else if (ri === null) {
682      body = tab === 'rules' ? await rules() : <Text>{s(v.demo === null ? 'noRun' : 'demoFiles')}</Text>
683    } else {
684      const reasonLine = (text: string, pad: number, key: string) =>
685        text === '' ? null : <Text key={key} color="error" wrap="truncate-end">{`${' '.repeat(pad)}↳ ${text}`}</Text>
686      const progress =
687        ri.match !== null
688          ? (
689            <Box>
690              <Text>{`${s('goalGate')} `}</Text>
691              {bar(ui, ri.match, 100, BAR, s('passBar', { pct: ri.match, bar: PASS_PCT }))}
692            </Box>
693          )
694          : bar(ui, ri.done, ri.total, BAR, `${ri.done}/${ri.total}`)
695      const rows: unknown[] = []
696      if (kind === 'flow') {
697        // stages in order; each subgoal opens into its gate verdicts, a retry one level under the reject it answers
698        flowLines(ri).forEach((l, i) => {
699          const pad = l.kind === 'attempt' ? 2 + Math.min(l.depth, 4) * 2 : 0
700          const name =
701            l.kind === 'stage' ? s(`stage${cap(l.stage!)}` as Key)
702            : l.kind === 'sub' ? `${l.id}${l.title ? ` ${l.title}` : ''}`
703            : s('tryNo', { n: l.n ?? 0 })
704          rows.push(
705            <Text key={`f${i}`} wrap="truncate-end">
706              {' '.repeat(pad)}
707              <Text color={TINT[l.state]}>{MARK[l.state]}</Text>
708              {` ${name}`}
709            </Text>,
710          )
711          const why = reasonLine(l.reason, pad + 2, `w${i}`)
712          if (why !== null) rows.push(why)
713        })
714      } else {
715        // per subgoal: the result and every gate verdict; the critique and the goal gate when they rejected
716        if (ri.critique.sound === false) {
717          rows.push(<Text key="c" color="error" wrap="truncate-end">{`${MARK.failed} ${s('critiqueRejected')}`}</Text>)
718          const why = reasonLine(ri.critique.reason, 2, 'cw')
719          if (why !== null) rows.push(why)
720        }
721        ri.subs.forEach((x, i) => {
722          rows.push(<Text key={`s${i}`} wrap="truncate-end"><Text color={TINT[x.state]}>{MARK[x.state]}</Text>{` ${x.id}${x.title ? ` ${x.title}` : ''}`}</Text>)
723          const result = x.state === 'done' ? s('resPassed', { n: x.tries }) : x.state === 'failed' ? s('resFailed', { n: x.tries }) : s('resNone')
724          rows.push(<Text key={`r${i}`} dimColor wrap="truncate-end">{`  ${result}${x.stalled ? ` · ${s('stalled')}` : ''}`}</Text>)
725          x.gates.forEach(gt =>
726            rows.push(
727              <Text key={`g${i}-${gt.n}`} color={gt.pass ? undefined : 'error'} wrap="truncate-end">
728                {`  ${s(gt.pass ? 'gatePassed' : 'gateRejected', { n: gt.n })}${gt.reason !== '' && !gt.pass ? ` — ${gt.reason}` : ''}`}
729              </Text>,
730            ),
731          )
732        })
733        if (ri.goalReason !== '' && ri.pass === false) {
734          rows.push(<Text key="gg" color="error" wrap="truncate-end">{`${MARK.failed} ${s('goalGate')}`}</Text>)
735          const why = reasonLine(ri.goalReason, 2, 'ggw')
736          if (why !== null) rows.push(why)
737        }
738      }
739      body = (
740        <Box flexDirection="column">
741          <Box flexDirection="column">
742            {rows.slice(0, LINE_MAX)}
743            {rows.length > LINE_MAX && <Text dimColor>{`  ${s('more', { n: rows.length - LINE_MAX })}`}</Text>}
744          </Box>
745          {progress}
746          {kind === 'detail' && (
747            <Box flexDirection="column" marginTop={1}>
748              <Text bold>{s('rules')}</Text>
749              {await rules()}
750            </Box>
751          )}
752        </Box>
753      )
754    }
755
756    // the header, Now / last step / You and the rail are harness-draw's lines; the tab row and the keys are Buttons
757    return (
758      <Box flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
759        {r === null ? <Text bold wrap="truncate-end">{s('paneTitle')}</Text> : renderLines(ui, paneHead(r, ctx))}
760        {body}
761        <Box marginTop={1} justifyContent="space-between">
762          <Box flexShrink={0}>{tabRow}</Box>
763          {plan.right !== '' && <Box flexShrink={1} marginLeft={2}><Text dimColor wrap="truncate-end">{plan.right}</Text></Box>}
764        </Box>
765        <Box columnGap={1}>
766          <Box flexShrink={0}><Text dimColor wrap="truncate-end">{s('keysLead')}</Text></Box>
767          {closeBtn}
768          <Box flexShrink={0}><Text dimColor wrap="truncate-end">{s('keysTail')}</Text></Box>
769          {steps}
770          {(e.surface === 'terminal' || e.surface === 'desktop' || e.surface === 'vscode') && (
771            <Box flexShrink={1} height={1} overflow="hidden"><Input key="keys" autoFocus value="" placeholder="" onInput={onKey} onSubmit={onSubmit} /></Box>
772          )}
773        </Box>
774      </Box>
775    )
776  })
777
778  // the band: three rows for the leading harness run (what it is doing and whether it waits on you / how far / what
779  // it cost and what came back last), `+N` for the others. Graph runs are the graph mod's: no row for them here.
780  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
781    const v = await view($)
782    if (e.props.hasSurvey || v.ordered.length === 0) return next(e)
783    const { Box, Text, Button } = $.ui.resolve(e)
784    const label = STRINGS[await read($, lang)].bandOpen
785    const [row1, ...rest] = bandLines(v.ordered, { width: e.props.bodyColumns, nowMs: v.nowMs, tick: await read($, spin), reserve: cells(label) + 5 }) // the Button draws `[ label ]` (4 cells of chrome) after a 1-column margin
786    return (
787      <Box flexDirection="column">
788        <Box>
789          <Box flexShrink={1}>{renderLines({ Box, Text, Button }, [row1])}</Box>
790          <Box flexShrink={0} marginLeft={1}><Button key="open" label={label} onPress={() => openPane($)} /></Box>
791        </Box>
792        {renderLines({ Box, Text, Button }, rest)}
793        {await next(e)}
794      </Box>
795    )
796  })
797}
798
hooks/draw.tsx 95 lines
1/*
2 * Drawing kit for mods: stage rail, progress bar, tabs, board.
3 * Origin: teams/hooks/mod.tsx (teams 0.46.0). Copied per plugin because a mod imports only its own
4 * plugin's files; copies may drift, so change one and diff the other.
5 */
6export type Mark = 'done' | 'running' | 'pending' | 'failed'
7
8export const MARK: Record<Mark, string> = { done: '✔', running: '●', pending: '○', failed: '✘' }
9// the stage rail: a dot per stage, a solid rail up to where the run is, dotted after
10export const DOT: Record<Mark, string> = { done: '●', running: '◉', pending: '○', failed: '✘' }
11export const TINT: Record<Mark, string> = { done: 'success', running: 'claude', pending: 'inactive', failed: 'error' }
12
13// a key the table lacks formats to ''
14export const fmt = (text: string | undefined, vars: Record<string, string | number> = {}) =>
15  (text ?? '').replace(/\{(\w+)\}/g, (_, k: string) => String(vars[k] ?? ''))
16
17export const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
18
19// Claude Code's `language` setting
20export const isKorean = (language: unknown) => typeof language === 'string' && /^(ko|korean|한국어)/i.test(language)
21
22// filled cells of a bar `width` wide, clamped to 0..width
23export const cells = (done: number, total: number, width: number) =>
24  total > 0 ? Math.min(width, Math.max(0, Math.round((width * done) / total))) : 0
25
26// between two stages: solid once the next stage has started, dotted before
27export const connector = (nextState: Mark) => (nextState !== 'pending' ? ' ━━ ' : ' ┄┄ ')
28
29// the resolved components from $.ui.resolve(e)
30export type Ui = { Box: any; Text: any; Button: any }
31
32export function rail(ui: Ui, stages: { label: string; state: Mark }[]) {
33  const { Box, Text } = ui
34  return (
35    <Box flexWrap="wrap">
36      {stages.map((g, i) => {
37        const next = stages[i + 1]
38        return (
39          <Box key={`g${i}`}>
40            <Text color={TINT[g.state]} bold={g.state === 'running'}>{`${DOT[g.state]} ${g.label}`}</Text>
41            {next !== undefined && (
42              <Text color={next.state !== 'pending' ? 'success' : 'inactive'}>{connector(next.state)}</Text>
43            )}
44          </Box>
45        )
46      })}
47    </Box>
48  )
49}
50
51export function bar(ui: Ui, done: number, total: number, width: number, suffix?: string) {
52  const { Box, Text } = ui
53  const filled = cells(done, total, width)
54  return (
55    <Box>
56      <Text color="success">{'━'.repeat(filled)}</Text>
57      <Text color="inactive">{'─'.repeat(width - filled)}</Text>
58      {suffix !== undefined && <Text bold>{`  ${suffix}`}</Text>}
59    </Box>
60  )
61}
62
63// plain tabs with hotkeys 1-9: the selected one in full strength with a dot, the rest dim
64export function tabs(ui: Ui, items: { key: string; label: string }[], current: string, onPick: (key: string) => void) {
65  const { Box, Button } = ui
66  return (
67    <Box columnGap={3}>
68      {items.map((one, i) => (
69        <Button key={one.key} plain hotkey={String(i + 1)} dimColor={current !== one.key}
70          label={`${current === one.key ? '● ' : ''}${one.label}`} onPress={() => onPick(one.key)} />
71      ))}
72    </Box>
73  )
74}
75
76// columns of bordered cards, each with a count in its title
77export function board<T>(
78  ui: Ui,
79  cols: { label: string; tint: string; items: T[] }[],
80  render: (item: T, i: number) => unknown,
81) {
82  const { Box, Text } = ui
83  const width = `${Math.floor(100 / Math.max(cols.length, 1))}%`
84  return (
85    <Box>
86      {cols.map(col => (
87        <Box key={col.label} flexDirection="column" width={width} borderStyle="round" borderColor={col.tint} paddingX={1}>
88          <Text bold color={col.tint}>{`${col.label} ${col.items.length}`}</Text>
89          {col.items.map(render)}
90        </Box>
91      ))}
92    </Box>
93  )
94}
95
hooks/harness-draw.tsx 526 lines
1/*
2 * Harness-only drawing: the state glyphs, the layout of the pane and the three-row band as lines of styled
3 * segments, and the demo fixtures. Pure: every function takes a row (status.ts) and a width and returns lines;
4 * mod.tsx only renders them (renderLines). draw.tsx stays the copy shared with graph, so nothing here edits it.
5 *
6 * Width is counted in code points: every glyph used is one column in a terminal.
7 */
8import type { HarnessRow, PaneTab, RowStage } from '../types'
9import type { Ui } from './draw'
10import {
11  costText, countsText, cycleRun, doingOf, elapsedText, inStageText, isActing, lastStep, latestRound, openingOrder, otherRunLabel,
12  pickRun, railItems, rankedProblems, restLine, roundHeading, roundText, runCount, runPosition, runState, severityOf,
13  topFinding, waitsOnYou, youLine,
14} from './status'
15import type { RailItem, RailMark } from './status'
16
17/* --- glyphs: only these nine mark state; no faces --- */
18
19export const GLYPH = { edit: '✎', read: '⌕', run: '▸', think: '…', judge: '⚖', done: '✔', fail: '✘', idle: '◌', you: '⚑' } as const
20export const STATE_GLYPHS: readonly string[] = Object.values(GLYPH)
21export const RAIL_MARK: Record<RailMark, string> = { done: GLYPH.done, failed: GLYPH.fail, current: '●', pending: '○' }
22// rail connectors and dots, and the plain typography the text uses; with the nine, everything the pane may print beyond ASCII
23export const RAIL_GLYPHS: readonly string[] = ['━', '┄', '●', '○']
24export const TYPOGRAPHY: readonly string[] = ['·', '—', '↳', '◀', '▶', '─', '│', '╭', '╮', '╰', '╯']
25export const ALLOWED: readonly string[] = [...STATE_GLYPHS, ...RAIL_GLYPHS, ...TYPOGRAPHY]
26
27// the spinner: the action glyphs that fit the stage, one frame per tick
28const FRAMES: Record<RowStage, readonly string[]> = {
29  plan: [GLYPH.edit, GLYPH.think],
30  setgoal: [GLYPH.edit, GLYPH.think],
31  critique: [GLYPH.judge, GLYPH.think],
32  implement: [GLYPH.edit, GLYPH.read, GLYPH.run],
33  gate: [GLYPH.judge, GLYPH.think],
34  report: [GLYPH.edit, GLYPH.think],
35}
36export function spinnerFrame(tick: number, stage: RowStage = 'implement'): string {
37  const frames = FRAMES[stage]
38  const i = Number.isFinite(tick) ? Math.trunc(tick) : 0
39  return frames[((i % frames.length) + frames.length) % frames.length]!
40}
41
42// One glyph for the run: waits on you ⚑; acting, the spinner frame; otherwise idle ◌ (waiting on a vendor, stalled, no now.json)
43export const stateGlyph = (r: HarnessRow, tick: number) => (waitsOnYou(r) ? GLYPH.you : isActing(r) ? spinnerFrame(tick, r.stage) : GLYPH.idle)
44
45/* --- lines of segments --- */
46
47export type Tint = 'success' | 'claude' | 'inactive' | 'error'
48export type Seg = { t: string; tint?: Tint; bold?: boolean; dim?: boolean }
49export type Line = Seg[]
50
51const seg = (t: string, o: Omit<Seg, 't'> = {}): Seg => ({ t, ...o })
52export const plain = (l: Line) => l.map(s => s.t).join('')
53export const width = (s: string) => Array.from(s).length
54export const lineWidth = (l: Line) => l.reduce((n, s) => n + width(s.t), 0)
55
56// cut to w columns; the cut ends in …
57export function clipLine(l: Line, w: number): Line {
58  if (lineWidth(l) <= w) return l
59  if (w <= 0) return []
60  const out: Line = []
61  let left = w - 1
62  for (const s of l) {
63    if (left <= 0) break
64    const cs = Array.from(s.t)
65    if (cs.length <= left) {
66      out.push(s)
67      left -= cs.length
68    } else {
69      out.push({ ...s, t: cs.slice(0, left).join('') })
70      break
71    }
72  }
73  const last = out[out.length - 1]
74  if (last === undefined) return [seg('…')]
75  out[out.length - 1] = { ...last, t: `${last.t.trimEnd()}…` }
76  return out
77}
78
79export const clip = (text: string, w: number) => plain(clipLine([seg(text)], w))
80
81// A row of segments that must fit w. Lowest priority goes first: `drop` > 0 segments leave in descending order,
82// each first cut to `min` columns (… at the cut) when it has one; segments with no `drop` never leave, and only
83// truncate (widest first) unless `fixed`. `right` on the last segment pads it to the right edge. Never wider than w.
84export type FitSeg = { parts: Seg[]; sep?: string; drop?: number; min?: number; fixed?: boolean; right?: boolean }
85export const fs = (text: string, o: Omit<FitSeg, 'parts'> & Omit<Seg, 't'> = {}): FitSeg => {
86  const { sep, drop, min, fixed, right, ...style } = o
87  return { parts: [seg(text, style)], sep, drop, min, fixed, right }
88}
89const fw = (f: FitSeg) => lineWidth(f.parts)
90
91export function fit(input: readonly FitSeg[], w: number): Line {
92  const segs = input.filter(f => fw(f) > 0)
93  const total = () => segs.reduce((n, f, i) => n + (i > 0 ? width(f.sep ?? '') : 0) + fw(f), 0)
94  while (total() > w) {
95    let top = -1
96    segs.forEach((f, i) => {
97      if ((f.drop ?? 0) > 0 && (top < 0 || f.drop! >= segs[top]!.drop!)) top = i
98    })
99    if (top < 0) break
100    const f = segs[top]!
101    const over = total() - w
102    if (f.min !== undefined && fw(f) > f.min) segs[top] = { ...f, parts: clipLine(f.parts, Math.max(f.min, fw(f) - over)) }
103    else segs.splice(top, 1)
104  }
105  while (total() > w) {
106    let wide = -1
107    segs.forEach((f, i) => {
108      if (!f.fixed && (f.drop ?? 0) === 0 && fw(f) > 2 && (wide < 0 || fw(f) > fw(segs[wide]!))) wide = i
109    })
110    if (wide < 0) break
111    const f = segs[wide]!
112    // the widest gives way toward the next widest, so several long segments share the cut
113    const next = Math.max(0, ...segs.filter((g, i) => i !== wide && !g.fixed && (g.drop ?? 0) === 0).map(fw))
114    segs[wide] = { ...f, parts: clipLine(f.parts, Math.max(2, fw(f) - (total() - w), Math.min(next, fw(f) - 1))) }
115  }
116  const out: Line = []
117  const pad = w - total()
118  segs.forEach((f, i) => {
119    if (i > 0 && f.sep) out.push(seg(f.sep, { dim: true }))
120    if (f.right && i === segs.length - 1 && i > 0 && pad > 0) out.push(seg(' '.repeat(pad)))
121    out.push(...f.parts)
122  })
123  return clipLine(out, w)
124}
125
126// left text, right text on the same line: the right side sheds low-priority pieces first, then the left truncates
127export function leftRight(left: Line, rightSegs: readonly FitSeg[], w: number, minLeft = 10): Line {
128  const right = fit(rightSegs, Math.max(0, w - Math.min(lineWidth(left), minLeft) - 2))
129  const rw = lineWidth(right)
130  const l = clipLine(left, w - rw - (rw > 0 ? 2 : 0))
131  return [...l, seg(' '.repeat(Math.max(rw > 0 ? 2 : 0, w - lineWidth(l) - rw))), ...right]
132}
133
134// a plain bordered frame for the demo text; lines are padded or cut to the inside width
135export function frame(title: string, lines: readonly Line[], w: number): string[] {
136  const inner = w - 4
137  const top = `╭─ ${title} ${'─'.repeat(Math.max(0, w - 5 - width(title)))}╮`
138  const body = lines.map(l => {
139    const c = clipLine(l, inner)
140    return `│ ${plain(c)}${' '.repeat(inner - lineWidth(c))} │`
141  })
142  return [clip(top, w), ...body, `╰${'─'.repeat(w - 2)}╯`]
143}
144
145// the one place Ink is touched: lines of segments as Text
146export function renderLines(ui: Ui, lines: readonly Line[]) {
147  const { Box, Text } = ui
148  return (
149    <Box flexDirection="column">
150      {lines.map((l, i) => (
151        <Text key={i} wrap="truncate-end">
152          {l.length === 0 ? ' ' : l.map((s, j) => <Text key={j} color={s.tint} bold={s.bold} dimColor={s.dim}>{s.t}</Text>)}
153        </Text>
154      ))}
155    </Box>
156  )
157}
158
159/* --- the rail --- */
160
161const MARK_TINT: Record<RailMark, Tint> = { done: 'success', failed: 'error', current: 'claude', pending: 'inactive' }
162const SEV_TINT = { blocker: 'error', major: 'error', minor: 'claude', nit: 'inactive' } as const
163
164// `✔ Plan ━━ ✔ SetGoal ━━ ✘ Critique ━━ ● SetGoal again ┄┄ ○ Critique ┄┄ ○ Subgoals 0/3 ┄┄ ○ Goal gate ┄┄ ○ Report`
165// compact: short labels, single connectors
166export function railLine(items: readonly RailItem[], compact: boolean): Line {
167  const out: Line = []
168  items.forEach((it, i) => {
169    out.push(seg(`${RAIL_MARK[it.mark]} ${compact ? it.short : it.label}`, { tint: MARK_TINT[it.mark], bold: it.mark === 'current' }))
170    const next = items[i + 1]
171    if (next !== undefined) {
172      const solid = next.mark !== 'pending'
173      out.push(seg(compact ? (solid ? ' ━ ' : ' ┄ ') : solid ? ' ━━ ' : ' ┄┄ ', { tint: solid ? 'success' : 'inactive' }))
174    }
175  })
176  return out
177}
178
179// the rail at the width it is given: full labels when they fit, else the compact one, cut with … at last
180function railFit(items: readonly RailItem[], w: number): Line {
181  const full = railLine(items, false)
182  return clipLine(lineWidth(full) <= w ? full : railLine(items, true), w)
183}
184
185const bar = (done: number, total: number, cells: number) => {
186  const filled = total > 0 ? Math.min(cells, Math.max(0, Math.round((cells * done) / total))) : 0
187  return '━'.repeat(filled) + '─'.repeat(cells - filled)
188}
189
190/* --- the pane --- */
191
192export type PaneCtx = {
193  width: number // columns inside the frame
194  nowMs: number
195  tick: number
196  pos: { k: number; n: number }
197  other: string | null // otherRunLabel
198  tab: PaneTab
199  maxLines?: number // cap on a findings list before `+N more`
200}
201
202const compactAt = (inner: number) => inner < 150
203const TABS: { key: PaneTab; label: string; short: string }[] = [
204  { key: 'now', label: 'Now', short: 'Now' },
205  { key: 'flow', label: 'Flow', short: 'Flow' },
206  { key: 'findings', label: 'Findings', short: 'Findings' },
207  { key: 'rules', label: 'Gate rules', short: 'Rules' },
208]
209
210const glyphSeg = (g: string): Seg => seg(g, { tint: g === GLYPH.idle ? 'inactive' : 'claude', bold: true })
211// the Now line's own glyph: the spinner while the run acts, otherwise idle (⚑ belongs to the You line)
212const nowGlyph = (r: HarnessRow, tick: number) => (isActing(r) ? spinnerFrame(tick, r.stage) : GLYPH.idle)
213
214export function headerLine(r: HarnessRow, c: PaneCtx): Line {
215  const compact = compactAt(c.width)
216  const multi = c.pos.n > 1
217  const state = runState(r)
218  const runs = compact ? `${runCount(c.pos, true)}${multi ? ' ◀▶' : ''}` : `${runCount(c.pos)}${multi ? ' ◀ [ ] ▶' : ''}`
219  const right = [
220    fs(state, { tint: r.stalled ? 'error' : waitsOnYou(r) ? 'claude' : 'success', drop: 2 }),
221    fs(elapsedText(r, c.nowMs), { sep: ' · ', drop: 4 }),
222    fs(costText(r), { sep: ' · ', drop: 3 }),
223    fs(runs, { sep: ' · ', fixed: true }),
224  ]
225  return leftRight([seg(r.slug, { bold: true })], right, c.width)
226}
227
228const nowLine = (r: HarnessRow, c: PaneCtx, compact: boolean): Line => {
229  const d = doingOf(r)
230  const left: Line = [glyphSeg(nowGlyph(r, c.tick)), seg(compact ? ' ' : ' Now   ', { dim: true }), seg(d.text, d.canned ? { dim: true } : {})]
231  return leftRight(left, [fs(roundText(r, compact), { drop: 1 }), fs(inStageText(r, c.nowMs, compact), { sep: ' · ', drop: 2 })], c.width, 20)
232}
233
234const lastLine = (r: HarnessRow, c: PaneCtx, compact: boolean): Line => {
235  const s = lastStep(r, c.nowMs)
236  return leftRight([seg(compact ? '  last: ' : '        last step: ', { dim: true }), seg(s.text)], [fs(s.age, { dim: true, drop: 1 })], c.width, 20)
237}
238
239const youLineOf = (r: HarnessRow, c: PaneCtx, compact: boolean): Line => {
240  const y = youLine(r)
241  const head = y.you ? seg(GLYPH.you, { tint: 'claude', bold: true }) : seg(' ')
242  return clipLine([head, seg(compact ? ' ' : ' You   ', { dim: true }), seg(y.text, y.you ? { bold: true } : {})], c.width)
243}
244
245const problemLine = (p: { n: number; severity: keyof typeof SEV_TINT; text: string }, w: number, compact: boolean): Line =>
246  fit([
247    fs(`  ${p.n}${compact ? ' ' : '  '}`, { fixed: true }),
248    fs(p.severity.padEnd(7), { fixed: true, tint: SEV_TINT[p.severity] }),
249    fs(p.text, { sep: '  ' }),
250  ], w)
251
252const TAB_NUM: Record<PaneTab, number> = { now: 1, flow: 2, findings: 3, rules: 4 }
253
254// the Now tab's findings block: the latest round's verdict, its top two, and what is left
255function nowFindings(r: HarnessRow, c: PaneCtx, compact: boolean): Line[] {
256  const rd = latestRound(r)
257  const heading = roundHeading(rd, compact)
258  if (heading === null) return [[seg('No critique round yet', { dim: true })]]
259  const out: Line[] = [clipLine([seg(heading, { bold: true })], c.width)]
260  const ranked = rankedProblems(rd)
261  ranked.slice(0, 2).forEach(p => out.push(problemLine(p, c.width, compact)))
262  const rest = restLine(rd, 2)
263  if (rest !== '') out.push(clipLine([seg(`     ${rest} · Findings ${compact ? '' : '('}${TAB_NUM.findings}${compact ? '' : ')'}`, { dim: true })], c.width))
264  return out
265}
266
267// the Findings tab: the node's rollup over every round, then each round's problems
268function findingsBody(r: HarnessRow, c: PaneCtx, compact: boolean): Line[] {
269  const max = c.maxLines ?? 14
270  const out: Line[] = [clipLine([seg(`All rounds · ${countsText(r.severity)}`, { bold: true })], c.width)]
271  if (r.rounds.length === 0) return [...out, [seg('No critique round yet', { dim: true })]]
272  for (const rd of r.rounds) {
273    out.push([])
274    out.push(clipLine([seg(roundHeading(rd, compact) ?? '', { bold: true })], c.width))
275    for (const p of rankedProblems(rd)) out.push(problemLine(p, c.width, compact))
276  }
277  if (out.length <= max) return out
278  return [...out.slice(0, max - 1), [seg(`  +${out.length - (max - 1)} more lines`, { dim: true })]]
279}
280
281// The tab row's right side: the run `]` would open, else how many more there are, else nothing; whichever fits `room`
282function otherSide(c: PaneCtx, room: number): string {
283  const more = c.pos.n - 1
284  const short = more > 0 ? `+${more} run${more > 1 ? 's' : ''}` : ''
285  const right = c.other !== null && width(c.other) <= room ? c.other : short
286  return width(right) <= room ? right : ''
287}
288
289export function tabLine(c: PaneCtx, compact: boolean): Line {
290  const left: Line = []
291  TABS.forEach((t, i) => {
292    const current = t.key === c.tab
293    const n = TAB_NUM[t.key]
294    left.push(seg(`${current ? '● ' : ''}${compact ? `${t.short} ${n}` : `${t.label} (${n})`}`, { bold: current, dim: !current }))
295    if (i < TABS.length - 1) left.push(seg(compact ? '  ' : '   '))
296  })
297  return leftRight(left, [fs(otherSide(c, c.width - lineWidth(left) - 2), { dim: true })], c.width, lineWidth(left))
298}
299
300export type TabLabels = Record<PaneTab, { label: string; short: string }>
301export const TAB_LABELS: TabLabels = Object.fromEntries(TABS.map(t => [t.key, { label: t.label, short: t.short }])) as TabLabels
302
303// The live tab row: Buttons (hotkeys 1-4) on the left, the other-run label on the right. Each Button draws as
304// `<n>: <label>` with `● ` on the current one, and the row never wraps: the compact labels when the full ones do
305// not fit, and the right side only when it fits what is left.
306export function tabRowPlan(c: PaneCtx, labels: TabLabels = TAB_LABELS): { items: { key: PaneTab; label: string }[]; right: string } {
307  const widthOf = (names: string[]) => names.reduce((n, t, i) => n + 3 + width(t) + (TABS[i]!.key === c.tab ? 2 : 0), 0) + 3 * (names.length - 1)
308  const pick = (form: 'label' | 'short') => TABS.map(t => labels[t.key][form])
309  const form = widthOf(pick('label')) <= c.width ? 'label' : 'short'
310  return {
311    items: TABS.map(t => ({ key: t.key, label: labels[t.key][form] })),
312    right: otherSide(c, c.width - widthOf(pick(form)) - 2),
313  }
314}
315
316// Columns inside the pane's own round border and padding, from the columns the engine gives the body
317export const innerWidth = (bodyColumns: number) => Math.max(20, bodyColumns - 4)
318
319// Terminal cells of a string: Hangul, CJK and full-width forms take two
320export const cells = (t: string) => [...t].reduce((n, c) => n + (/[ᄀ-ᅟ⺀-꓏가-힣＀-⦆]/.test(c) ? 2 : 1), 0)
321
322// The host Input draws '⏎ submit' at the row's end; its gap plus label
323export const SUBMIT_HINT_CELLS = 1 + cells('⏎ submit')
324
325// The footer keys row (lead, [ q ], tail, then prev/next beside it): prev/next join only when keys, steps and the
326// host's submit hint all fit the width; otherwise the keys stay one row and [ ] still step
327export function footerFits(
328  t: { lead: string; tail: string; prev: string; next: string }, w: number, runs: number,
329): { steps: boolean } {
330  const keys = cells(t.lead) + 1 + 5 + 1 + cells(t.tail)
331  const steps = 1 + cells(t.prev) + 2 + cells(t.next)
332  return { steps: runs > 1 && keys + steps + SUBMIT_HINT_CELLS <= w }
333}
334
335// header, Now / last step / You, the rail
336export function paneHead(r: HarnessRow, c: PaneCtx): Line[] {
337  const compact = compactAt(c.width)
338  const rail = railItems(r)
339  const barText = r.total > 0 && !compact ? `subgoals ${r.passed}/${r.total} ${bar(r.passed, r.total, 10)}` : ''
340  return ([
341    headerLine(r, c), [],
342    nowLine(r, c, compact), lastLine(r, c, compact), youLineOf(r, c, compact), [],
343    leftRight(railFit(rail, c.width - (barText === '' ? 0 : width(barText) + 2)), [fs(barText, { dim: true })], c.width, 20), [],
344  ] as Line[]).map(l => clipLine(l, c.width))
345}
346
347// the Now tab's findings, or the Findings tab (the node's rollup over every round)
348export function paneContent(r: HarnessRow, c: PaneCtx): Line[] {
349  const compact = compactAt(c.width)
350  return (c.tab === 'findings' ? findingsBody(r, c, compact) : nowFindings(r, c, compact)).map(l => clipLine(l, c.width))
351}
352
353// The pane's body for the run, between the frame's top and bottom: head, the tab's content and the tab row. The
354// Flow and Gate rules tabs are mod.tsx's own (they read the run's files); this draws Now and Findings.
355export function paneLines(r: HarnessRow, c: PaneCtx): Line[] {
356  return [...paneHead(r, c), ...paneContent(r, c), [], clipLine(tabLine(c, compactAt(c.width)), c.width)]
357}
358
359/* --- the band: three rows for the leading run --- */
360
361const INDENT = '          ' // under `⚑ harness `, so the rows read as one block
362
363// The band for the harness runs in opening order: the leading run's three rows (what it is doing and whether it
364// waits on you / how far / what it cost and what came back last), `+N` for the others. No graph run is drawn here.
365// `reserve` columns at the end of row 1 are left to mod.tsx's open button.
366export function bandLines(ordered: readonly HarnessRow[], o: { width: number; nowMs: number; tick: number; reserve?: number }): Line[] {
367  const r = ordered[0]
368  if (r === undefined) return []
369  const w = o.width
370  const compact = w < 150
371  const more = ordered.length - 1
372  const y = youLine(r)
373  const d = doingOf(r)
374  const row1 = fit([
375    { parts: [glyphSeg(stateGlyph(r, o.tick))], fixed: true },
376    fs('harness', { sep: ' ', drop: 6, dim: true }),
377    fs(r.slug, { sep: ' ', bold: true }),
378    fs(d.text, { sep: ' · ', drop: 1, min: 16, dim: d.canned }),
379    y.you ? fs(`asks you: ${y.text}`, { sep: ' · ', tint: 'claude', bold: true }) : fs(''),
380    fs(roundText(r, compact), { sep: ' · ', drop: 4 }),
381    more > 0 ? { ...fs(compact ? `+${more}` : `+${more} run${more > 1 ? 's' : ''}`, { sep: '  ', fixed: true, dim: true }), right: true } : fs(''),
382  ], w - (o.reserve ?? 0))
383  const rail = railItems(r)
384  const sub = r.total > 0 ? `subgoals ${r.passed}/${r.total}` : ''
385  // the rail already names the subgoals, so the right-hand count goes first when the row is tight
386  const row2 = fit([
387    fs(INDENT, { fixed: true }),
388    { parts: railFit(rail, Math.max(8, w - INDENT.length)) },
389    { ...fs(sub, { sep: '  ', drop: 1, dim: true }), right: true },
390  ], w)
391  const finding = topFinding(r)
392  const row3 = fit([
393    fs(INDENT, { fixed: true }),
394    fs(costText(r), { fixed: true, bold: true }),
395    fs(elapsedText(r, o.nowMs), { sep: ' · ', fixed: true }),
396    finding === null ? fs('') : fs(`top finding: ${finding}`,{ sep: ' · ', drop: 2, min: 24 }),
397  ], w)
398  return [row1, row2, row3]
399}
400
401/* --- the demo: fixtures rendered to plain text, no live run --- */
402
403export const DEMO_SCENARIOS = ['minimal', 'full', 'parallel', 'narrow'] as const
404export type DemoScenario = (typeof DEMO_SCENARIOS)[number]
405export const DEMO_NOW = Date.parse('2026-10-18T10:00:00Z')
406
407const iso = (agoMs: number) => new Date(DEMO_NOW - agoMs).toISOString()
408const MIN = 60_000
409const sev = (...s: [keyof typeof SEV_TINT, string][]) => s.map(([severity, text]) => ({ severity, text }))
410const base = (slug: string, over: Partial<HarnessRow> = {}): HarnessRow => ({
411  slug, stage: 'plan', round: null, waiting: null, stalled: false, now: null, started_at: null, max_critique_rounds: 3,
412  severity: { blocker: 0, major: 0, minor: 0, nit: 0 }, rounds: [], passed: 0, failed: 0, total: 0, ...over,
413})
414const withSeverity = (r: HarnessRow): HarnessRow => ({ ...r, severity: severityOf(r.rounds.flatMap(x => x.problems)) })
415const nowOf = (o: Partial<NonNullable<HarnessRow['now']>>): NonNullable<HarnessRow['now']> => ({
416  stage: null, doing: null, round: null, last_step: null, next: null, waiting: null, cost_usd: null, at: null, since: null, ...o,
417})
418
419const csvExport = withSeverity(base('csv-export', {
420  stage: 'setgoal', round: 3, started_at: iso(72 * MIN), total: 3,
421  rounds: [
422    {
423      round: 1, sound: false,
424      problems: sev(
425        ['major', '"export button" has no check that a file actually downloads — the acceptance cannot be tested'],
426        ['major', 'the large-report subgoal edits the auth middleware, outside the plan'],
427        ['nit', 'subgoal titles mix verbs and nouns'],
428        ['major', 'no subgoal covers an empty report'],
429        ['major', 'the goal spec names no column order for the file'],
430      ),
431    },
432    {
433      round: 2, sound: false,
434      problems: sev(
435        ['minor', 'the empty-report subgoal does not say what the file contains'],
436        ['blocker', 'the column order is still unspecified, so two subgoals can disagree on it'],
437        ['minor', 'subgoal s3 repeats the download check of s1'],
438      ),
439    },
440  ],
441  now: nowOf({
442    stage: 'setgoal', round: 3, cost_usd: 3.4, at: iso(12_000), since: iso(6 * MIN),
443    doing: 'SetGoal is rewriting the spec — critique round 2 rejected it (1 blocker, 2 minor)',
444    last_step: 'edited the goal spec — split "export button" into two subgoals',
445    next: 'critique round 3 judges the new spec, then 3 subgoals are built',
446  }),
447}))
448
449export function demoRows(s: DemoScenario): HarnessRow[] {
450  switch (s) {
451    case 'minimal':
452      return [base('fix-date-filter')]
453    case 'full':
454      return [csvExport]
455    case 'parallel':
456      return [
457        withSeverity({
458          ...csvExport, stage: 'implement', round: 3, passed: 1,
459          rounds: [...csvExport.rounds, { round: 3, sound: true, problems: [] }],
460          now: nowOf({
461            stage: 'implement', round: 3, cost_usd: 5.15, at: iso(8_000), since: iso(4 * MIN),
462            doing: 'Subgoal s2 is being built — the date range check',
463            last_step: 'edited src/export/range.ts — added the end-before-start check', next: 'its gate judges s2, then s3 starts',
464          }),
465        }),
466        base('fix-date-filter', {
467          stage: 'setgoal', started_at: iso(20 * MIN), total: 2,
468          waiting: { who: 'you', what: 'approve the goal spec — 2 subgoals touch the billing API' },
469          now: nowOf({
470            stage: 'setgoal', doing: 'SetGoal wrote the spec and waits for approval', at: iso(2 * MIN), since: iso(2 * MIN),
471            last_step: 'wrote the goal spec with 2 subgoals', next: 'critique judges the spec after you approve it',
472            waiting: { who: 'you', what: 'approve the goal spec — 2 subgoals touch the billing API' },
473          }),
474        }),
475      ]
476    case 'narrow':
477      return [
478        withSeverity(base('export-quarterly-revenue-report-with-regional-breakdown', {
479          stage: 'critique', round: 3, started_at: iso(190 * MIN), total: 5, passed: 0,
480          waiting: { who: 'you', what: 'confirm whether the legacy invoice PDF route stays or goes before the third critique round starts' },
481          rounds: [
482            { round: 1, sound: false, problems: sev(['blocker', 'the plan changes the invoice table without a migration step'], ['major', 'no acceptance for currency rounding']) },
483            { round: 2, sound: false, problems: sev(['major', 'the regional breakdown subgoal depends on a subgoal that comes after it'], ['minor', 'the file name pattern is left open'], ['nit', 'typo in subgoal s4']) },
484          ],
485          now: nowOf({
486            stage: 'critique', round: 3, cost_usd: 12.8, at: iso(40_000), since: iso(11 * MIN),
487            doing: 'Critique is judging the third version of the spec for the quarterly revenue report and its regional breakdown',
488            last_step: 'rewrote subgoal s2 so the regional breakdown no longer depends on s4 and the currency rounding has its own acceptance',
489            next: 'the third critique round judges the new spec, then 5 subgoals are built one by one',
490            waiting: { who: 'you', what: 'confirm whether the legacy invoice PDF route stays or goes before the third critique round starts' },
491          }),
492        })),
493      ]
494  }
495}
496
497// The command's argument: `demo` takes the scenario after the current one (the first when none), `demo <name>` that
498// scenario, `demo off` leaves the demo; anything else is no demo argument (null: the live run).
499export function parseDemoArg(args: string, current: DemoScenario | null): DemoScenario | 'off' | null {
500  const [head, name] = args.trim().toLowerCase().split(/\s+/)
501  if (head !== 'demo') return null
502  if (name === 'off') return 'off'
503  const named = DEMO_SCENARIOS.find(s => s === name)
504  if (named !== undefined) return named
505  return DEMO_SCENARIOS[(current === null ? 0 : DEMO_SCENARIOS.indexOf(current) + 1) % DEMO_SCENARIOS.length]!
506}
507
508// The pane (Now, and for `full` also Findings) and the band for one scenario at one width, as plain text; the
509// report quotes it and the test pins it.
510export function renderDemo(scenario: DemoScenario, w: number): string {
511  const rows = demoRows(scenario)
512  const ordered = openingOrder(rows, {})
513  const out: string[] = []
514  const pane = (title: string, selected: string | null, tab: PaneTab) => {
515    const r = pickRun(ordered, selected)
516    if (r === null) return
517    const ctx: PaneCtx = { width: w - 4, nowMs: DEMO_NOW, tick: 0, pos: runPosition(ordered, selected), other: otherRunLabel(ordered, selected), tab }
518    out.push(`# ${title}`, ...frame('Harness', paneLines(r, ctx), w))
519  }
520  pane(`${scenario} · pane · ${w} columns`, null, 'now')
521  if (scenario === 'parallel') pane(`${scenario} · after next · ${w} columns`, cycleRun(ordered, null, 1), 'now')
522  if (scenario === 'full') pane(`${scenario} · findings tab · ${w} columns`, null, 'findings')
523  out.push(`# ${scenario} · band · ${w} columns`, ...bandLines(ordered, { width: w, nowMs: DEMO_NOW, tick: 0 }).map(plain))
524  return out.join('\n')
525}
526
hooks/status.ts 464 lines
1/*
2 * What the harness pane shows, as plain functions: the reasons the run files hold and the flow built
3 * from them. No engine calls here; mod.tsx reads the files and draws what these return.
4 */
5import type { HarnessRow, PaneTab, RowNow, RowProblem, RowRound, RowStage, RowWaiting, RunInfo, Severity, StageKey, StageMark } from '../types'
6
7export const NONE = '—' // the harness records no vendor or model, so the agent column reads this
8
9const oneLine = (v: unknown, max: number) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '')
10
11/*
12 * The failed stages of a run as `node engine/fallback-check.mjs` gives them (`failures` on each row): the reason, the
13 * next step and the severity are the node's; these are readers and a text builder, they decide nothing. Local to this
14 * file: HarnessRow in ../types is not widened, a row carries `failures` as RunRow.
15 */
16export type FailureSeverity = 'info' | 'needs you' | 'gave up'
17export type RowFailure = { key: string; at: number; what: string; reason: string; next_step: string | null; severity: FailureSeverity }
18export type RunRow = HarnessRow & { failures: RowFailure[] }
19
20const FAILURE_SEVERITIES: readonly string[] = ['info', 'needs you', 'gave up']
21const FAILURE_MARK: Record<FailureSeverity, string> = { info: '↻', 'needs you': '⚠', 'gave up': '✗' }
22export const FAILURE_TOAST_MS = 10_000 // the toast of a failure that needs a person or ended the run; info keeps the default
23const PUSH_MAX = 200
24
25// One failure, tolerant: a field of the wrong type drops the whole entry (never a guess).
26export function normalizeFailure(v: unknown): RowFailure | null {
27  const o = typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null
28  if (o === null || typeof o.key !== 'string' || o.key === '' || typeof o.at !== 'number' || !Number.isFinite(o.at)) return null
29  if (typeof o.what !== 'string' || typeof o.reason !== 'string' || !FAILURE_SEVERITIES.includes(o.severity as string)) return null
30  if (o.next_step !== null && typeof o.next_step !== 'string') return null
31  return { key: o.key, at: o.at, what: o.what, reason: o.reason, next_step: o.next_step, severity: o.severity as FailureSeverity }
32}
33
34// a row's failures, oldest first as the node lists them; a row the node did not give (the demo's) has none
35export const failuresOf = (r: HarnessRow): RowFailure[] => (r as Partial<RunRow>).failures ?? []
36
37// The reason of the newest failure under a key: the key itself or a longer one at a `|` (so `r|gate|S1|1` is not `r|gate|S1|10`).
38export function reasonFor(failures: readonly RowFailure[], key: string): string {
39  return failures.filter(f => f.key === key || f.key.startsWith(`${key}|`)).pop()?.reason ?? ''
40}
41
42// `<icon> <run> <what> failed: <reason> → <next_step>` (no arrow without a next step); a failure that needs a person or
43// gave up also has a push text (cut at 200) and a longer toast. The icon and the timeout follow the severity only.
44export function failureToast(run: string, f: RowFailure): { text: string; pushText: string | null; timeoutMs?: number } {
45  const text = `${FAILURE_MARK[f.severity]} ${run} ${f.what} failed: ${f.reason}${f.next_step === null ? '' : ` → ${f.next_step}`}`
46  return f.severity === 'info' ? { text, pushText: null } : { text, pushText: text.slice(0, PUSH_MAX), timeoutMs: FAILURE_TOAST_MS }
47}
48
49// 45s, 3m 12s, 1h 5m; '' when unknown
50export function clock(ms: number | null): string {
51  if (ms === null || !Number.isFinite(ms)) return ''
52  const s = Math.max(0, Math.round(ms / 1000))
53  if (s < 60) return `${s}s`
54  const m = Math.floor(s / 60)
55  if (m < 60) return `${m}m ${s % 60}s`
56  return `${Math.floor(m / 60)}h ${m % 60}m`
57}
58
59// Elapsed on the Now line: the harness writes no start time, so this is the time since the run's
60// newest file changed. A finished run has none.
61export const sinceLast = (r: RunInfo, now: number) => (r.finished || r.lastMs <= 0 ? '' : clock(now - r.lastMs))
62
63export type FlowLine = {
64  kind: 'stage' | 'sub' | 'attempt'
65  depth: number // an attempt: 0 first gate verdict, each retry one deeper, under the reject it answers
66  state: StageMark
67  stage?: StageKey
68  id?: string
69  title?: string
70  n?: number
71  reason: string // why it was rejected; '' when it was not
72}
73
74// Stages in order; the implement stage opens into its subgoals, each with its gate verdicts, a retry nested
75// under the reject it answers. Critique and goal-gate rejects carry their reason.
76export function flowLines(r: RunInfo): FlowLine[] {
77  const out: FlowLine[] = []
78  for (const g of r.stages) {
79    if (g.key === 'implement' && r.subs.length > 0) {
80      for (const sub of r.subs) {
81        out.push({ kind: 'sub', depth: 0, state: sub.state, id: sub.id, title: sub.title, reason: '' })
82        sub.gates.forEach((gt, i) =>
83          out.push({ kind: 'attempt', depth: i, state: gt.pass ? 'done' : 'failed', id: sub.id, n: gt.n, reason: gt.pass ? '' : gt.reason }),
84        )
85      }
86      continue
87    }
88    const reason = g.key === 'critique' ? (g.state === 'failed' ? r.critique.reason : '') : g.key === 'gate' && g.state === 'failed' ? r.goalReason : ''
89    out.push({ kind: 'stage', depth: 0, state: g.state, stage: g.key, reason })
90  }
91  return out
92}
93
94/*
95 * The rows of `node engine/fallback-check.mjs --list --json`: what the pane and band say about each open
96 * run. Glyph-free; harness-draw.tsx owns the glyphs and the layout.
97 */
98
99export const SEVERITIES = ['blocker', 'major', 'minor', 'nit'] as const
100const ROW_STAGES: readonly RowStage[] = ['plan', 'setgoal', 'critique', 'implement', 'gate', 'report']
101
102const obj = (v: unknown): Record<string, unknown> | null => (typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null)
103const count = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : 0)
104const orNull = (v: unknown) => (typeof v === 'string' ? v : null)
105
106export const emptySeverity = (): Severity => ({ blocker: 0, major: 0, minor: 0, nit: 0 })
107
108function normalizeWaiting(v: unknown): RowWaiting | null {
109  const o = obj(v)
110  if (o === null || (o.who !== 'you' && o.who !== 'vendor') || typeof o.what !== 'string') return null
111  return { who: o.who, what: o.what }
112}
113
114function normalizeNow(v: unknown): RowNow | null {
115  const o = obj(v)
116  if (o === null) return null
117  return {
118    stage: orNull(o.stage), doing: orNull(o.doing),
119    round: typeof o.round === 'number' && Number.isInteger(o.round) ? o.round : null,
120    last_step: orNull(o.last_step), next: orNull(o.next), waiting: normalizeWaiting(o.waiting),
121    cost_usd: typeof o.cost_usd === 'number' && Number.isFinite(o.cost_usd) ? o.cost_usd : null,
122    at: orNull(o.at), since: orNull(o.since),
123  }
124}
125
126function normalizeRound(v: unknown, i: number): RowRound {
127  const o = obj(v) ?? {}
128  const problems: RowProblem[] = (Array.isArray(o.problems) ? (o.problems as unknown[]) : []).map(p => {
129    const q = obj(p)
130    const sev = String(q?.severity ?? '').toLowerCase()
131    return {
132      severity: (SEVERITIES as readonly string[]).includes(sev) ? (sev as RowProblem['severity']) : 'major',
133      text: oneLine(q?.text ?? (typeof p === 'string' ? p : ''), 240),
134    }
135  })
136  return { round: typeof o.round === 'number' && Number.isInteger(o.round) && o.round >= 1 ? o.round : i + 1, sound: typeof o.sound === 'boolean' ? o.sound : null, problems }
137}
138
139export function severityOf(problems: readonly RowProblem[]): Severity {
140  const out = emptySeverity()
141  for (const p of problems) out[p.severity]++
142  return out
143}
144
145// One row, tolerant: a missing or malformed field takes a safe default and nothing throws. No slug, no row.
146export function normalizeRow(v: unknown): RunRow | null {
147  const o = obj(v)
148  if (o === null || typeof o.slug !== 'string' || o.slug === '') return null
149  const rounds = (Array.isArray(o.rounds) ? (o.rounds as unknown[]) : []).map(normalizeRound)
150  const sev = obj(o.severity)
151  const now = normalizeNow(o.now)
152  const cap = o.max_critique_rounds
153  return {
154    slug: o.slug,
155    stage: ROW_STAGES.includes(o.stage as RowStage) ? (o.stage as RowStage) : 'plan',
156    round: typeof o.round === 'number' && Number.isInteger(o.round) ? o.round : null,
157    waiting: normalizeWaiting(o.waiting) ?? now?.waiting ?? null,
158    stalled: o.stalled === true,
159    now,
160    started_at: orNull(o.started_at),
161    max_critique_rounds: typeof cap === 'number' && Number.isInteger(cap) && cap >= 1 ? cap : 2,
162    severity: sev === null ? severityOf(rounds.flatMap(r => r.problems)) : { blocker: count(sev.blocker), major: count(sev.major), minor: count(sev.minor), nit: count(sev.nit) },
163    rounds, passed: count(o.passed), failed: count(o.failed), total: count(o.total),
164    failures: (Array.isArray(o.failures) ? (o.failures as unknown[]) : []).map(normalizeFailure).filter((f): f is RowFailure => f !== null),
165  }
166}
167
168// The --list --json output. Empty, invalid or not a list is null: the caller keeps its last good list.
169// `[]` is a real answer (no open runs).
170export function parseRows(text: unknown): HarnessRow[] | null {
171  if (typeof text !== 'string' || text.trim() === '') return null
172  let v: unknown
173  try {
174    v = JSON.parse(text)
175  } catch {
176    return null
177  }
178  if (!Array.isArray(v)) return null
179  return v.map(normalizeRow).filter((r): r is RunRow => r !== null)
180}
181
182// The `--show <dir> --json` output: one row. Anything else is null.
183export function parseRow(text: unknown): RunRow | null {
184  if (typeof text !== 'string' || text.trim() === '') return null
185  try {
186    return normalizeRow(JSON.parse(text))
187  } catch {
188    return null
189  }
190}
191
192export const waitsOnYou = (r: HarnessRow) => r.waiting?.who === 'you'
193// rejects the person can have seen: rejected critique rounds and failed subgoals
194export const rejectCount = (r: HarnessRow) => r.rounds.filter(x => x.sound === false).length + r.failed
195export const hasNewReject = (r: HarnessRow, looked: Record<string, number>) => rejectCount(r) > (looked[r.slug] ?? 0)
196export const markLooked = (looked: Record<string, number>, r: HarnessRow | null): Record<string, number> =>
197  r === null || looked[r.slug] === rejectCount(r) ? looked : { ...looked, [r.slug]: rejectCount(r) }
198
199// The run waiting on you, else one with a reject since you last looked, else the most recently changed
200// (--list already sorts newest first; the sort here is stable).
201export function openingOrder(rows: readonly HarnessRow[], looked: Record<string, number>): HarnessRow[] {
202  const rank = (r: HarnessRow) => (waitsOnYou(r) ? 0 : hasNewReject(r, looked) ? 1 : 2)
203  return rows.map((r, i) => ({ r, i })).sort((a, b) => rank(a.r) - rank(b.r) || a.i - b.i).map(x => x.r)
204}
205
206// openingOrder, kept: `frozen` is the slug order of the last call. While the open slugs are the same set, that order
207// stands, so a look (markLooked) or a changed row never moves a run under `[` / `]`; a run that opens or closes, or
208// no `frozen` (null), orders again from `looked`.
209export function frozenOrder(rows: readonly HarnessRow[], looked: Record<string, number>, frozen: readonly string[] | null): HarnessRow[] {
210  const bySlug = new Map(rows.map(r => [r.slug, r]))
211  const same = frozen !== null && frozen.length === rows.length && bySlug.size === rows.length && frozen.every(s => bySlug.has(s))
212  return same ? frozen.map(s => bySlug.get(s)!) : openingOrder(rows, looked)
213}
214
215// The run shown: the selected slug while it is open, else the first in opening order.
216export const pickRun = (ordered: readonly HarnessRow[], selected: string | null): HarnessRow | null =>
217  ordered.find(r => r.slug === selected) ?? ordered[0] ?? null
218
219export function runPosition(ordered: readonly HarnessRow[], selected: string | null): { k: number; n: number } {
220  const at = ordered.findIndex(r => r.slug === pickRun(ordered, selected)?.slug)
221  return { k: at < 0 ? 0 : at + 1, n: ordered.length }
222}
223
224export const runCount = ({ k, n }: { k: number; n: number }, compact = false) => (compact ? `${k}/${n}` : `run ${k} of ${n}`)
225
226// `[` and `]`: the slug a step lands on, stopping at the first and the last run; with fewer than two runs, nothing changes.
227export function cycleRun(ordered: readonly HarnessRow[], selected: string | null, step: 1 | -1): string | null {
228  if (ordered.length < 2) return selected
229  const at = Math.max(0, ordered.findIndex(r => r.slug === pickRun(ordered, selected)?.slug))
230  return ordered[Math.min(ordered.length - 1, Math.max(0, at + step))]!.slug
231}
232
233const STAGE_NAME: Record<RowStage, string> = { plan: 'Plan', setgoal: 'SetGoal', critique: 'Critique', implement: 'Implement', gate: 'Goal gate', report: 'Report' }
234export const stageName = (s: RowStage) => STAGE_NAME[s]
235
236// `Implement 2/4`, `Critique round 2`; ` · stalled` when it is
237export function stageLabel(r: HarnessRow): string {
238  const base = r.stage === 'implement' && r.total > 0 ? `${STAGE_NAME.implement} ${r.passed}/${r.total}` : STAGE_NAME[r.stage]
239  return r.stalled ? `${base} · stalled` : base
240}
241
242// The tab row's right side: the run `]` would open (on the last run, the previous one), and how many more there are
243export function otherRunLabel(ordered: readonly HarnessRow[], selected: string | null): string | null {
244  if (ordered.length < 2) return null
245  const at = Math.max(0, ordered.findIndex(r => r.slug === pickRun(ordered, selected)?.slug))
246  const other = ordered[at + 1 < ordered.length ? at + 1 : at - 1]!
247  return `other run: ${other.slug} · ${stageLabel(other)}${ordered.length > 2 ? ` (+${ordered.length - 2})` : ''}`
248}
249
250/* --- the spinner --- */
251
252// Acting: now.json is there, the run waits on no one, and it is not stalled (it is open: the list holds only open runs).
253export const isActing = (r: HarnessRow) => r.now !== null && r.waiting === null && !r.stalled
254
255// The faster interval runs only while a displayed run acts, a pane or band is shown, and a surface exists.
256export const spinnerPlan = (rows: readonly (HarnessRow | null)[], surfaces: number, shown: boolean): { run: boolean } => ({
257  run: surfaces > 0 && shown && rows.some(r => r !== null && isActing(r)),
258})
259
260/* --- times, cost, sentences --- */
261
262export const parseMs = (iso: string | null): number | null => {
263  const t = iso === null ? NaN : Date.parse(iso)
264  return Number.isNaN(t) ? null : t
265}
266
267// 45s, 6m, 1h 12m; '' when unknown
268export function span(ms: number | null): string {
269  if (ms === null || !Number.isFinite(ms)) return ''
270  const s = Math.max(0, Math.round(ms / 1000))
271  if (s < 60) return `${s}s`
272  const m = Math.floor(s / 60)
273  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
274}
275
276const since = (iso: string | null, nowMs: number) => {
277  const t = parseMs(iso)
278  return t === null ? '' : span(nowMs - t)
279}
280
281// `$3.40`, or `—` unless now.json carries a number
282export const costText = (r: HarnessRow) => (r.now?.cost_usd != null ? `$${r.now.cost_usd.toFixed(2)}` : NONE)
283export const elapsedText = (r: HarnessRow, nowMs: number) => since(r.started_at, nowMs)
284export const runState = (r: HarnessRow) => (r.stalled ? 'stalled' : waitsOnYou(r) ? 'waiting on you' : 'running')
285
286const STAGE_DOING: Record<RowStage, string> = {
287  plan: 'Plan is drafting the approach',
288  setgoal: 'SetGoal is writing the goal spec',
289  critique: 'Critique is judging the spec',
290  implement: 'Subgoals are being built and judged',
291  gate: 'The goal gate is judging the result',
292  report: 'Report is being written',
293}
294
295// what the run is doing, in a sentence: now.doing (canned false), else the stage's own (canned true)
296export function doingOf(r: HarnessRow): { text: string; canned: boolean } {
297  const live = oneLine(r.now?.doing ?? '', 200)
298  return live === '' ? { text: STAGE_DOING[r.stage], canned: true } : { text: live, canned: false }
299}
300export const doingText = (r: HarnessRow) => doingOf(r).text
301
302// The status line: open runs per stage in flow order, `Plan(6) / Implement(11)`; a stalled row counts under its stage;
303// no rows is no status.
304export function stageStatus(rows: readonly HarnessRow[]): string | undefined {
305  const parts = ROW_STAGES.map(s => ({ s, n: rows.filter(r => r.stage === s).length })).filter(x => x.n > 0)
306  return parts.length === 0 ? undefined : parts.map(({ s, n }) => `${s.charAt(0).toUpperCase()}${s.slice(1)}(${n})`).join(' / ')
307}
308
309export const roundText = (r: HarnessRow, compact = false) =>
310  r.round === null ? '' : compact ? `round ${r.round}/${r.max_critique_rounds}` : `round ${r.round} of ${r.max_critique_rounds}`
311
312export const inStageText = (r: HarnessRow, nowMs: number, compact = false) => {
313  const t = since(r.now?.since ?? null, nowMs)
314  return t === '' ? '' : compact ? t : `${t} in this stage`
315}
316
317// the driver's latest step and how old it is; '—' and no age when it wrote none
318export function lastStep(r: HarnessRow, nowMs: number): { text: string; age: string } {
319  const text = oneLine(r.now?.last_step ?? '', 120)
320  const age = since(r.now?.at ?? null, nowMs)
321  return text === '' ? { text: NONE, age: '' } : { text, age: age === '' ? '' : `${age} ago` }
322}
323
324// The You line without its glyph: you = the run waits on a person (⚑ in the pane)
325export function youLine(r: HarnessRow): { you: boolean; text: string } {
326  if (r.waiting?.who === 'you') return { you: true, text: oneLine(r.waiting.what, 200) }
327  const next = oneLine(r.now?.next ?? '', 200)
328  const vendor = r.waiting?.who === 'vendor' ? `waiting on a vendor: ${oneLine(r.waiting.what, 120)}` : ''
329  return { you: false, text: ['nothing needed', vendor, next === '' ? '' : `next: ${next}`].filter(Boolean).join(' · ') }
330}
331
332/* --- the rail: a loop shows as repeats --- */
333
334export type RailMark = 'done' | 'failed' | 'current' | 'pending'
335export type RailItem = { label: string; short: string; mark: RailMark }
336
337const STAGE_AT: Record<RowStage, number> = { plan: 0, setgoal: 1, critique: 2, implement: 3, gate: 4, report: 5 }
338
339// Plan, SetGoal, then Critique and (when it rejected) SetGoal again, until a critique accepts; then the subgoals,
340// the goal gate, the report. A round exists once its critique file does, so the one in progress is the pending
341// or current item after the last round.
342export function railItems(r: HarnessRow): RailItem[] {
343  const at = STAGE_AT[r.stage]
344  const item = (label: string, mark: RailMark, short = label): RailItem => ({ label, short, mark })
345  const items: RailItem[] = [
346    item('Plan', at === 0 ? 'current' : 'done'),
347    item('SetGoal', at > 1 || r.rounds.length > 0 ? 'done' : at === 1 ? 'current' : 'pending'),
348  ]
349  r.rounds.forEach((rd, i) => {
350    items.push(item('Critique', rd.sound === false ? 'failed' : 'done'))
351    if (rd.sound !== false) return
352    const lastRound = i === r.rounds.length - 1
353    // the last rejected round at the cap goes on to implement (fallback.md): its SetGoal again is drawn only while current
354    if (lastRound && r.rounds.length >= r.max_critique_rounds && at !== 1) return
355    items.push(item('SetGoal again', !lastRound || at > 1 ? 'done' : at === 1 ? 'current' : 'pending', 'SetGoal'))
356  })
357  const latest = r.rounds[r.rounds.length - 1]
358  if (latest === undefined || (latest.sound === false && r.rounds.length < r.max_critique_rounds)) items.push(item('Critique', at === 2 ? 'current' : at > 2 ? 'done' : 'pending'))
359  const judged = r.total > 0 && r.passed + r.failed >= r.total
360  items.push(item(r.total > 0 ? `Subgoals ${r.passed}/${r.total}` : 'Subgoals', at === 3 ? 'current' : at > 3 ? (r.failed > 0 && judged ? 'failed' : 'done') : 'pending'))
361  items.push(item('Goal gate', at === 4 ? 'current' : at > 4 ? 'done' : 'pending', 'Gate'))
362  items.push(item('Report', at === 5 ? 'current' : 'pending'))
363  return items
364}
365
366/* --- findings --- */
367
368// `4 major, 1 nit`; `no findings` when there are none
369export function countsText(s: Severity): string {
370  const parts = SEVERITIES.filter(k => s[k] > 0).map(k => `${s[k]} ${k}`)
371  return parts.length === 0 ? 'no findings' : parts.join(', ')
372}
373
374export const latestRound = (r: HarnessRow): RowRound | null => r.rounds[r.rounds.length - 1] ?? null
375const verdictOf = (rd: RowRound) => (rd.sound === false ? 'rejected' : rd.sound === true ? 'sound' : 'judged')
376
377// `Critique round 1 · rejected · 4 major, 1 nit`: the Now view's findings heading; null before any critique
378export function roundHeading(rd: RowRound | null, compact = false): string | null {
379  if (rd === null) return null
380  return `${compact ? `Critique r${rd.round}` : `Critique round ${rd.round}`} · ${verdictOf(rd)} · ${countsText(severityOf(rd.problems))}`
381}
382
383// the round's problems, most severe first (stable), numbered as the round lists them
384export function rankedProblems(rd: RowRound | null): { n: number; severity: RowProblem['severity']; text: string }[] {
385  if (rd === null) return []
386  return rd.problems
387    .map((p, i) => ({ n: i + 1, severity: p.severity, text: oneLine(p.text, 240) }))
388    .sort((a, b) => SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) || a.n - b.n)
389}
390
391// the counts of what a list cut to `shown` entries leaves out: `2 major, 1 nit`; '' when nothing
392export function restText(rd: RowRound | null, shown: number): string {
393  const rest = rankedProblems(rd).slice(shown)
394  return rest.length === 0 ? '' : countsText(severityOf(rest))
395}
396
397// `+3: 2 major, 1 nit`: the pane's cut-count line; '' when nothing is cut
398export function restLine(rd: RowRound | null, shown: number): string {
399  const rest = rankedProblems(rd).slice(shown)
400  return rest.length === 0 ? '' : `+${rest.length}: ${countsText(severityOf(rest))}`
401}
402
403// the most severe finding of the latest round that has any
404export function topFinding(r: HarnessRow): string | null {
405  for (let i = r.rounds.length - 1; i >= 0; i--) {
406    const first = rankedProblems(r.rounds[i]!)[0]
407    if (first !== undefined && first.text !== '') return first.text
408  }
409  return null
410}
411
412/* --- what the mod reads and shows --- */
413
414// The one reader of the run files is the node CLI (it works with no mod, compat-claude); the mod runs it.
415export const listArgv = (pluginRoot: string, cwd: string): string[] => ['node', `${pluginRoot}/engine/fallback-check.mjs`, '--list', '--json', '--cwd', cwd]
416// A finished run is not in the list; its own failures are the node's answer for its directory.
417export const showArgv = (pluginRoot: string, runDir: string): string[] => ['node', `${pluginRoot}/engine/fallback-check.mjs`, '--show', runDir, '--json']
418
419// The rows on screen: the band's leading run, and the pane's run while the pane is open.
420export function shownRows(ordered: readonly HarnessRow[], selected: string | null, paneOpen: boolean): HarnessRow[] {
421  const lead = ordered[0]
422  if (lead === undefined) return []
423  const picked = paneOpen ? pickRun(ordered, selected) : null
424  return picked === null || picked === lead ? [lead] : [lead, picked]
425}
426
427// The pane opens on Now when a run is open, else on the gate rules (the one tab that answers with no run).
428export const openTab = (hasRun: boolean): PaneTab => (hasRun ? 'now' : 'rules')
429
430/* --- the run-switch keys `[` and `]` --- */
431
432// `[` is the previous run, `]` the next. A Button hotkey cannot be either (the engine takes one digit or lowercase
433// letter), so the pane draws an autoFocus Input that takes every printable key while the pane holds the focus (the
434// moment hotkeys are armed too); the Input's text is read here, its last character is the key just pressed.
435export type PaneKey = { kind: 'step'; by: 1 | -1 } | { kind: 'tab'; tab: PaneTab } | { kind: 'close' } | null
436
437const KEY_TABS: Record<string, PaneTab> = { '1': 'now', '2': 'flow', '3': 'findings', '4': 'rules' }
438
439// `[` / `]` step the run, `1`-`4` pick a tab, `q` closes; any other text (or none, or a non-string) is no key.
440// Text holding a `/` is a slash command being typed (`/harness-status`, `/help q`): held, no key fires until submit.
441export function paneKey(text: unknown): PaneKey {
442  if (typeof text !== 'string' || text === '' || text.includes('/')) return null
443  const k = [...text].pop()!
444  if (k === ']') return { kind: 'step', by: 1 }
445  if (k === '[') return { kind: 'step', by: -1 }
446  if (k === 'q') return { kind: 'close' }
447  const tab = KEY_TABS[k]
448  return tab === undefined ? null : { kind: 'tab', tab }
449}
450
451// A slash command typed into the pane's Input and submitted. The Input's buffer may start with earlier key presses
452// (`][2q/help`), so the command starts at the first `/`. `/harness-status` closes the pane (the command again toggles);
453// `/name args` runs that command; anything else is dropped.
454export type PaneSlash = { kind: 'close' } | { kind: 'run'; command: string; args: string } | null
455
456export function paneSlash(text: unknown): PaneSlash {
457  if (typeof text !== 'string') return null
458  const at = text.indexOf('/')
459  if (at < 0) return null
460  const m = /^\/([^\s/]+)\s*(.*)$/.exec(text.slice(at).trim())
461  if (m === null) return null
462  return m[1] === 'harness-status' ? { kind: 'close' } : { kind: 'run', command: m[1]!, args: m[2]! }
463}
464
types/index.d.ts 91 lines
1export type Decision = { ts: number; session_id?: string; tool: string; target: string; decision: 'allow' | 'deny'; reason: string }
2export type StageKey = 'plan' | 'setgoal' | 'critique' | 'implement' | 'gate' | 'report'
3export type StageMark = 'done' | 'running' | 'pending' | 'failed'
4// a QualityGate verdict, subgoals/<id>/gate-<n>.json
5export type RunGate = { n: number; pass: boolean; reason: string }
6export type RunSub = { id: string; title: string; state: StageMark; reason: string; tries: number; gates: RunGate[]; stalled: boolean }
7// the current run of .harness-run/<run>/, as the mod reads it
8export type RunInfo = {
9  slug: string
10  title: string
11  live: boolean
12  finished: boolean
13  stages: { key: StageKey; state: StageMark }[]
14  subs: RunSub[]
15  done: number
16  total: number
17  now: { kind: 'implement' | 'test' | 'gate' | 'retry' | 'stage' | 'done'; id?: string; title?: string; attempt?: number; stage?: StageKey }
18  match: number | null
19  pass: boolean | null
20  // 02-critique.json: sound (null: no file) and why it was not
21  critique: { sound: boolean | null; reason: string }
22  goalReason: string // 04-goal-gate.json reason
23  lastMs: number // mtime of the run's newest file
24}
25
26// One row of `node engine/fallback-check.mjs --list --json` (P1's contract; status.ts normalizeRow reads it
27// tolerantly). The row keys: slug, dir, stage, round, waiting, stalled, now, started_at,
28// max_critique_rounds, severity, rounds, passed, failed, total.
29export type RowStage = 'plan' | 'setgoal' | 'critique' | 'implement' | 'gate' | 'report'
30export type Severity = { blocker: number; major: number; minor: number; nit: number }
31export type RowWaiting = { who: 'you' | 'vendor'; what: string }
32// now.json as the engine writes it; every field but stage may be null
33export type RowNow = {
34  stage: string | null
35  doing: string | null
36  round: number | null
37  last_step: string | null
38  next: string | null
39  waiting: RowWaiting | null
40  cost_usd: number | null
41  at: string | null
42  since: string | null
43}
44export type RowProblem = { severity: keyof Severity; text: string }
45// one critique round, oldest first; sound null when its file held no verdict
46export type RowRound = { round: number; sound: boolean | null; problems: RowProblem[] }
47export type HarnessRow = {
48  slug: string
49  stage: RowStage
50  round: number | null
51  waiting: RowWaiting | null
52  stalled: boolean
53  now: RowNow | null
54  started_at: string | null
55  max_critique_rounds: number
56  severity: Severity
57  rounds: RowRound[]
58  passed: number
59  failed: number
60  total: number
61}
62export type PaneTab = 'now' | 'flow' | 'findings' | 'rules'
63
64declare module 'claude-code' {
65  interface PluginState {
66    harness: {
67      last: Decision | null
68      armed: boolean
69      patterns: string[]
70      windowHours: number
71      // the files of the run the Flow and Gate rules tabs show (null: none read)
72      run: RunInfo | null
73      broken: boolean
74      lang: 'en' | 'ko'
75      // open harness runs from `--list --json`: the last good list, kept when a read fails
76      rows: HarnessRow[]
77      // the run the pane shows, by slug (null: opening order decides)
78      selected: string | null
79      // per slug, how many rejects (rejected critique rounds + failed subgoals) the person had seen
80      looked: Record<string, number>
81      // spinner frame counter, advanced only while a run acts and a pane or band is shown
82      tick: number
83      paneTab: PaneTab
84      // the demo fixture the pane and band draw (`/harness-status demo`); null: the live runs
85      demo: 'minimal' | 'full' | 'parallel' | 'narrow' | null
86      // the run outcome this mod publishes for trophy: labels only, never an id (same type in graph and teams)
87      outcome: { system: 'graph' | 'teams' | 'harness'; outcome: 'pass' | 'reject' | 'fail'; at: number } | null
88    }
89  }
90}
91