SLOPSHOPPER

dispatch

Plan before you fly — interview-driven specs you can execute. preflight captures what you want as INTENT.md before any solution is chosen; hop interviews…

paneguardcommandtoastprocesstimer
★ 1v5.7.7MITupdated 2026-10-26FunnyQ/cc-plugins/packages/dispatch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dispatch
│ ┃ flightdeck ✕ › fix the failing auth test and add an audit log call │ ┃ Loading… │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /flightdeck │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · flightdeck
Loading…
README

cc-plugins

A local Claude Code, Codex, and OpenCode plugin marketplace for a personal coding workflow. It ships five plugins: monitor turns local traces into useful dashboards — the usage-dashboard skill is the rear-view mirror for usage history, and the cockpit skill is the windshield for the session currently in flight; dispatch is interview-driven planning you can then execute — spec the work, write a blueprint to disk, and fly it with a quality loop, or map a whole project into milestone legs and plan each one just-in-time; relay delegates a task out to another harness's CLI (codex, opencode, or claude) — delegate work, request a review, or generate an image — then captures the result and reports back; chronicle authors your git history — commits (auto simple/atomic), reviewer-legible PRs/MRs, and config-first releases that bump versions, write the changelog, and cut the tag; herdr is reference plus a typed wrapper for driving agents across panes in the Herdr terminal workspace manager.

Development Workflow

This repository uses GitHub Flow. Create feature and fix branches from main, then open pull requests back into main. The existing develop branch is historical and does not indicate that this repository uses git-flow. Chronicle records this machine-readable PR policy in .chronicle/pr.json.

Plugins

monitor bundles three skills:

SkillDescription
usage-dashboardLocal usage dashboard for Claude Code, Codex, and OpenCode: sessions, tokens, cost, model mix, and project activity, plus live sessions for Claude Code and Codex
cockpitPer-project work cockpit for Claude Code, Codex, and OpenCode: goal capture, decision log, live transcript, needs-your-call bridge, and a send box for live sessions
installOne-stop prerequisite check and permission wiring for the whole plugin, command-triggered

dispatch bundles five skills:

SkillDescription
preflightShort interview that captures what you want as docs/<slug>/INTENT.md, before anyone decides how to build it — writes one file and stops, never executes
hopLightweight interviewer that gathers requirements into a single in-conversation plan to approve and execute
flightplanHeavyweight interviewer that writes a multi-file blueprint to disk — PLAN.md + a tasks/ tree of self-contained task files for sub-agents
autopilotExecutes a flightplan tree in parallel waves — a dev→verify→judge→score loop gated on each task's Eval rubric, an atomic commit between waves, then the closing final-review gate, leaving an audit trail
waypointsRolling-wave milestone-roadmap tier above flightplan — writes only docs/<proj>/WAYPOINTS.md plus a waypoints.ts CLI (active / leg-scaffold / advance) so each leg's flightplan is planned just-in-time after the previous leg lands

relay is a single portable skill:

SkillDescription
relayDelegate a task to another harness's CLI (codex / opencode / claude): delegate (do work), review (analysis only), or image (codex only) — capture the result, smart-apply when safe, and report back

chronicle bundles four skills:

SkillDescription
commitCraft git commit(s) for the current changes — auto-decides between one simple commit and an atomic split
prOpen a reviewer-legible PR/MR for the current branch, enriched by the cockpit decision trail when present
releaseCut a release — bump version files, write the CHANGELOG entry, then commit, merge, tag, and push; local stops before the push, prepare after the entry
installSet up chronicle's prerequisites — the named agent roles on Codex (Claude Code needs none)

herdr is a single skill:

SkillDescription
herdrReference for the Herdr terminal workspace manager (config, CLI, plugin dev) plus a typed herd wrapper to spawn and drive agents in sibling panes when running inside herdr

Claude Code Installation

CLI

claude plugins marketplace add FunnyQ/cc-plugins
claude plugins install monitor@q-lab-marketplace
# Any of these plugin ids works: monitor, dispatch, relay, chronicle, herdr

TUI

  1. Open Claude Code
  2. Type /plugins to open the plugin manager
  3. Select Add Marketplace → enter FunnyQ/cc-plugins
  4. Select Install Plugin → choose the plugin you want

The usage-dashboard skill runs a prerequisite check automatically before launching the dashboard, so there's no manual setup step. If something is missing, the hint is surfaced in the terminal. The most common case is stats-cache.json not existing yet; run /stats once in Claude Code to seed it.

If you want to run the precheck yourself:

bun $CLAUDE_PLUGIN_ROOT/skills/install/scripts/install.ts

Codex Installation

Codex reads this marketplace from .agents/plugins/marketplace.json. The registry lists all five plugins, and each is installed by id.

codex plugin marketplace add FunnyQ/cc-plugins
codex plugin add monitor@q-lab-marketplace
# Any of these plugin ids works: monitor, dispatch, relay, chronicle, herdr

Check the install:

codex plugin list | rg 'q-lab-marketplace|monitor'

After installing a Codex plugin, start a new Codex session so the skill list is refreshed.

OpenCode Installation

There is no plugin registry step. The repo is the single source of truth: opencode/install.ts symlinks skills, agents, commands, and the plugin module straight into ~/.config/opencode/, so an update to the checkout is live immediately — no reinstall, no rebuild.

Requires OpenCode 1.x. The plugin module targets OpenCode's V1 plugin API. OpenCode 2.x replaced that API, so on 2.x the module fails to load and none of its hooks run. The cockpit send and relay's opencode backend also support 1.x only.

bun opencode/install.ts --check     # report what is and is not wired
bun opencode/install.ts --apply     # symlink everything, raise subagent_depth
bun opencode/install.ts --unlink    # remove only what --apply created

--dry-run also exists — it prints the same plan as --apply without writing anything.

--apply installs:

InstallsCountTarget
Skills15~/.config/opencode/skills/<name>/
Plugin module1~/.config/opencode/plugin/q-lab.ts
Chronicle agents6~/.config/opencode/agents/<name>.md
Commands2~/.config/opencode/commands/<name>.md
subagent_depth1 edit~/.config/opencode/opencode.json

The subagent_depth prerequisite. --apply raises subagent_depth to at least 2 in ~/.config/opencode/opencode.json, the one config file it touches outside symlinks. The edit is raise-only — every other key in that file is preserved, and a value already ≥ 2 is left alone. OpenCode ships defaulting subagent_depth to 1, which blocks nesting outright, so this isn't a hypothetical edge case — it's the shipped default. Chronicle no longer needs it — none of its agents spawns a child — but dispatch's autopilot does: below the required depth its driver simply stops mid-run with no error naming the config, and the failure reads exactly like a plugin bug. Anyone hand-editing opencode.json instead of running --apply needs to set this key to 2 themselves.

Which config file gets the edit. OpenCode merges three global config names in order — config.json, then opencode.json, then opencode.jsonc — so the last one present wins. The installer patches whichever of those already exists, highest precedence first, and creates opencode.json only when none does. Two consequences: an existing opencode.jsonc is the file that gets raised, and a config carrying comments is read but never rewritten, because re-serializing it would delete them — --check and --apply report manual and print the line to add by hand.

Works under OpenCode:

  • All 15 skills, discovered from ~/.config/opencode/skills/.
  • usage-dashboard reads OpenCode data natively — the shared reader already handles ~/.local/share/opencode/opencode.db.
  • cockpit reads and sends for OpenCode sessions. Precondition: the OpenCode TUI must have been started with a port (opencode --port <n>), or OPENCODE_TUI_SERVER_URL must be set before cockpit starts.
  • relay delegate and review.
  • The five ported hook behaviors: decision-log start, the scribe nudge, the chronicle branch guard, the dispatch flightplan lint, and the guard comment check.
  • Both monitor commands.
  • Chronicle's subagents, spawned through the task tool.

Does not work under OpenCode:

  • The statusline. It is a Claude-only concept with no OpenCode equivalent, and there is no plan for one.
  • relay image — codex-only, and it fails at the capability gate before any CLI runs.
  • Workflow-driven autopilot. There is no Workflow tool, so autopilot runs as a manual task-tool wave loop instead: behaviorally close, but with no automatic parallel-wave scheduling.
  • monitor's setup.ts --session-check. It is deliberately not ported because it is inert outside Claude Code — it returns immediately without CLAUDE_PLUGIN_DATA, and its actual work is statusline-path migration and reaping orphaned Claude processes.

usage-dashboard

A single-page dashboard that reads local ~/.claude/ and ~/.codex/ data and visualizes usage in a browser. No telemetry, no cloud; everything stays on your machine.

Token Atlas dashboard preview

Features

  • Live now (Claude + Codex) — a panel of your currently-active Claude and Codex sessions with live status; click one to open it in cockpit's live transcript view (token-atlas links out rather than rendering transcripts itself). When cockpit's daemon isn't running the panel says so and the rows stay inert, so a click never opens a dead tab
  • Cost + usage overview — sessions, interactions, tokens, estimated spend, daily burn, and monthly budget projection
  • Persistent history — Claude usage is rolled into a local SQLite store (~/.local/share/q-lab/token-atlas/), so your token/cost/model history survives Claude Code's automatic transcript cleanup (cleanupPeriodDays) instead of disappearing as old sessions age out
  • Model analysis — daily trend, model distribution, and per-model token/cost breakdown
  • Project insights — project rankings with drilldown details for model mix and cost
  • Session ledger — recent Claude and Codex sessions side by side
  • Anomaly detection — flags days that break from your recent baseline
  • Token composition — input, output, cache-read, cache-write, and reasoning token shares
  • Activity timeline — hourly and daily activity patterns from local session data
  • Data health diagnostics — non-fatal source-read failures and record counts
  • Filters + export — provider/range filters, persisted preferences, and JSON/CSV export

Prerequisites

  • At least one Claude Code session (the cockpit shim fetches its release binary on first run)
  • For Claude usage totals, run /stats once to seed stats-cache.json

Quick Start

packages/monitor/skills/cockpit/bin/cockpit atlas serve   # [--port N] [--no-open]

As JSON instead: cockpit atlas stats (dashboard data), cockpit atlas live (active sessions), cockpit atlas rollup-update [--rebuild] (rollup DB).

Opens http://localhost:5938 in your default browser.

Options

--port <n>    Use a different port (default: 5938)
--no-open     Don't auto-open browser

Pricing

Token costs are estimated using bundled defaults (references/pricing-defaults.json). On startup, live prices are fetched from OpenRouter (3s timeout, silent fail). You can override with a custom file:

~/.config/cc-dashboard/pricing.json
{
  "models": {
    "claude-opus-4-7": { "input": 5.00, "output": 25.00, "cacheRead": 0.50, "cacheWrite": 6.25 }
  }
}

cockpit

Cockpit is a per-project dashboard and skill for active work. Start with a session goal, keep a distilled decision log, stream the current Claude Code or Codex transcript, and park on needs_your_call so a button click in the dashboard wakes the session.

Cockpit dashboard preview

Quick Start

In Claude Code or Codex, invoke the cockpit skill and confirm the proposed goals. From a development checkout, the dashboard can also be started directly:

packages/monitor/skills/cockpit/bin/cockpit server

Opens http://localhost:5858 in your default browser.

Provider Support

  • Claude Code transcripts resolve from ~/.claude/projects/**/<session>.jsonl.
  • Codex transcripts resolve from ~/.codex/state_5.sqlite thread rows and rollout files under ~/.codex/sessions.
  • OpenCode transcripts resolve via the opencode provider in packages/monitor/cockpit-rs/src/server/transcript.rs, reading the same ~/.local/share/opencode/opencode.db the usage-dashboard uses.
  • Decision logs live per-project under .cockpit/; the registry and wait/send bridge are shared through ~/.local/share/q-lab/cockpit/.

Send box

The send box at the bottom of the Decision Log column can send text into a running session.

  • Claude Code uses the monitor mod's inbox poll, described below. The agent's answer comes back through the live transcript.
  • Codex uses the managed Codex remote-control daemon. Cockpit connects to the local app-server control socket, resumes the selected thread, and submits or steers a turn. Direct app-server is only a fallback when remote-control is unavailable.
  • OpenCode uses the TUI HTTP bridge, not the mod: it discovers the running TUI from OPENCODE_TUI_SERVER_URL (or a ps scan for opencode --port <n>) and delivers through /tui/append-prompt + /tui/submit-prompt. Same port precondition as the OpenCode Installation section above — the TUI must have been started with --port; a serve process is not discovered, and a successful send is not a delivery receipt.

A monitor mod (hooks/register.ts) delivers Claude Code sends. On session start it long-polls the cockpit daemon's inbox over HTTP and submits each message as a new turn once the session is idle. The same mod relays permission dialogs to the dashboard. It needs a Claude Code build with function-hook mods, and a plain claude session gets both:

claude

If an older version left a hand-wired cockpit-channel entry in ~/.claude.json, /monitor:install removes it. See the cockpit skill for the full setup.

For Codex send support, install and enable the managed standalone Codex remote-control daemon:

curl -fsSL https://chatgpt.com/codex/install.sh | sh
codex app-server daemon enable-remote-control

Cockpit checks /api/codex-control/status before enabling the Codex send box, so stale or non-resumable threads stay disabled instead of failing only after send.

dispatch

Interview-driven planning you can execute. Four skills form one arc — capture what you want, gather the spec, commit a blueprint to disk, then fly it with a multi-agent quality loop — and a fifth, waypoints, sits above it for whole-project rolling-wave planning.

Dispatch flow: preflight, hop, waypoints, flightplan, autopilot, final review, ship

  • preflight — a short interview that captures what you want as docs/<slug>/INTENT.md, before anyone decides how to build it. Writes one file and stops; never executes.
  • hop — a lightweight interview that produces a single in-conversation plan and executes it. Best when you'll execute now, in one session. Formerly named preflight.
  • flightplan — a thorough interview that writes docs/<slug>/PLAN.md plus a tasks/ tree of self-contained task files (each with its own ## Eval rubric). Best when the work spans sessions or hands off to sub-agents.
  • autopilot — executes that tree in waves. Each wave re-scouts the ready set (next-ready) and runs those tasks in parallel; for each task it runs Dev → an independent binary gate (re-runs the task's Verification) → a rubric judge → a deterministic score gate, retrying until the task passes its rubric. Between waves it makes an atomic commit of the completed work, so the run leaves a clean per-wave history rather than one giant diff. The Final review task depends transitively on every other task, so the wave loop naturally schedules it last as the whole-tree gate — a closing multi-lens review round (cross-vendor codex + four /simplify lenses → an Opus fixer), followed by a final commit of its fixes. Every verdict lands in a self-gitignored docs/<slug>/.flightlog/ audit trail (RUNLOG.md).
  • waypoints — the tier above flightplan for large builds. It writes only a milestone roadmap (docs/<proj>/WAYPOINTS.md, legs tracked with [x]/[~]/[ ]); each leg's detailed flightplan is generated just-in-time after the previous leg lands, so every plan starts from what actually shipped rather than one oversized up-front guess. A waypoints.ts CLI collapses the lifecycle into three verbs — active (rolling-wave digest), leg-scaffold (nest a leg's tree under docs/<proj>/legs/NN-slug/), and advance (land the active leg; writing requires --outcome as the confirmation gate). flightplan gains a narrow waypoint mode that plans one leg at a time. Human-in-loop by design — one leg lands before the next is planned.

Installation

# Claude Code
claude plugins install dispatch@q-lab-marketplace

# Codex
codex plugin add dispatch@q-lab-marketplace

# OpenCode
bun opencode/install.ts --apply

(Add the marketplace first if you haven't — see the monitor install steps above.)

relay

One portable skill that delegates a task out to another harness's CLI, then captures the output and reports back — a multi-backend generalization of the codex-only odin-codex skill.

/relay <codex|opencode|claude> delegate <task>
/relay <codex|opencode|claude> review [task]
/relay codex image <prompt> --out <path>
  • delegate — ask a backend to do something (implement, refactor, debug); smart-applied when safe.
  • review — analysis only, no edits. No task reviews uncommitted changes; a provided task is followed as written.
  • image — generate an image via codex (gpt-image-2). codex-only; opencode/claude fail fast at the capability gate.

A capability gate rejects unsupported (backend, mode) pairs before any CLI runs. Every run captures full output to /tmp/relay/<ts>/last.md and prints it. Models resolve by precedence: --model flag > config file (~/.config/q-lab/cc-plugins/relay/config.json) > built-in defaults. Per-CLI invocation details, headless output handling, and the OpenCode symlink install live in the backend reference.

Live-pane mode — inside herdr (HERDR_ENV=1), delegate/review automatically run the backend's interactive TUI in a visible, take-over-able pane opened in its own new tab (so your working pane keeps its full size), via the herdr plugin's herd.ts, dynamically imported — no hard dependency. The answer is captured through a result-file contract; stdout stays the clean answer, live metadata rides stderr. --dangerous makes it a YOLO / unattended run (auto-approves permissions: codex/claude bypass flags, opencode --auto); without it, approval prompts surface in the pane for a human to answer. A run that outlives --wait-timeout (default 10 min) exits 0 with a "still running" report and leaves the pane alive. --headless opts out; outside herdr the classic headless flow is unchanged.

Installation

# Claude Code
claude plugins install relay@q-lab-marketplace

# Codex
codex plugin add relay@q-lab-marketplace

# OpenCode
bun opencode/install.ts --apply

If you previously ran the old manual symlink (ln -s .../packages/relay/skills/relay ~/.claude/skills/relay), remove it. opencode/install.ts --apply installs relay under ~/.config/opencode/skills/, and OpenCode scans ~/.claude/skills/ as well — leaving the old symlink in place surfaces two skills both named relay. --check warns about it.

chronicle

Chronicle authors your git history — what a commit says, what a pull request argues, and what a release ships. A thin SKILL.md sends the bulky reading to an agent — a diff, a branch, a range of commits — and keeps the decisions where you can see them. Diff-reading and git output stay out of your conversation.

  • commit — one agent reads the changeset, cuts it into commits that each build on their own, and writes the messages; a script decides whether the split is worth keeping and does the staging. Pass simple to force one commit.
  • pr — reads the branch, harvests the cockpit decision trail when one exists, and opens a GitHub PR or GitLab MR with a title, a four-section body, and an optional Mermaid overview diagram. The trail is an enrichment, not a requirement; an unrecognized remote stops the flow rather than guessing.
  • release — config-first: detects whole-repo vs per-component layout, remembers it in a committed .chronicle/release.json, then bumps the version files and writes the CHANGELOG entry, commits, tags, and pushes. Pass local to stop before the push, or prepare to stop after the entry.
  • install — sets up each harness's prerequisite: on Claude Code the nested-subagent spawn-depth setting described in the Plugins section above, on Codex the named agent roles the orchestrators are addressed by.

Installation

# Claude Code
claude plugins install chronicle@q-lab-marketplace

# Codex
codex plugin add chronicle@q-lab-marketplace

# OpenCode
bun opencode/install.ts --apply

herdr

Reference and in-session agent orchestration for Herdr, a terminal workspace manager with workspaces, tabs, split panes, and agent detection. Two halves:

  • Reference — a knowledge skill that answers questions about Herdr's config.toml, CLI, keybindings, and plugin development. Detail lives in references/; the skill reads only the relevant file.
  • herd wrapper — a typed Bun wrapper (scripts/herd.ts) over the raw herdr CLI, for when you (an agent) are running inside a herdr pane (HERDR_ENV=1) and want to spawn and drive other agents in sibling panes or their own tabs (spawn --new-tab). It collapses herdr's multi-step recipes into seven verbs and handles the sharp edges: it addresses agents by a collision-resistant generated name (pane ids renumber), its send writes the prompt and presses Enter (raw agent send only writes literal text), its keys verb sends bare key chords (submit / clear the input box), and its read defaults to the visible screen (agent TUIs leave scrollback empty).
HERD="$CLAUDE_PLUGIN_ROOT/skills/herdr/scripts/herd.ts"   # or the skill's load-time base dir

bun "$HERD" spawn reviewer --agent codex --task "review the diff in src/api/"
bun "$HERD" send reviewer-a3f9 "now check error handling"
bun "$HERD" wait reviewer-a3f9 --status idle --time
Source 7 files
hooks/register.ts 43 lines
1/**
2 * flightplan-lint as a Claude Code mod: the matcher rejects every path outside
3 * a flightplan tasks tree before the hook runs, so an unrelated Edit or Write
4 * spawns nothing. Violations ride back as the result's `context`, which the
5 * model reads the way it read the command hook's exit-2 stderr. OpenCode keeps
6 * flightplan-lint.sh, since it has no function hooks.
7 */
8
9import type { Register } from "claude-code";
10import { flightdeck } from "./flightdeck/flightdeck.tsx";
11import { TASK_PATH } from "./task-path.ts";
12
13export const register: Register = (on) => {
14  on(
15    "tool.call",
16    { tool: ["Edit", "Write"], file_path: TASK_PATH },
17    async ($, e, next) => {
18      const ran = await next(e);
19      if (ran.deny !== undefined || ran.isError) return ran;
20      if ((ran.result as { staged?: boolean }).staged) return ran;
21
22      const lint = await $.process.run([
23        "bun",
24        `${$.plugin.root}/skills/flightplan/scripts/lint-task.ts`,
25        "--authoring",
26        e.file_path,
27      ]);
28      if (lint.exitCode === 0) return ran;
29
30      const output = `${lint.stdout}${lint.stderr}`.trimEnd();
31      return {
32        ...ran,
33        context: [
34          ...(ran.context ?? []),
35          `flightplan lint violations in ${e.file_path}:\n${output}`,
36        ],
37      };
38    },
39  );
40
41  flightdeck(on);
42};
43
hooks/flightdeck/flightdeck.tsx 377 lines
1import { atom, read, update } from "claude-code";
2import type { EngineInterface, On, Timer } from "claude-code";
3
4import type { FlightdeckDeck } from "../../types";
5import { FLIGHTDECK_COMMAND, planArg, planFromOutput } from "./deck-command.ts";
6import {
7  type CardModel,
8  clip,
9  COLOR,
10  docked,
11  inline,
12  type Line,
13} from "./rows.ts";
14import type { DeckSnapshot, DeckTask, DeckTokens } from "./types.ts";
15
16const PANE = "flightdeck";
17const COLUMNS = 40;
18const INLINE_ROWS = 2;
19const SNAPSHOT_POLL_MS = 2000;
20
21const EMPTY: FlightdeckDeck = {
22  snapshot: null,
23  stale: false,
24  message: null,
25  tokenMode: "fresh",
26};
27const deck = atom({ plugin: "dispatch", key: "flightdeck" } as const, EMPTY);
28
29// the module keeps the truth and publishes it whole, so two writes racing on the atom both land the latest view
30let view: FlightdeckDeck = EMPTY;
31let generation = 0;
32let ticker: Timer | undefined;
33let lastOut = "";
34let followedPlan: string | null = null;
35
36const publish = ($: EngineInterface) => update($, deck, () => view);
37
38const firstLine = (text: string) => text.split("\n")[0]?.trim() ?? "";
39const runScript = ($: EngineInterface, name: string, ...args: string[]) =>
40  $.process.run([
41    "bun",
42    `${$.plugin.root}/skills/autopilot/scripts/${name}`,
43    ...args,
44  ]);
45const isOpen = async ($: EngineInterface) =>
46  (await $.ui.panes()).some((p) => p.id === PANE);
47const isPlaced = async ($: EngineInterface) =>
48  (await $.ui.panes()).some((p) => p.id === PANE && p.isPlaced);
49
50const toastText = (t: DeckTask) => {
51  const parts = [t.ref, t.title, t.state, `attempt ${t.attempts}`];
52  if (t.score)
53    parts.push(
54      `score ${t.score.weighted.toFixed(1)}/${t.score.threshold.toFixed(1)} ${t.score.passed ? "passed" : "failed"}`,
55    );
56  return parts.join(" · ");
57};
58
59const tokens = new Map<string, DeckTokens | null>();
60let runTokens: DeckTokens | null = null;
61const unread = (s: DeckSnapshot | null) =>
62  Object.values(s?.tasks ?? {}).some(
63    (t) => t.state === "done" && !tokens.has(t.ref),
64  );
65
66const refresh = async ($: EngineInterface, gen: number, plan: string) => {
67  const withUsage = unread(view.snapshot as DeckSnapshot | null);
68  const r = withUsage
69    ? await runScript($, "deck-snapshot.ts", plan, "--usage")
70    : await runScript($, "deck-snapshot.ts", plan);
71  if (gen !== generation) return;
72  if (r.exitCode === 0) {
73    if (r.stdout !== lastOut || view.stale || withUsage) {
74      lastOut = r.stdout;
75      const snapshot = JSON.parse(r.stdout) as DeckSnapshot;
76      for (const t of Object.values(snapshot.tasks)) {
77        if (t.state !== "done") continue;
78        if (withUsage && !tokens.has(t.ref)) tokens.set(t.ref, t.tokens);
79        t.tokens = tokens.get(t.ref) ?? null;
80      }
81      if (withUsage) runTokens = snapshot.tokens;
82      snapshot.tokens = runTokens;
83      view = {
84        ...view,
85        snapshot,
86        stale: false,
87        message: null,
88      };
89      await publish($);
90    }
91  } else {
92    const message = firstLine(r.stderr);
93    if (!view.stale || view.message !== message) {
94      view = { ...view, stale: true, message };
95      await publish($);
96    }
97  }
98  const live = view.snapshot as DeckSnapshot | null;
99  if (live?.agents.length || (live?.time && live.time.endedAt === null))
100    $.ui.invalidate("ui.render");
101};
102
103const openOn = async ($: EngineInterface, plan: string) => {
104  const gen = ++generation;
105  followedPlan = plan;
106  tokens.clear();
107  runTokens = null;
108  view = { ...EMPTY, tokenMode: view.tokenMode };
109  lastOut = "";
110  void publish($);
111  ticker?.cancel();
112  let isRunning = false;
113  let isFirst = true;
114  const tick = async () => {
115    if (isRunning) return;
116    isRunning = true;
117    try {
118      if (!isFirst && !(await isOpen($))) {
119        if (gen === generation) {
120          generation++;
121          followedPlan = null;
122          own.cancel();
123        }
124        return;
125      }
126      isFirst = false;
127      await refresh($, gen, plan);
128    } finally {
129      isRunning = false;
130    }
131  };
132  const own = $.clock.every(SNAPSHOT_POLL_MS, () => void tick());
133  ticker = own;
134  void tick();
135  const title = `Flightdeck · ${plan.replace(/\/+$/, "").split("/").pop()}`;
136  return $.ui.open({
137    id: PANE,
138    title,
139    columns: COLUMNS,
140    rows: INLINE_ROWS,
141  });
142};
143
144const close = async ($: EngineInterface) => {
145  generation++;
146  followedPlan = null;
147  ticker?.cancel();
148  ticker = undefined;
149  await $.ui.close({ id: PANE });
150};
151
152export const flightdeck = (on: On) => {
153  // a matcher of its own, so no other unmatched session.start hook in this module collides with it
154  on("session.start", { isInteractive: true }, async ($, e, next) => {
155    await $.command.register({
156      name: "flightdeck",
157      description: "Open the flightdeck overview pane",
158      argumentHint: "[planDir|close]",
159    });
160    return next(e);
161  });
162
163  on("command.run", { command: "flightdeck" }, async ($, e) => {
164    const arg = e.args.trim();
165    if (arg === "close" || (arg === "" && (await isPlaced($)))) {
166      await close($);
167      return { text: "Flightdeck closed." };
168    }
169    const target = arg || followedPlan;
170    if (target) {
171      await openOn($, target);
172      return { text: `Flightdeck opened on ${target}.` };
173    }
174    const gen = generation;
175    const top = await $.process.run(["git", "rev-parse", "--show-toplevel"]);
176    const root = top.exitCode === 0 ? top.stdout.trim() : await $.session.cwd();
177    const r = await runScript($, "deck-snapshot.ts", "--latest", root);
178    if (r.exitCode === 3)
179      return { text: `No flightplan run found under ${root}/docs` };
180    if (r.exitCode !== 0) return { text: firstLine(r.stderr) };
181    if (gen !== generation) return { text: "Flightdeck lookup superseded." };
182    const { plan } = JSON.parse(r.stdout) as { plan: string };
183    await openOn($, plan);
184    return { text: `Flightdeck opened on ${plan}.` };
185  });
186
187  // a distinct matcher from register.ts's Edit|Write lint hook; opens in the launching session only
188  on(
189    "tool.call",
190    { tool: "Bash", command: FLIGHTDECK_COMMAND },
191    async ($, e, next) => {
192      const ran = await next(e);
193      if (ran.deny !== undefined || ran.isError) return ran;
194      const plan =
195        planFromOutput((ran.result as { stdout?: string }).stdout ?? "") ??
196        planArg(e.command);
197      if (plan && !(await openOn($, plan)).isPlaced)
198        $.ui.toast(
199          "Flightdeck is waiting for a wider terminal. Type /flightdeck to show it.",
200        );
201      return ran;
202    },
203  );
204
205  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
206    const { Box, Text, Button } = $.ui.resolve(e);
207    const { snapshot, stale, message, tokenMode } = await read($, deck);
208    const s = snapshot as DeckSnapshot | null;
209    const width = e.props.bodyColumns ?? COLUMNS;
210
211    const row = (line: Line) => (
212      <Box flexDirection="row">
213        {line.length === 0 && <Text> </Text>}
214        {line.map((seg) => {
215          const task = seg.ref ? s?.tasks[seg.ref] : undefined;
216          if (!task)
217            return (
218              <Text color={seg.color} dimColor={seg.dim}>
219                {seg.text}
220              </Text>
221            );
222          // a Button takes no colour, so the ref is the pressable part and the coloured glyph rides beside it; a clip that cut into the ref leaves it all pressable
223          const head = seg.text.startsWith(task.ref) ? task.ref : seg.text;
224          const rest = seg.text.slice(head.length);
225          return (
226            <Box flexDirection="row">
227              <Button
228                key={`card:${task.ref}`}
229                plain
230                dimColor={seg.dim}
231                label={head}
232                onPress={() => $.ui.toast(toastText(task))}
233              />
234              {rest && (
235                <Text color={seg.color} dimColor={seg.dim}>
236                  {rest}
237                </Text>
238              )}
239            </Box>
240          );
241        })}
242      </Box>
243    );
244
245    if (!s)
246      return row(clip([{ text: message ?? "Loading…", dim: true }], width));
247    if (e.props.placement === "inline")
248      return (
249        <Box flexDirection="column">{inline(s, width, stale).map(row)}</Box>
250      );
251    const launch = async () => {
252      const r = await runScript($, "flightdeck.ts", "--plan", s.plan, "--open");
253      if (r.exitCode !== 0) $.ui.toast(firstLine(r.stderr));
254    };
255    const { title, totals, bars, wave, states, cards, crew } = docked(
256      s,
257      width,
258      Date.now(),
259      stale,
260      tokenMode,
261    );
262    const toggleTokens = async () => {
263      view = {
264        ...view,
265        tokenMode: view.tokenMode === "fresh" ? "billed" : "fresh",
266      };
267      await publish($);
268    };
269    // a Button takes no colour, so the glyph is coloured Text and the ref beside it is the pressable part
270    const cardBox = (c: CardModel) => (
271      <Box
272        flexDirection="column"
273        width={cards.inner + 2}
274        borderStyle="round"
275        borderColor={c.color}
276        borderDimColor={c.dim}
277      >
278        <Box flexDirection="row">
279          <Text color={c.color} dimColor={c.dim}>
280            {c.head.slice(0, 2)}
281          </Text>
282          <Button
283            key={`card:${c.ref}`}
284            plain
285            dimColor={c.dim}
286            label={c.head.slice(2)}
287            onPress={() => $.ui.toast(toastText(s.tasks[c.ref]!))}
288          />
289          {c.time && (
290            <Box flexGrow={1} justifyContent="flex-end">
291              <Text dimColor>{c.time}</Text>
292            </Box>
293          )}
294        </Box>
295        <Text dimColor>{c.sub}</Text>
296        {c.agents.map((line) => (
297          <Text color={COLOR["in-progress"]}>{line}</Text>
298        ))}
299        {c.tokens && <Text dimColor>{c.tokens}</Text>}
300      </Box>
301    );
302    return (
303      // the top row clears the pane's close mark, which sits over the body's first line
304      <Box flexDirection="column" paddingTop={1}>
305        <Box
306          key="title"
307          justifyContent="center"
308          borderStyle="round"
309          borderDimColor
310        >
311          <Text bold>{title}</Text>
312        </Box>
313        {totals && (
314          <Box
315            key="totals"
316            flexDirection="column"
317            borderStyle="round"
318            borderDimColor
319            paddingX={1}
320          >
321            <Button
322              key="token-mode"
323              plain
324              dimColor
325              label={`Total Cost · ${tokenMode}`}
326              onPress={() => void toggleTokens()}
327            />
328            <Box flexDirection="row" justifyContent="space-between">
329              <Text>{totals.time}</Text>
330              {totals.tokens && <Text>{totals.tokens}</Text>}
331            </Box>
332          </Box>
333        )}
334        {bars.map(row)}
335        {crew.length > 0 && (
336          <Box
337            key="loose-agents"
338            flexDirection="column"
339            alignItems="center"
340            borderStyle="round"
341            borderColor={COLOR["in-progress"]}
342          >
343            {crew.map(row)}
344          </Box>
345        )}
346        {row([])}
347        <Box flexDirection="row" justifyContent="center">
348          {row(wave)}
349        </Box>
350        <Box flexDirection="row" justifyContent="center">
351          {row(states)}
352        </Box>
353        {cards.groups.map((g) => (
354          <Box flexDirection="row">
355            <Text>{g.label}</Text>
356            <Box
357              flexDirection="row"
358              flexWrap="wrap"
359              flexShrink={1}
360              columnGap={1}
361            >
362              {g.cards.map(cardBox)}
363            </Box>
364          </Box>
365        ))}
366        <Box flexDirection="row" justifyContent="center">
367          <Button
368            key="open"
369            label="Open flightdeck"
370            onPress={() => void launch()}
371          />
372        </Box>
373      </Box>
374    );
375  });
376};
377
hooks/task-path.ts 3 lines
1export const TASK_PATH =
2  /(^|\/)docs\/.+\/tasks\/[a-z][a-z0-9]*\/[0-9]{2}-.+\.md$/;
3
hooks/flightdeck/deck-command.ts 21 lines
1export const FLIGHTDECK_COMMAND =
2  /(?<![\w.-])flightdeck\.ts(?![\w.-])[\s\S]*?\s--plan(?:=|\s)/;
3
4const LAUNCHER = /(?<![\w.-])flightdeck\.ts(?![\w.-])/;
5const PLAN = /\s--plan(?:=|\s+)(?:"([^"]*)"|'([^']*)'|([^\s"']+))/;
6
7const PLAN_LINE = /^flightdeck plan: (.+)$/m;
8
9export function planFromOutput(stdout: string): string | null {
10  return PLAN_LINE.exec(stdout)?.[1] ?? null;
11}
12
13export function planArg(command: string): string | null {
14  const at = LAUNCHER.exec(command);
15  if (!at) return null;
16  const call = command.slice(at.index).split(/[;&|]/)[0] ?? "";
17  const m = PLAN.exec(call);
18  const plan = m && (m[1] ?? m[2] ?? m[3]);
19  return plan && !plan.includes("$") ? plan : null;
20}
21
hooks/flightdeck/rows.ts 354 lines
1import type {
2  DeckAgent,
3  DeckCrew,
4  DeckSnapshot,
5  DeckState,
6  DeckTask,
7  DeckTokens,
8} from "./types.ts";
9
10export type Seg = { text: string; color?: string; dim?: boolean; ref?: string };
11export type Line = Seg[];
12
13export const GLYPH: Record<DeckState, string> = {
14  done: "✓",
15  "in-progress": "●",
16  ready: "○",
17  blocked: "·",
18  invalid: "✗",
19};
20
21export const COLOR: Record<DeckState, string | undefined> = {
22  done: "#3fb950",
23  "in-progress": "#d29922",
24  ready: undefined,
25  blocked: undefined,
26  invalid: "#f85149",
27};
28
29const SEP = " · ";
30
31const width = (line: Line) => line.reduce((n, seg) => n + seg.text.length, 0);
32
33const styled = (state: DeckState, text: string): Seg => ({
34  text,
35  ...(COLOR[state] && { color: COLOR[state] }),
36  ...(state === "blocked" && { dim: true }),
37});
38
39export function card(task: DeckTask): Seg {
40  const attempts = task.attempts > 1 ? String(task.attempts) : "";
41  return {
42    ...styled(task.state, `${task.ref} ${GLYPH[task.state]}${attempts}`),
43    ref: task.ref,
44  };
45}
46
47export function endState(s: DeckSnapshot): "wave" | "done" | "stuck" {
48  if (s.currentWave !== null) return "wave";
49  return s.counts.done === s.counts.total ? "done" : "stuck";
50}
51
52function stuckRefs(s: DeckSnapshot): string[] {
53  return s.unschedulable.filter((ref) => s.tasks[ref]?.state !== "done");
54}
55
56function diagnostics(s: DeckSnapshot, stale: boolean): Line {
57  const line: Line = [];
58  if (stale) line.push({ text: "stale", dim: true }, { text: SEP });
59  if (s.errors > 0)
60    line.push(
61      { text: `${s.errors} errors`, color: COLOR.invalid },
62      { text: SEP },
63    );
64  return line;
65}
66
67export const BAR = "━";
68
69function bar(done: number, total: number, cells: number): Line {
70  const filled = total > 0 ? Math.round((done / total) * cells) : 0;
71  const line: Line = [];
72  if (filled > 0) line.push({ text: BAR.repeat(filled), color: COLOR.done });
73  if (cells - filled > 0)
74    line.push({ text: BAR.repeat(cells - filled), dim: true });
75  return line;
76}
77
78export type TokenMode = keyof DeckTokens;
79
80export function runTotals(
81  s: DeckSnapshot,
82  now: number,
83  mode: TokenMode,
84): { time: string; tokens: string | null } | null {
85  if (!s.time) return null;
86  const end = s.time.endedAt === null ? now : Date.parse(s.time.endedAt);
87  return {
88    time: formatElapsed(end - Date.parse(s.time.startedAt)),
89    tokens: s.tokens === null ? null : `${formatTokens(s.tokens[mode])} tok`,
90  };
91}
92
93export function summary(s: DeckSnapshot, stale: boolean): Line[] {
94  const state = endState(s);
95  const wave: Line = [
96    state === "wave"
97      ? { text: `wave ${s.currentWave}/${s.waves.length}` }
98      : state === "done"
99        ? { text: "all done" }
100        : {
101            text: `stuck · ${stuckRefs(s).length} unschedulable`,
102            color: COLOR.invalid,
103          },
104  ];
105
106  const c = s.counts;
107  const pair = (state: DeckState, n: number, word: string): Seg => {
108    const text = `${GLYPH[state]} ${n}${word ? ` ${word}` : ""}`;
109    return state === "invalid" && n === 0 ? { text } : styled(state, text);
110  };
111  const states: Line = [
112    ...diagnostics(s, stale),
113    pair("in-progress", c.inProgress, "running"),
114    { text: "  " },
115    pair("ready", c.ready, "ready"),
116    { text: "  " },
117    pair("blocked", c.blocked, "waiting"),
118    { text: "  " },
119    pair("invalid", c.invalid, ""),
120  ];
121  return [wave, states];
122}
123
124export function compactSummary(s: DeckSnapshot, stale: boolean): Line {
125  const line: Line = [
126    ...diagnostics(s, stale),
127    { text: `${s.counts.done}/${s.counts.total}${SEP}` },
128  ];
129  const state = endState(s);
130  if (state === "wave")
131    line.push({ text: `W${s.currentWave}/${s.waves.length}` });
132  else if (state === "done") line.push({ text: "all done" });
133  else line.push({ text: "stuck", color: COLOR.invalid });
134  line.push({ text: `${SEP}${s.slug}` });
135  return line;
136}
137
138export function bucketBars(s: DeckSnapshot, w: number): Line[] {
139  const nameW = Math.max(0, ...s.buckets.map((b) => b.name.length));
140  return s.buckets.map((b) => {
141    const count = `${b.done}/${b.total}`;
142    const barW = Math.max(1, w - nameW - 2 - count.length);
143    return [
144      { text: `${b.name.padEnd(nameW)} ` },
145      ...bar(b.done, b.total, barW),
146      { text: ` ${count}` },
147    ];
148  });
149}
150
151const MIN_INNER = 17;
152const SLACK = 4;
153
154export type CardModel = {
155  ref: string;
156  head: string; // glyph + ref
157  sub: string; // title, then attempts/score right-aligned, padded to the inner width
158  time: string | null; // time spent, right of the head; null before any agent started
159  tokens: string | null; // right-aligned to the inner width, done tasks only
160  agents: string[]; // one line per in-flight agent on this task: role, attempt, elapsed
161  color?: string;
162  dim?: boolean;
163};
164export type WaveCards = {
165  inner: number; // every card's width inside its border
166  groups: { label: string; cards: CardModel[] }[];
167};
168
169const fit = (text: string, w: number) =>
170  text.length <= w ? text : `${text.slice(0, Math.max(0, w - 1))}…`;
171
172const elapsedOf = (a: DeckAgent, now: number) =>
173  a.startedAt === null ? "—" : formatElapsed(now - Date.parse(a.startedAt));
174
175const spread = (left: string, right: string, inner: number) => {
176  const leftW = Math.max(0, inner - right.length - 1);
177  return `${fit(left, leftW).padEnd(leftW)} ${right}`.slice(0, inner);
178};
179
180// the web fleet's token format, so the two views print one number the same way
181export function formatTokens(n: number): string {
182  if (n < 1_000) return String(Math.trunc(n));
183  if (n < 1_000_000) return `${(n / 1_000).toFixed(1)}K`;
184  return `${(n / 1_000_000).toFixed(1)}M`;
185}
186
187function timeOf(t: DeckTask, now: number): string | null {
188  if (!t.time) return null;
189  const end = t.time.endedAt === null ? now : Date.parse(t.time.endedAt);
190  return formatElapsed(end - Date.parse(t.time.startedAt));
191}
192
193export function waveCards(
194  s: DeckSnapshot,
195  w: number,
196  now: number,
197  mode: TokenMode,
198): WaveCards {
199  const groups = s.waves.map((refs, i) => ({ label: `W${i + 1}`, refs }));
200  if (s.unschedulable.length > 0)
201    groups.push({ label: "W?", refs: s.unschedulable });
202  const labelW = Math.max(0, ...groups.map((g) => g.label.length)) + 1;
203  const longest = Math.max(
204    0,
205    ...groups.flatMap((g) => g.refs.map((r) => r.length)),
206  );
207  const inner = Math.max(
208    1,
209    Math.min(Math.max(MIN_INNER, longest + 2 + SLACK), w - labelW - 2),
210  );
211
212  const model = (t: DeckTask): CardModel => {
213    const meta = [
214      t.score ? t.score.weighted.toFixed(1) : "",
215      t.attempts > 1 ? `a${t.attempts}` : "",
216    ]
217      .filter(Boolean)
218      .join(" ");
219    const { color, dim } = styled(t.state, "");
220    const time = timeOf(t, now);
221    return {
222      ref: t.ref,
223      head: fit(
224        `${GLYPH[t.state]} ${t.ref}`,
225        time ? inner - time.length - 1 : inner,
226      ),
227      time,
228      tokens:
229        t.tokens === null
230          ? null
231          : `${formatTokens(t.tokens[mode])} tok`.padStart(inner),
232      sub: meta
233        ? spread(t.title, meta, inner)
234        : fit(t.title, inner).padEnd(inner),
235      agents: s.agents
236        .filter((a) => a.ref === t.ref)
237        .map((a) =>
238          spread(
239            `${a.role}${a.attempt === null ? "" : ` #${a.attempt}`}`,
240            elapsedOf(a, now),
241            inner,
242          ),
243        ),
244      ...(color && { color }),
245      ...(dim && { dim }),
246    };
247  };
248  return {
249    inner,
250    groups: groups.map((g) => ({
251      label: g.label.padEnd(labelW),
252      cards: g.refs.map((ref) => model(s.tasks[ref]!)),
253    })),
254  };
255}
256
257export function formatElapsed(ms: number): string {
258  const total = Math.max(0, Math.floor(ms / 1000));
259  if (total < 60) return `${total}s`;
260  const m = Math.floor(total / 60);
261  if (m < 60) return `${m}m${String(total % 60).padStart(2, "0")}s`;
262  return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}m`;
263}
264
265const CREW_GLYPH = {
266  "in-flight": GLYPH["in-progress"],
267  finished: GLYPH.done,
268  abandoned: GLYPH.invalid,
269};
270
271export function crewLines(s: DeckSnapshot, now: number): Line[] {
272  const roleW = Math.max(0, ...s.crew.map((c) => c.role.length));
273  const labelW = Math.max(0, ...s.crew.map((c) => c.label.length));
274  return s.crew.map((c: DeckCrew) => {
275    const elapsed =
276      c.status === "in-flight"
277        ? c.startedAt === null
278          ? "—"
279          : formatElapsed(now - Date.parse(c.startedAt))
280        : c.elapsedMs === null
281          ? "—"
282          : formatElapsed(c.elapsedMs);
283    const text = `${CREW_GLYPH[c.status]} ${c.role.padEnd(roleW)} ${c.label.padEnd(labelW)}  ${elapsed}`;
284    return [
285      c.status === "in-flight"
286        ? { text, color: COLOR["in-progress"] }
287        : { text, dim: true },
288    ];
289  });
290}
291
292export function clip(line: Line, w: number): Line {
293  if (width(line) <= w) return line;
294  if (w < 1) return [];
295  if (w === 1) return [{ ...line[0], text: "…" }];
296  const out: Line = [];
297  let left = w - 1;
298  for (const seg of line) {
299    if (left === 0) break;
300    const text = seg.text.slice(0, left);
301    left -= text.length;
302    if (text.length > 0) out.push({ ...seg, text });
303  }
304  const last = out[out.length - 1];
305  last.text += "…";
306  return out;
307}
308
309export function docked(
310  s: DeckSnapshot,
311  w: number,
312  now: number,
313  stale: boolean,
314  mode: TokenMode,
315): {
316  title: string;
317  totals: ReturnType<typeof runTotals>;
318  bars: Line[];
319  wave: Line;
320  states: Line;
321  cards: WaveCards;
322  crew: Line[];
323} {
324  const [wave, states] = summary(s, stale);
325  return {
326    title: s.slug,
327    wave: clip(wave, w),
328    totals: runTotals(s, now, mode),
329    bars: bucketBars(s, w).map((l) => clip(l, w)),
330    states: clip(states, w),
331    cards: waveCards(s, w, now, mode),
332    crew: crewLines(s, now).map((l) => clip(l, w - 2)),
333  };
334}
335
336export function inline(s: DeckSnapshot, w: number, stale: boolean): Line[] {
337  const state = endState(s);
338  let second: Line;
339  if (state === "done") second = [{ text: "all done" }];
340  else {
341    const label = state === "wave" ? `W${s.currentWave} ` : "W? ";
342    const refs =
343      state === "wave"
344        ? (s.waves[(s.currentWave as number) - 1] ?? [])
345        : stuckRefs(s);
346    second = [{ text: label }];
347    refs.forEach((ref, i) => {
348      if (i > 0) second.push({ text: "  " });
349      second.push(card(s.tasks[ref]!));
350    });
351  }
352  return [clip(compactSummary(s, stale), w), clip(second, w)];
353}
354
hooks/flightdeck/types.ts 57 lines
1export type DeckState =
2  "done" | "in-progress" | "ready" | "blocked" | "invalid";
3
4export type DeckTask = {
5  ref: string; // "bucket/NN", or the graph node id
6  title: string;
7  state: DeckState;
8  attempts: number;
9  score: { weighted: number; threshold: number; passed: boolean } | null;
10  time: { startedAt: string; endedAt: string | null } | null; // first agent start to last finish; endedAt null while one runs
11  tokens: DeckTokens | null; // done tasks only, and only from a --usage run
12};
13
14export type DeckTokens = { fresh: number; billed: number };
15
16export type DeckAgent = {
17  role: string; // FleetRow.role
18  ref: string | null;
19  attempt: number | null;
20  label: string;
21  startedAt: string | null; // ISO; the pane renders elapsed from it at draw time
22};
23
24// a fleet row with no task card to ride (scout, commit), kept after it ends as the web fleet keeps it
25export type DeckCrew = {
26  role: string;
27  label: string;
28  status: "in-flight" | "finished" | "abandoned";
29  startedAt: string | null; // ISO; in-flight elapsed is drawn from it
30  elapsedMs: number | null; // a finished row's duration
31};
32
33export type DeckSnapshot = {
34  deckSource: "tasks" | "graph";
35  plan: string; // absolute plan dir
36  slug: string;
37  planTitle: string;
38  counts: {
39    total: number;
40    done: number;
41    inProgress: number;
42    ready: number;
43    blocked: number;
44    invalid: number;
45  };
46  buckets: { name: string; done: number; total: number }[]; // TreePayload.buckets order
47  waves: string[][]; // waves[0] = wave 1; refs in TreePayload.tasks order
48  unschedulable: string[]; // refs no layer reaches (cycle, dangling dep), sorted
49  currentWave: number | null; // 1-based: lowest wave holding a non-done task; null when no wave holds one (all done, or only unschedulable work left)
50  tasks: Record<string, DeckTask>;
51  agents: DeckAgent[]; // FleetRow.status === "in-flight" only, startedAt ascending
52  crew: DeckCrew[];
53  time: DeckTask["time"]; // the whole run: first agent start to last finish, open while one runs
54  tokens: DeckTokens | null; // the whole run's, crew included, only from a --usage run // the latest 3 taskless fleet rows of any status, newest first
55  errors: number; // TreePayload.errors.length
56};
57
types/index.d.ts 14 lines
1// `snapshot` is a DeckSnapshot (hooks/flightdeck/types.ts), typed loosely because a contract may import nothing.
2export type FlightdeckDeck = {
3  snapshot: object | null;
4  stale: boolean;
5  message: string | null;
6  tokenMode: "fresh" | "billed";
7};
8
9declare module "claude-code" {
10  interface PluginState {
11    dispatch: { flightdeck: FlightdeckDeck };
12  }
13}
14