oc-flight-deck 0.3.0 → 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
@@ -143,6 +144,18 @@ growing rows as the session produces data.
143
144
  Set `"persist": false` to restore omission: rows with no data are then left out
144
145
  entirely, which is also how a narrow rail stays shortest.
145
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
+
146
159
  ## Configuration
147
160
 
148
161
  **You don't need any.** Install it and the panel works. But every knob is
@@ -198,15 +211,17 @@ toast naming the key to fix.
198
211
 
199
212
  Flight Deck shows what OpenCode already knows.
200
213
 
201
- - **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.
202
215
  - **No telemetry.** Nothing is collected or phoned home.
203
216
  - **Nothing on disk.** The one thing it writes is an animation counter in the
204
217
  host's in-memory plugin state, so the spinner and `elapsed` keep moving
205
218
  between turns. It is scoped to this plugin and dies with the TUI; it is never
206
219
  persisted, and `"refresh": 0` removes even that.
207
- - **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
208
221
  host's own events. The timer only re-reads state the host already holds in
209
- 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.
210
225
  - **Theme-native.** Every line uses your active theme's text tokens, so it blends
211
226
  with whatever look you already run.
212
227
 
@@ -72,6 +72,8 @@
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
78
  // Every named row renders persistently, so the rail keeps a stable shape:
77
79
  // a row with no data yet shows the placeholder below, in the same label
@@ -38,7 +38,7 @@
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
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."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-flight-deck",
3
- "version": "0.3.0",
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",
@@ -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
  },
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];
@@ -154,6 +157,70 @@ function asCount(value: unknown): number | undefined {
154
157
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
155
158
  }
156
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
+
157
224
  /** `518k`, `29.2M`, `32M`, `940` — short enough for a narrow rail, precise enough to read. */
158
225
  export function formatCount(value: number): string {
159
226
  if (value < 1_000) return String(Math.round(value));
@@ -445,6 +512,10 @@ export function statLine(
445
512
  if (turns === undefined || turns === 0) return undefined;
446
513
  return row("turns", String(turns));
447
514
  }
515
+ case "guard": {
516
+ const token = guardToken(source.guard);
517
+ return token === undefined ? undefined : row("guard", token);
518
+ }
448
519
  default:
449
520
  return undefined;
450
521
  }