oc-flight-deck 0.2.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -59,6 +59,7 @@ learn. The panel appears beside an open session and starts reading.
59
59
  | `reasoning` | Reasoning tokens, when the model emits them. Available, off by default. |
60
60
  | `turns` | How many prompts you have sent this session. Available, off by default. |
61
61
  | `total` | The family total and subagent count on a row of its own. Adding it makes `cost` show the session figure alone. Available, off by default. |
62
+ | `guard` | Harness status from oc-harness-guard. Available, off by default. |
62
63
 
63
64
  `project` matches on the host's **project id**, not on a directory, so a worktree
64
65
  counts as part of the same project. A host that reports no project id leaves
@@ -123,6 +124,38 @@ wraps costs more than a row that says less.
123
124
  A 98% hit rate is why millions of tokens can cost cents. The moment that number
124
125
  drops, your bill doesn't.
125
126
 
127
+ ### Every selected row stays on the rail
128
+
129
+ Each field named in `sidebar.rows` renders exactly one row, in order. When the
130
+ host has nothing to show yet, the row shows the `sidebar.placeholder` value
131
+ (default `"—"`) in the same label column as a live row — so `cache` is visible
132
+ before the first cache hit, and the rail keeps a stable shape instead of
133
+ growing rows as the session produces data.
134
+
135
+ ```jsonc
136
+ {
137
+ "sidebar": {
138
+ "persist": true, // the default: stable rows with a placeholder
139
+ "placeholder": "—"
140
+ }
141
+ }
142
+ ```
143
+
144
+ Set `"persist": false` to restore omission: rows with no data are then left out
145
+ entirely, which is also how a narrow rail stays shortest.
146
+
147
+ ### guard pairs with oc-harness-guard
148
+
149
+ The guard row is opt-in: add it to sidebar.rows and the panel polls harness
150
+ status about every ten seconds, plus right away when the rendered session
151
+ changes. It shows the worst signal first, then falls back to ok when every
152
+ source reports available and quiet. A source that reports unavailable reads as
153
+ unknown, and no data renders the placeholder like any other row.
154
+
155
+ It only appears when oc-harness-guard is installed and answering. Without it
156
+ the row stays on the placeholder, and the panel never installs or requires the
157
+ other plugin. Each side works alone.
158
+
126
159
  ## Configuration
127
160
 
128
161
  **You don't need any.** Install it and the panel works. But every knob is
@@ -178,15 +211,17 @@ toast naming the key to fix.
178
211
 
179
212
  Flight Deck shows what OpenCode already knows.
180
213
 
181
- - **No network calls.** Nothing is fetched, nothing is sent.
214
+ - **No network calls while the opt-in `guard` row stays off.** Nothing is fetched, nothing is sent. When the `guard` row is enabled, the panel polls the local guard RPC (same machine, no telemetry) about every ten seconds, plus right away on session change.
182
215
  - **No telemetry.** Nothing is collected or phoned home.
183
216
  - **Nothing on disk.** The one thing it writes is an animation counter in the
184
217
  host's in-memory plugin state, so the spinner and `elapsed` keep moving
185
218
  between turns. It is scoped to this plugin and dies with the TUI; it is never
186
219
  persisted, and `"refresh": 0` removes even that.
187
- - **No polling of your session** — cost, tokens, and permissions update from the
220
+ - **No polling of your session while the opt-in `guard` row stays off** — cost, tokens, and permissions update from the
188
221
  host's own events. The timer only re-reads state the host already holds in
189
- memory, and only so the clock-derived rows keep moving.
222
+ memory, and only so the clock-derived rows keep moving. When the `guard` row
223
+ is enabled, the panel additionally polls the local guard RPC on its own
224
+ ten-second cadence.
190
225
  - **Theme-native.** Every line uses your active theme's text tokens, so it blends
191
226
  with whatever look you already run.
192
227
 
@@ -207,7 +242,9 @@ bun run check
207
242
  `bun run check` typechecks and runs the suite, including headless OpenTUI render
208
243
  tests that mount the panel in a real renderer and assert the exact characters
209
244
  that come out. A guard test parses the shipped example config and asserts it
210
- still matches the real defaults, so the documentation can't drift from the code.
245
+ still matches the real defaults, and a schema test validates that parsed
246
+ example against the shipped schema — defaults, types, and allowed values —
247
+ so the documentation can't drift from the code on either side.
211
248
 
212
249
  To load the plugin **from this checkout** while working on it, add it to the
213
250
  `opencode.jsonc` of the project you run OpenCode in. A `plugins` entry is a
@@ -230,8 +267,7 @@ Built on the official
230
267
 
231
268
  ## Compatibility
232
269
 
233
- The OpenCode plugin API is still in beta. This release targets
234
- `@opencode/plugin` beta `0.0.0-beta-19425`; pin a host version you've tested.
270
+ Built against `@opencode/plugin` `2.0.2`; pin a host version you've tested.
235
271
 
236
272
  Requires OpenCode V2 (`opencode2`). Building from source needs Bun 1.4+ or
237
273
  Node 22+.
@@ -72,10 +72,13 @@
72
72
  // spark recent turn sizes as a sparkline
73
73
  // reasoning reasoning tokens, when the model emits them
74
74
  // turns how many prompts you have sent this session
75
+ // guard harness status from oc-harness-guard: breaches, orphans,
76
+ // findings, or ok. Available, off by default.
75
77
  //
76
- // A row appears only once the host has data for it — nothing is drawn as a
77
- // placeholder. The fixed lines and the live rows together are capped at 24,
78
- // and anything past that is dropped.
78
+ // Every named row renders persistently, so the rail keeps a stable shape:
79
+ // a row with no data yet shows the placeholder below, in the same label
80
+ // column as a live row. The fixed lines and the live rows together are
81
+ // capped at 24, and anything past that is dropped.
79
82
  "rows": [
80
83
  "caution",
81
84
  "status",
@@ -90,7 +93,15 @@
90
93
  "perms",
91
94
  "elapsed",
92
95
  "tps"
93
- ]
96
+ ],
97
+
98
+ // Every named row renders persistently: with no data yet it shows the
99
+ // placeholder below, in the same label column as a live row. Set to false
100
+ // to omit rows with no data instead.
101
+ "persist": true,
102
+
103
+ // Value shown for a persistent row with no data yet. Any non-empty string.
104
+ "placeholder": "—"
94
105
  },
95
106
 
96
107
  // ── Footer ───────────────────────────────────────────────────────────────
@@ -38,10 +38,21 @@
38
38
  },
39
39
  "rows": {
40
40
  "type": "array",
41
- "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns"] },
41
+ "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "tps", "spark", "reasoning", "turns", "guard"] },
42
42
  "default": ["caution", "status", "agent", "model", "branch", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
43
43
  "maxItems": 24,
44
- "description": "Which live fields to draw, top to bottom. Any subset, any order — this is the single most useful thing to change. Rows with no data are omitted entirely, so a narrow rail grows rows as a session produces them rather than showing placeholders. Counted together with `sidebar.lines` against a 24-line cap on the whole rail."
44
+ "description": "Which live fields to draw, top to bottom. Any subset, any order — this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, using `sidebar.placeholder` until the host has data; with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail."
45
+ },
46
+ "persist": {
47
+ "type": "boolean",
48
+ "default": true,
49
+ "description": "Render every field named in `sidebar.rows` as a persistent row, using `sidebar.placeholder` when the host has no data yet. True keeps the rail a stable shape that fills in as the session produces data; false restores the old behavior of omitting rows with no data."
50
+ },
51
+ "placeholder": {
52
+ "type": "string",
53
+ "minLength": 1,
54
+ "default": "—",
55
+ "description": "Value shown for a persistent row with no data yet. Used only when `sidebar.persist` is true. Must be a non-empty string; anything else falls back to the default em dash."
45
56
  }
46
57
  }
47
58
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-flight-deck",
3
- "version": "0.2.4",
3
+ "version": "0.4.0",
4
4
  "description": "Live OpenCode V2 session telemetry — agent, model, branch, cost, tokens, cache hit rate and context usage in your sidebar.",
5
5
  "keywords": [
6
6
  "opencode",
package/src/tui/config.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  // Everything is optional. Missing or invalid values fall back to the sane
9
9
  // defaults below, so the rail always renders and a typo can never break the TUI.
10
10
 
11
- import { isStatField, STAT_FIELDS } from "./stats.js";
11
+ import { DEFAULT_PLACEHOLDER, isStatField, STAT_FIELDS } from "./stats.js";
12
12
  import type { CautionThresholds } from "./caution.js";
13
13
 
14
14
  export interface SidebarConfig {
@@ -18,6 +18,13 @@ export interface SidebarConfig {
18
18
  readonly lines: readonly string[];
19
19
  /** Live session fields to render, top to bottom. Default `DEFAULT_SIDEBAR_ROWS`. */
20
20
  readonly rows: readonly string[];
21
+ /**
22
+ * Render every named row even when the host has no data for it, using
23
+ * `placeholder` as the value. Default `true`; `false` restores omission.
24
+ */
25
+ readonly persist: boolean;
26
+ /** Value shown for a row with no data when `persist` is on. Default `"—"`. */
27
+ readonly placeholder: string;
21
28
  }
22
29
 
23
30
  export interface FooterConfig {
@@ -208,7 +215,13 @@ export const MIN_REFRESH_MS = 16;
208
215
  export const DEFAULT_FOOTER_TEXT = "Flight Deck";
209
216
 
210
217
  export const DEFAULT_CONFIG: FlightDeckConfig = {
211
- sidebar: { enabled: true, lines: DEFAULT_SIDEBAR_LINES, rows: DEFAULT_SIDEBAR_ROWS },
218
+ sidebar: {
219
+ enabled: true,
220
+ lines: DEFAULT_SIDEBAR_LINES,
221
+ rows: DEFAULT_SIDEBAR_ROWS,
222
+ persist: true,
223
+ placeholder: DEFAULT_PLACEHOLDER,
224
+ },
212
225
  footer: { enabled: false, text: DEFAULT_FOOTER_TEXT },
213
226
  caution: DEFAULT_CAUTION,
214
227
  layout: DEFAULT_LAYOUT,
@@ -324,7 +337,13 @@ function readRows(value: unknown, issues: string[]): readonly string[] {
324
337
  issues.push(`${path} must be a string; skipping it`);
325
338
  return;
326
339
  }
327
- const name = entry.trim().toLowerCase();
340
+ // Control characters are normalized before matching, like every other
341
+ // config string: `cache\n` is the `cache` row, not an unknown field.
342
+ const name = normalizeText(entry, path, issues).toLowerCase();
343
+ if (name.length === 0) {
344
+ issues.push(`${path} is empty; skipping it`);
345
+ return;
346
+ }
328
347
  if (!isStatField(name)) {
329
348
  issues.push(`${path} is not a known field (${STAT_FIELDS.join(", ")}); skipping it`);
330
349
  return;
@@ -614,6 +633,13 @@ export function resolveConfig(options: unknown): ConfigResolution {
614
633
  enabled: readBoolean(sidebar.enabled, DEFAULT_CONFIG.sidebar.enabled, "sidebar.enabled", issues),
615
634
  lines,
616
635
  rows,
636
+ persist: readBoolean(sidebar.persist, DEFAULT_CONFIG.sidebar.persist, "sidebar.persist", issues),
637
+ placeholder: readText(
638
+ sidebar.placeholder,
639
+ DEFAULT_CONFIG.sidebar.placeholder,
640
+ "sidebar.placeholder",
641
+ issues,
642
+ ),
617
643
  },
618
644
  footer: {
619
645
  enabled: readBoolean(footer.enabled, footerConfigured, "footer.enabled", issues),
@@ -0,0 +1,419 @@
1
+ // Live harness status for the Flight Deck rail, sourced from oc-harness-guard's RPC.
2
+ //
3
+ // Why the contract is mirrored rather than imported:
4
+ //
5
+ // The host installs each plugin into its own isolated tree
6
+ // (`~/.cache/opencode/npm/<pkg>@latest/<ts>/node_modules/<pkg>`) and Node/bun
7
+ // resolution only walks ancestor `node_modules`. Guard's tree is a sibling,
8
+ // never an ancestor, so `import("oc-harness-guard/rpc")` cannot resolve.
9
+ // Declaring guard as a dependency would make installing deck download guard,
10
+ // breaking the promise that installing one never forces the other. So the
11
+ // contract is defined locally (`id: "harness-guard"`, method `status`) and the
12
+ // payload is read defensively, exactly how every other source field is treated
13
+ // (`unknown` + coercion). This is sound because the wire routes on id + method
14
+ // name only and the client performs no schema validation at call time; the
15
+ // server validates against its own registered contract. Drift degrades to the
16
+ // placeholder instead of throwing.
17
+ //
18
+ // Why this publishes through `context.storage.memory`, like ./ticker.ts:
19
+ //
20
+ // The host's Solid is compiled into the `opencode2` binary while this plugin
21
+ // resolves its own `solid-js` from the npm cache. Those are two module
22
+ // instances, and Solid keeps dependency tracking in module state — so a
23
+ // plugin-local signal is invisible to the host render. `context.storage.memory`
24
+ // returns a store owned by the *host's* Solid, so writing it from a timer
25
+ // notifies the host's render, and reading it inside the slot render registers
26
+ // the dependency that makes the rail re-run.
27
+ //
28
+ // The bridge never throws. Any failure (no store, RPC unavailable, `refused`,
29
+ // malformed output) stores `null`, which the getter reads as `undefined` so
30
+ // the persist layer renders the placeholder.
31
+
32
+ /** Aggregates from guard's `status` output. Only what the row needs. */
33
+ export interface GuardAirworthiness {
34
+ readonly available: boolean;
35
+ readonly findings: number;
36
+ }
37
+
38
+ export interface GuardWarden {
39
+ readonly available: boolean;
40
+ readonly breaches: number;
41
+ readonly orphans: number;
42
+ }
43
+
44
+ export interface GuardFlightPlan {
45
+ readonly available: boolean;
46
+ }
47
+
48
+ export interface GuardStatus {
49
+ readonly airworthiness?: GuardAirworthiness;
50
+ readonly warden?: GuardWarden;
51
+ readonly flightPlan?: GuardFlightPlan;
52
+ }
53
+
54
+ /** The value kept in the host's memory store. Null means "no data". */
55
+ interface GuardStoreState {
56
+ value: GuardStatus | null;
57
+ }
58
+
59
+ /** The store the host hands back: read-only to us, reactive to the host. */
60
+ interface GuardStore {
61
+ readonly value?: unknown;
62
+ }
63
+
64
+ /** The mutation function the host hands back. */
65
+ type GuardUpdate = (mutation: (draft: GuardStoreState) => void) => void;
66
+
67
+ /** The host capabilities the bridge needs, so it stays trivially stubbable. */
68
+ export interface GuardHost {
69
+ readonly storage?: {
70
+ /**
71
+ * Typed as `unknown` on the return on purpose: this is reached across a
72
+ * beta version boundary, so the shape is checked at runtime instead of
73
+ * trusted from a type that may not match the binary.
74
+ */
75
+ memory(key: string, options: { readonly initial: GuardStoreState }): unknown;
76
+ };
77
+ /** Untyped on purpose: resolved defensively at poll time, never trusted. */
78
+ readonly client?: unknown;
79
+ }
80
+
81
+ /** Injectable RPC accessor, so tests never need a real host client. */
82
+ export interface GuardDeps {
83
+ readonly status: (input: { readonly sessionID: string }) => Promise<unknown>;
84
+ }
85
+
86
+ export interface GuardBridge {
87
+ /**
88
+ * Current status, read from the host's store.
89
+ *
90
+ * This must be read inside the slot render, while the host's reactive scope
91
+ * is active, or it will not register as a dependency and nothing will update.
92
+ * `undefined` means no data, so the persist layer renders the placeholder.
93
+ */
94
+ readonly status: GuardStatus | undefined;
95
+ /**
96
+ * Retarget the bridge at the rendered session and fetch immediately when it
97
+ * changes. Idempotent: following the same session twice does not re-fetch.
98
+ * Never throws.
99
+ */
100
+ follow(sessionID: string | undefined): void;
101
+ /** Stops the timer. Safe to call more than once. */
102
+ dispose(): void;
103
+ }
104
+
105
+ /** Namespaced so it cannot collide with another plugin's memory keys. */
106
+ export const GUARD_KEY = "flight-deck.guard";
107
+
108
+ /**
109
+ * How often the bridge re-reads guard status.
110
+ *
111
+ * A dedicated constant, deliberately not `config.refresh`: the ticker wakes
112
+ * the renderer up to ten times a second for the spinner, while a breach or
113
+ * orphan needs no such cadence. Ten seconds keeps a status indicator fresh
114
+ * without a request storm, and polling (rather than push events) avoids the
115
+ * location-bearing event envelope. Revisit push only if the platform offers a
116
+ * location-free envelope.
117
+ */
118
+ export const GUARD_POLL_MS = 10_000;
119
+
120
+ /**
121
+ * Mirrored guard contract. See the module header for why it is mirrored.
122
+ *
123
+ * The schemas are intentionally permissive: the server validates against its
124
+ * own registered contract, and the client performs no validation at call time,
125
+ * so precision here would only create a second place to drift. The payload is
126
+ * normalized defensively after the call.
127
+ */
128
+ export const GUARD_CONTRACT = {
129
+ id: "harness-guard",
130
+ methods: {
131
+ status: {
132
+ input: { type: "object", properties: { sessionID: { type: "string" } }, required: ["sessionID"] },
133
+ output: { type: "object" },
134
+ },
135
+ },
136
+ events: {},
137
+ } as const;
138
+
139
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
140
+ return typeof value === "object" && value !== null && !Array.isArray(value)
141
+ ? (value as Record<string, unknown>)
142
+ : undefined;
143
+ }
144
+
145
+ /**
146
+ * A non-negative whole count. Numbers only when finite and `>= 0`, floored;
147
+ * arrays count by length; everything else is dropped (reported as `undefined`
148
+ * so the caller can fall back). Mirrors the posture of the rest of `stats.ts`.
149
+ */
150
+ function asCount(value: unknown): number | undefined {
151
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return Math.floor(value);
152
+ if (Array.isArray(value)) return value.length;
153
+ return undefined;
154
+ }
155
+
156
+ function countOrZero(...candidates: readonly unknown[]): number {
157
+ for (const candidate of candidates) {
158
+ const count = asCount(candidate);
159
+ if (count !== undefined) return count;
160
+ }
161
+ return 0;
162
+ }
163
+
164
+ function normalizeAirworthiness(value: unknown): GuardAirworthiness | undefined {
165
+ const section = asRecord(value);
166
+ if (section === undefined) return undefined;
167
+ // Only an explicit boolean makes a section usable. A present section with a
168
+ // missing or garbage `available` is dropped rather than read as either `ok`
169
+ // or `unknown`: it is neither a signal nor a reported outage.
170
+ if (section.available !== true && section.available !== false) return undefined;
171
+ return {
172
+ available: section.available === true,
173
+ findings: countOrZero(section.findings, section.counts),
174
+ };
175
+ }
176
+
177
+ function normalizeWarden(value: unknown): GuardWarden | undefined {
178
+ const section = asRecord(value);
179
+ if (section === undefined) return undefined;
180
+ if (section.available !== true && section.available !== false) return undefined;
181
+ return {
182
+ available: section.available === true,
183
+ breaches: countOrZero(section.breaches),
184
+ orphans: countOrZero(section.orphans),
185
+ };
186
+ }
187
+
188
+ function normalizeFlightPlan(value: unknown): GuardFlightPlan | undefined {
189
+ const section = asRecord(value);
190
+ if (section === undefined) return undefined;
191
+ if (section.available !== true && section.available !== false) return undefined;
192
+ return { available: section.available === true };
193
+ }
194
+
195
+ /**
196
+ * Normalize untrusted guard output, or `undefined` when there is no usable
197
+ * data. Never throws: every field is coerced, everything else is dropped.
198
+ */
199
+ export function normalizeGuardStatus(value: unknown): GuardStatus | undefined {
200
+ try {
201
+ const top = asRecord(value);
202
+ if (top === undefined) return undefined;
203
+ const airworthiness = normalizeAirworthiness(top.airworthiness);
204
+ const warden = normalizeWarden(top.warden);
205
+ const flightPlan = normalizeFlightPlan(top.flightPlan);
206
+ if (airworthiness === undefined && warden === undefined && flightPlan === undefined) return undefined;
207
+ const status: { -readonly [K in keyof GuardStatus]: GuardStatus[K] } = {};
208
+ if (airworthiness !== undefined) status.airworthiness = airworthiness;
209
+ if (warden !== undefined) status.warden = warden;
210
+ if (flightPlan !== undefined) status.flightPlan = flightPlan;
211
+ return status;
212
+ } catch {
213
+ return undefined;
214
+ }
215
+ }
216
+
217
+ // A host whose store does not match the documented shape is treated as no store
218
+ // at all: half-opening one would throw on every poll instead of degrading.
219
+ // Validated exactly as ./ticker.ts validates its store.
220
+ function openStore(storage: NonNullable<GuardHost["storage"]>): { store: GuardStore; update: GuardUpdate } | undefined {
221
+ let opened: unknown;
222
+ try {
223
+ opened = storage.memory(GUARD_KEY, { initial: { value: null } });
224
+ } catch {
225
+ return undefined;
226
+ }
227
+
228
+ if (!Array.isArray(opened) || opened.length < 2) return undefined;
229
+ const [store, update] = opened as [unknown, unknown];
230
+ if (store === null || typeof store !== "object") return undefined;
231
+ if (typeof update !== "function") return undefined;
232
+
233
+ return { store: store as GuardStore, update: update as GuardUpdate };
234
+ }
235
+
236
+ function readStatus(store: GuardStore | undefined): GuardStatus | undefined {
237
+ try {
238
+ const value = store?.value;
239
+ if (value === null || value === undefined) return undefined;
240
+ return normalizeGuardStatus(value);
241
+ } catch {
242
+ return undefined;
243
+ }
244
+ }
245
+
246
+ function resolveStatusFn(host: GuardHost, deps: GuardDeps | undefined): GuardDeps["status"] | undefined {
247
+ if (deps !== undefined) {
248
+ try {
249
+ if (typeof deps.status === "function") return deps.status;
250
+ } catch {
251
+ return undefined;
252
+ }
253
+ return undefined;
254
+ }
255
+ try {
256
+ const client = asRecord(host.client);
257
+ const rpc = client?.rpc;
258
+ if (typeof rpc !== "function") return undefined;
259
+ // Local, justified cast: the wire routes on id + method name only and the
260
+ // client performs no schema validation at call time, so the local schemas
261
+ // only have to satisfy the generic bound, not match the server exactly.
262
+ // The payload is normalized defensively after the call, so drift degrades
263
+ // to the placeholder instead of throwing.
264
+ //
265
+ // NEVER use `.call`/`.apply` on the rpc factory itself: the real client
266
+ // attaches its raw API onto the callable (`Object.assign(makeRpc(...),
267
+ // raw.rpc)`), so the factory's `.call` is the raw `rpc.call` endpoint —
268
+ // not `Function.prototype.call`. Using it would POST
269
+ // `/api/rpc/undefined/undefined` and silently yield `undefined`. Invoke
270
+ // the factory directly; the resulting `status` is a plain function, so a
271
+ // direct call is safe there too.
272
+ const factory = rpc as (definition: typeof GUARD_CONTRACT) => { readonly status?: unknown };
273
+ const remote = factory(GUARD_CONTRACT) as { readonly status?: unknown };
274
+ const status = (remote as Record<string, unknown>).status;
275
+ if (typeof status !== "function") return undefined;
276
+ return (input) => (status as (arg: { readonly sessionID: string }) => Promise<unknown>)(input);
277
+ } catch {
278
+ return undefined;
279
+ }
280
+ }
281
+
282
+ function writeValue(opened: { store: GuardStore; update: GuardUpdate }, value: GuardStatus | null): boolean {
283
+ try {
284
+ opened.update((draft) => {
285
+ draft.value = value;
286
+ });
287
+ return true;
288
+ } catch {
289
+ return false;
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Start polling guard status into the host's memory store, or return
295
+ * `undefined` when there is no usable store.
296
+ *
297
+ * A missing RPC is not an error: the bridge still opens its store and keeps
298
+ * polling, writing `null` until guard answers. That way installing guard later
299
+ * appears within the poll interval instead of needing a restart. Only a
300
+ * missing or unusable store degrades to no bridge, exactly like the ticker.
301
+ * Nothing here ever throws into the caller or the render.
302
+ *
303
+ * Assumption: `deps` is a test-only override. Production omits it so the
304
+ * bridge resolves `status` from `host.client` on every poll (late installs
305
+ * recover); tests inject a fake `status` plus a short `intervalMs`.
306
+ */
307
+ export function startGuardBridge(
308
+ host: GuardHost | undefined,
309
+ deps?: GuardDeps | undefined,
310
+ intervalMs: number = GUARD_POLL_MS,
311
+ ): GuardBridge | undefined {
312
+ const storage = host?.storage;
313
+ if (host === undefined || storage === undefined || typeof storage.memory !== "function") return undefined;
314
+
315
+ const opened = openStore(storage);
316
+ if (opened === undefined) return undefined;
317
+
318
+ const cadence = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : GUARD_POLL_MS;
319
+ let currentSessionID: string | undefined;
320
+ let timer: ReturnType<typeof setInterval> | undefined;
321
+ // Generation invalidated on dispose and on every follow() session change, so
322
+ // a poll that outlives its session — or its bridge, after disposal or a hot
323
+ // reload where the host memory store is shared — cannot overwrite newer data.
324
+ let generation = 0;
325
+ // Monotonic request sequence so overlapping polls for the same session
326
+ // resolve in start order, not finish order: only the newest request of the
327
+ // current generation may write.
328
+ let nextSeq = 0;
329
+ let latestSeq = 0;
330
+ let disposed = false;
331
+
332
+ const stopTimer = () => {
333
+ if (timer !== undefined) clearInterval(timer);
334
+ timer = undefined;
335
+ };
336
+
337
+ const poll = async (sessionID: string | undefined): Promise<void> => {
338
+ if (disposed) return;
339
+ if (sessionID === undefined || sessionID.length === 0) return;
340
+ const myGeneration = generation;
341
+ const mySeq = ++nextSeq;
342
+ latestSeq = mySeq;
343
+ const stillCurrent = () => myGeneration === generation && mySeq === latestSeq && !disposed;
344
+ let raw: unknown;
345
+ try {
346
+ const statusFn = resolveStatusFn(host, deps);
347
+ if (statusFn === undefined) {
348
+ if (!stillCurrent()) return;
349
+ if (currentSessionID !== sessionID) return;
350
+ if (!writeValue(opened, null)) stopTimer();
351
+ return;
352
+ }
353
+ raw = await statusFn({ sessionID });
354
+ } catch {
355
+ // `refused`, unavailable, or any transport failure: no data, not an error.
356
+ // Abort check below still applies so a late session change wins.
357
+ if (!stillCurrent()) return;
358
+ if (currentSessionID !== sessionID) return;
359
+ if (!writeValue(opened, null)) stopTimer();
360
+ return;
361
+ }
362
+ // A session change, a newer request, or disposal during the await makes
363
+ // this response stale; the fresh request's own poll will overwrite, so
364
+ // drop it rather than flash it. The generation check also covers A→B→A,
365
+ // where the session ID matches again but the response is still stale.
366
+ if (!stillCurrent()) return;
367
+ if (currentSessionID !== sessionID) return;
368
+ let normalized: GuardStatus | null;
369
+ try {
370
+ normalized = normalizeGuardStatus(raw) ?? null;
371
+ } catch {
372
+ normalized = null;
373
+ }
374
+ if (!writeValue(opened, normalized)) stopTimer();
375
+ };
376
+
377
+ timer = setInterval(() => {
378
+ const sessionID = currentSessionID;
379
+ if (sessionID === undefined) return;
380
+ void poll(sessionID);
381
+ }, cadence);
382
+
383
+ return {
384
+ get status() {
385
+ return readStatus(opened.store);
386
+ },
387
+ follow(sessionID: string | undefined) {
388
+ try {
389
+ if (disposed) return;
390
+ const next = typeof sessionID === "string" && sessionID.length > 0 ? sessionID : undefined;
391
+ if (next === currentSessionID) return;
392
+ // Every session change invalidates in-flight polls, including A→B→A
393
+ // where the ID matches again but the earlier response is still stale.
394
+ generation += 1;
395
+ currentSessionID = next;
396
+ if (next === undefined) {
397
+ if (!writeValue(opened, null)) stopTimer();
398
+ return;
399
+ }
400
+ // Clear stale per-session data immediately so a switch never flashes
401
+ // the previous session's verdict while the fresh fetch is in flight.
402
+ // A failing clear stops the timer, mirroring the ticker's store-fails
403
+ // behavior; the getter then reads whatever the host still holds.
404
+ if (!writeValue(opened, null)) {
405
+ stopTimer();
406
+ return;
407
+ }
408
+ void poll(next);
409
+ } catch {
410
+ // Following a session must never break the render that reported it.
411
+ }
412
+ },
413
+ dispose() {
414
+ disposed = true;
415
+ generation += 1;
416
+ stopTimer();
417
+ },
418
+ };
419
+ }
package/src/tui/index.tsx CHANGED
@@ -5,6 +5,7 @@ import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
5
5
  import { loadConfigFile } from "./file-config.js";
6
6
  import { footerLine, liveRowOffset, sidebarLines } from "./presentation.js";
7
7
  import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
8
+ import { startGuardBridge } from "./guard.js";
8
9
  import { startTicker } from "./ticker.js";
9
10
 
10
11
  // Flight Deck is a read-only instrument panel for the OpenCode V2 CLI/TUI. It
@@ -350,6 +351,13 @@ export default Plugin.define({
350
351
  config.sidebar.rows.some((name) => (ANIMATED_FIELDS as readonly string[]).includes(name));
351
352
  const ticker = startTicker(context, animated ? config.refresh : 0);
352
353
 
354
+ // The guard row is opt-in and polls its own RPC: starting the bridge only
355
+ // when the row is on the rail means no timer and no request for a row
356
+ // nobody renders. The bridge resolves `status` from `context.client` on
357
+ // every poll, so installing guard later appears within its interval.
358
+ const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
359
+ const bridge = wantGuard ? startGuardBridge(context) : undefined;
360
+
353
361
  // Read session state inside the render so the rail stays live: cost and
354
362
  // tokens climb as the session runs, and the branch appears once VCS
355
363
  // resolves. Nothing here writes, requests, or leaves the process.
@@ -408,6 +416,7 @@ export default Plugin.define({
408
416
  spark: sparkValues(sessionID),
409
417
  elapsedMs: sessionElapsed(session),
410
418
  turns,
419
+ guard: bridge?.status,
411
420
  // Read the tick inside the render so the host registers a dependency on
412
421
  // it; that read is what makes the rail re-run on the ticker's schedule.
413
422
  frame: ticker?.frame ?? 0,
@@ -457,7 +466,12 @@ export default Plugin.define({
457
466
  // re-runs between host events, and a stall is precisely the failure
458
467
  // that produces no host events at all.
459
468
  watchedSession = sessionID;
469
+ // Keep the guard bridge on the rendered session: the follow fetches
470
+ // immediately on change, and the status read below subscribes this
471
+ // render to the bridge's host store, so polls re-run the rail.
472
+ bridge?.follow(sessionID);
460
473
  void ticker?.frame;
474
+ void bridge?.status;
461
475
 
462
476
  const source = snapshot(sessionID);
463
477
  const lines = sidebarLines(config, source);
@@ -494,6 +508,7 @@ export default Plugin.define({
494
508
  if (watchTimer !== undefined) clearInterval(watchTimer);
495
509
  watchTimer = undefined;
496
510
  ticker?.dispose();
511
+ bridge?.dispose();
497
512
  for (const release of releases) release();
498
513
  };
499
514
  },
@@ -13,12 +13,14 @@ import { statRows, type StatSource } from "./stats.js";
13
13
  * Sidebar lines to render, or an empty list when the sidebar rail is disabled.
14
14
  *
15
15
  * Configured `lines` render first (branding, separators, any fixed text), then
16
- * the live rows named by `sidebar.rows`, each included only once the host has
17
- * data for it.
16
+ * the live rows named by `sidebar.rows`. With `sidebar.persist` (the default)
17
+ * every named row renders exactly once, using `sidebar.placeholder` when the
18
+ * host has no data yet; with `persist: false` rows with no data are omitted.
18
19
  */
19
20
  export function sidebarLines(config: FlightDeckConfig, source: StatSource = {}): readonly string[] {
20
21
  if (!config.sidebar.enabled) return [];
21
- return [...config.sidebar.lines, ...statRows(config.sidebar.rows, source, config.layout)].slice(0, MAX_LINES);
22
+ const layout = { ...config.layout, persist: config.sidebar.persist, placeholder: config.sidebar.placeholder };
23
+ return [...config.sidebar.lines, ...statRows(config.sidebar.rows, source, layout)].slice(0, MAX_LINES);
22
24
  }
23
25
 
24
26
  /** Footer text to render, or `undefined` when the footer rail is disabled. */
package/src/tui/stats.ts CHANGED
@@ -60,6 +60,8 @@ export interface StatSource {
60
60
  readonly spark?: unknown;
61
61
  /** Animation frame counter, advanced by the ticker. */
62
62
  readonly frame?: unknown;
63
+ /** Harness status from oc-harness-guard's RPC, via the guard bridge. Untrusted. */
64
+ readonly guard?: unknown;
63
65
  }
64
66
 
65
67
  /** Fields a user may name in `sidebar.rows`, in the order they are documented. */
@@ -81,6 +83,7 @@ export const STAT_FIELDS = [
81
83
  "spark",
82
84
  "reasoning",
83
85
  "turns",
86
+ "guard",
84
87
  ] as const;
85
88
 
86
89
  export type StatField = (typeof STAT_FIELDS)[number];
@@ -120,8 +123,20 @@ export interface LayoutHint {
120
123
  * a property of `sidebar.rows`, not a separate setting to find.
121
124
  */
122
125
  readonly hasTotalRow?: boolean;
126
+ /**
127
+ * When true, `statRows` renders one row per named field even when the host
128
+ * has no data for it, using `placeholder` as the value. Default off when
129
+ * calling `statRows` directly; `sidebarLines` turns it on from
130
+ * `config.sidebar.persist`.
131
+ */
132
+ readonly persist?: boolean;
133
+ /** Value shown for a row with no data when `persist` is on. Default `"—"`. */
134
+ readonly placeholder?: string;
123
135
  }
124
136
 
137
+ /** Placeholder value for a persistent row with no data yet. */
138
+ export const DEFAULT_PLACEHOLDER = "—";
139
+
125
140
  const DEFAULT_LABEL_WIDTH = 10;
126
141
  const DEFAULT_BAR_WIDTH = 10;
127
142
  const DEFAULT_SPARK_WIDTH = 12;
@@ -142,6 +157,70 @@ function asCount(value: unknown): number | undefined {
142
157
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
143
158
  }
144
159
 
160
+ /**
161
+ * A guard count: a non-negative whole number, or an array counted by length.
162
+ *
163
+ * The RPC aggregates are numbers, but an array (findings, breaches) reads the
164
+ * same way — how many — so both count. Anything else is dropped to `undefined`
165
+ * so the caller can fall back to zero rather than print garbage.
166
+ */
167
+ function asGuardCount(value: unknown): number | undefined {
168
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return Math.floor(value);
169
+ if (Array.isArray(value)) return value.length;
170
+ return undefined;
171
+ }
172
+
173
+ function guardCountOrZero(...candidates: readonly unknown[]): number {
174
+ for (const candidate of candidates) {
175
+ const count = asGuardCount(candidate);
176
+ if (count !== undefined) return count;
177
+ }
178
+ return 0;
179
+ }
180
+
181
+ /**
182
+ * Short harness token for the `guard` row, or `undefined` when there is no
183
+ * usable data (the persist layer then renders the placeholder).
184
+ *
185
+ * A section counts as usable only with an explicit boolean `available`: a
186
+ * present section with a missing or garbage flag is dropped, not read as
187
+ * either `ok` or `unknown`. Any usable section reporting `available: false`
188
+ * reads as `unknown` — a failed or disabled source never renders a false `ok`.
189
+ * Otherwise the worst signal wins: breaches, then orphans, then findings.
190
+ * ASCII, short, no padding.
191
+ */
192
+ function guardToken(value: unknown): string | undefined {
193
+ try {
194
+ const top = asRecord(value);
195
+ if (top === undefined) return undefined;
196
+
197
+ const air = asRecord(top.airworthiness);
198
+ const war = asRecord(top.warden);
199
+ const plan = asRecord(top.flightPlan);
200
+
201
+ const airUsable = air !== undefined && (air.available === true || air.available === false);
202
+ const warUsable = war !== undefined && (war.available === true || war.available === false);
203
+ const planUsable = plan !== undefined && (plan.available === true || plan.available === false);
204
+ if (!airUsable && !warUsable && !planUsable) return undefined;
205
+
206
+ if ((airUsable && air.available === false) || (warUsable && war.available === false) || (planUsable && plan.available === false)) {
207
+ return "unknown";
208
+ }
209
+
210
+ const breaches = warUsable ? guardCountOrZero(war.breaches) : 0;
211
+ const orphans = warUsable ? guardCountOrZero(war.orphans) : 0;
212
+ const findings = airUsable ? guardCountOrZero(air.findings, air.counts) : 0;
213
+
214
+ // Abbreviated so a huge count cannot exceed the rail width; stays ASCII.
215
+ if (breaches > 0) return `${formatCount(breaches)} breach`;
216
+ if (orphans > 0) return `${formatCount(orphans)} orphan`;
217
+ if (findings > 0) return `${formatCount(findings)} finding`;
218
+ return "ok";
219
+ } catch {
220
+ return undefined;
221
+ }
222
+ }
223
+
145
224
  /** `518k`, `29.2M`, `32M`, `940` — short enough for a narrow rail, precise enough to read. */
146
225
  export function formatCount(value: number): string {
147
226
  if (value < 1_000) return String(Math.round(value));
@@ -215,6 +294,15 @@ function plain(value: string): string {
215
294
  return value.replace(CONTROL_CHARS, " ");
216
295
  }
217
296
 
297
+ /**
298
+ * One padded rail row: the label in its column, at least one space, then the
299
+ * flattened value. Shared by live rows and persistent placeholders so both
300
+ * keep the same column.
301
+ */
302
+ function formatRow(label: string, value: string, labelWidth: number): string {
303
+ return `${label.padEnd(labelWidth)}${label.length >= labelWidth ? " " : ""}${plain(value)}`;
304
+ }
305
+
218
306
  /**
219
307
  * Recent turn sizes as a shape.
220
308
  *
@@ -256,8 +344,7 @@ export function statLine(
256
344
  // column, so a label longer than `labelWidth` was glued straight onto its
257
345
  // value: at labelWidth 8 the `reasoning` row rendered as "reasoning153k".
258
346
  // The label is nine characters, which made this reachable from a config file.
259
- const row = (label: string, value: string): string =>
260
- `${label.padEnd(labelWidth)}${label.length >= labelWidth ? " " : ""}${plain(value)}`;
347
+ const row = (label: string, value: string): string => formatRow(label, value, labelWidth);
261
348
 
262
349
  switch (field) {
263
350
  case "caution": {
@@ -425,12 +512,22 @@ export function statLine(
425
512
  if (turns === undefined || turns === 0) return undefined;
426
513
  return row("turns", String(turns));
427
514
  }
515
+ case "guard": {
516
+ const token = guardToken(source.guard);
517
+ return token === undefined ? undefined : row("guard", token);
518
+ }
428
519
  default:
429
520
  return undefined;
430
521
  }
431
522
  }
432
523
 
433
- /** Render every named field that currently has data, in the given order. */
524
+ /** Render every named field, in the given order.
525
+ *
526
+ * By default only fields with data render; with `layout.persist` every known
527
+ * field renders exactly one row, using `layout.placeholder` (default `"—"`)
528
+ * for the value when the host has nothing to show yet. `statLine` keeps
529
+ * returning `string | undefined` — persistence lives here, not there.
530
+ */
434
531
  export function statRows(
435
532
  fields: readonly string[],
436
533
  source: StatSource,
@@ -440,10 +537,20 @@ export function statRows(
440
537
  // Passing that down means the choice lives in `sidebar.rows`, where someone
441
538
  // is already deciding what the rail shows.
442
539
  const hint: LayoutHint = { ...layout, hasTotalRow: fields.includes("total") };
540
+ const persist = hint.persist === true;
541
+ const placeholder = hint.placeholder ?? DEFAULT_PLACEHOLDER;
542
+ const labelWidth = hint.labelWidth ?? DEFAULT_LABEL_WIDTH;
443
543
  const rows: string[] = [];
444
544
  for (const field of fields) {
445
545
  const line = statLine(field, source, hint);
446
- if (line !== undefined) rows.push(line);
546
+ if (line !== undefined) {
547
+ rows.push(line);
548
+ continue;
549
+ }
550
+ // Unknown names stay skipped even when persistent: a typo must stay a
551
+ // reported-and-skipped row, not a placeholder that looks intentional.
552
+ if (!persist || !isStatField(field)) continue;
553
+ rows.push(formatRow(field, placeholder, labelWidth));
447
554
  }
448
555
  return rows;
449
556
  }