oc-flight-deck 0.3.0 → 0.5.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.
@@ -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
+ }