From 8b46802d39c5abeb20936e6ddb934eb05f5f44b1 Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 12:09:24 +0900 Subject: [PATCH] feat(recovery): consume ae-a8n supervision contract in recovery orchestration (#408) Read the durable ae-a8n.supervision/v1 state (supervision.json + monitor.lease.json) through a single consumer module and map it onto the existing recovery verdict vocabulary without re-owning any GUI probing, dialog pressing, or recovery policy: - a8n-transport/supervision.mjs: schema-validated reader, read-time observation-health re-evaluation (stale heartbeat -> monitor-lost), structured needs-human info (dialogs/options/reason/resume path), phase->verdict escalation (never downgrades), clean-gate, and a bounded phase wait honouring the document deadline. - recovery-orchestrator: runTimeoutRecovery reads supervision before and after the attempt and escalates (needs-human/quarantined -> quarantined, monitor-lost/unavailable/corrupt -> unknown, blocked/ recovering -> await-original); verifyHostExit gates 'clean' on trustworthy observation; CLI gains --session-root for observe / recover / verify-exit; diagnostics messages carry the supervision suffix additively. - dev-loop/devtools-cli/MCP: sessionRoot exposed on a8n sessions; evidence.supervision snapshot on every execute/verify result; UNKNOWN outcomes get a bounded --supervision-wait-ms classification window; failure diagnostics records carry record.supervision. - monitor-lost/degraded/unavailable are never folded into healthy or clean; corrupt/absent/future-version state stays unavailable. Fake/mock evidence only; real-host GUI path remains unverified. --- .../a8n-transport/supervision.mjs | 515 ++++++++++++++++++ .../a8n-transport/tests/supervision.test.mjs | 281 ++++++++++ .../dev-loop/failure-record.mjs | 16 +- .../ae-devtools-cli/dev-loop/session-open.mjs | 6 + .../ae-devtools-cli/dev-loop/supervision.mjs | 82 +++ .../dev-loop/tests/supervision.test.mjs | 138 +++++ packages/ae-devtools-cli/devtools-cli/cli.mjs | 34 ++ .../devtools-cli/diagnostics.mjs | 8 +- packages/ae-devtools-cli/mcp-server/tools.mjs | 14 +- .../recovery-orchestrator/cli.mjs | 50 +- .../recovery-orchestrator/diagnostics.mjs | 27 +- .../recovery-orchestrator/orchestrator.mjs | 67 ++- .../recovery-orchestrator/tests/run.mjs | 172 ++++++ 13 files changed, 1402 insertions(+), 8 deletions(-) create mode 100644 packages/ae-devtools-cli/a8n-transport/supervision.mjs create mode 100644 packages/ae-devtools-cli/a8n-transport/tests/supervision.test.mjs create mode 100644 packages/ae-devtools-cli/dev-loop/supervision.mjs create mode 100644 packages/ae-devtools-cli/dev-loop/tests/supervision.test.mjs diff --git a/packages/ae-devtools-cli/a8n-transport/supervision.mjs b/packages/ae-devtools-cli/a8n-transport/supervision.mjs new file mode 100644 index 00000000..30351f79 --- /dev/null +++ b/packages/ae-devtools-cli/a8n-transport/supervision.mjs @@ -0,0 +1,515 @@ +/** + * supervision.mjs — ae-a8n GUI-supervision contract consumer (Issue #408, + * Epic #407; ae-a8n specs/gui-supervision/spec.md, schema + * `ae-a8n.supervision/v1`). + * + * This module is the ONE place ae-devtools reads the durable supervision + * state ae-a8n's monitor publishes. Consumers (recovery-orchestrator, + * dev-loop, devtools-cli, MCP, VSCode) NEVER implement their own GUI + * probing, dialog pressing or recovery policy — they read this contract + * and map it onto their own verdict/surface vocabulary. + * + * Read path (spec §Durable shared state, US6): + * + * /supervision.json — the state document, atomic-published + * /monitor.lease.json — the monitor lease record + * + * `sessionDir` is the ae-a8n session root (`slice.sessionRoot` for a8n + * sessions). The published npm `@ido-bata/ae-a8n` (0.5.0) predates the + * supervision API, so this module implements the documented decode / + * health re-evaluation rules itself — the durable FILE is the contract, + * not the npm export surface. When a resolved ae-a8n build DOES export + * `supervisionReport`/`readSupervisionState`, callers may prefer it; + * `supportsSupervisionApi(mod)` reports which path is available. + * + * Honesty rules (mirroring ae-a8n state.ts): + * + * - absent / corrupt / future-version state is `unavailable`, never a + * fabricated healthy report; + * - the stored `observationHealth` is re-evaluated against the monitor + * heartbeat clock at read time — a stale heartbeat is `monitor-lost` + * regardless of what the document claims; + * - `monitor-lost` / `degraded` / `unavailable` health is NEVER folded + * into "healthy" by the verdict mapping below. + */ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +export const SUPERVISION_SCHEMA_VERSION = "ae-a8n.supervision/v1"; +export const SUPERVISION_STATE_FILE = "supervision.json"; +export const MONITOR_LEASE_FILE = "monitor.lease.json"; +export const MONITOR_LEASE_SCHEMA_VERSION = "ae-a8n.monitor-lease/v1"; +export const DEFAULT_MONITOR_TTL_MS = 30 * 1000; + +export const SUPERVISION_PHASES = Object.freeze([ + "running", + "blocked", + "recovering", + "resumed", + "needs-human", + "quarantined", +]); + +export const OBSERVATION_HEALTHS = Object.freeze(["ok", "degraded", "monitor-lost", "unavailable"]); + +const PHASES = new Set(SUPERVISION_PHASES); +const HEALTHS = new Set(OBSERVATION_HEALTHS); +const HOST_STATES = new Set([ + "none", + "process-gone", + "not-responding", + "busy-suspected", + "gui-session-lost", + "unknown", +]); +const TIERS = new Set(["auto-safe", "human-required", "report-only", "unknown"]); +const PENDING_STATES = new Set(["in-flight", "timed-out", "unknown"]); + +export function supervisionStatePath(sessionDir) { + return join(sessionDir, SUPERVISION_STATE_FILE); +} + +export function monitorLeasePath(sessionDir) { + return join(sessionDir, MONITOR_LEASE_FILE); +} + +function isRecord(v) { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +function isSupervisionWindow(v) { + return ( + isRecord(v) && + typeof v.title === "string" && + typeof v.role === "string" && + typeof v.blocking === "boolean" && + typeof v.tier === "string" && + TIERS.has(v.tier) + ); +} + +function isPendingRequest(v) { + return ( + isRecord(v) && + typeof v.id === "string" && + typeof v.method === "string" && + typeof v.since === "string" && + typeof v.state === "string" && + PENDING_STATES.has(v.state) + ); +} + +function isMonitorRecord(v) { + return ( + isRecord(v) && + typeof v.ownerId === "string" && + typeof v.pid === "number" && + typeof v.acquiredAt === "string" && + typeof v.heartbeatAt === "string" + ); +} + +function isBlockingInfo(v) { + if (v === null) return true; + return ( + isRecord(v) && + typeof v.host === "string" && + HOST_STATES.has(v.host) && + typeof v.detail === "string" && + Array.isArray(v.windows) && + v.windows.every(isSupervisionWindow) + ); +} + +/** + * Validate a parsed supervision document. Returns the doc or null — a + * document that fails validation is corrupt, never partially trusted. + * Mirrors ae-a8n `decodeSupervisionDoc` including the bounded-wait + * invariant: blocked/recovering/needs-human/quarantined MUST carry a + * deadline, so supervision waits are bounded by contract. + */ +export function decodeSupervisionDoc(value) { + if (!isRecord(value)) return null; + if (value.schemaVersion !== SUPERVISION_SCHEMA_VERSION) return null; + if (typeof value.phase !== "string" || !PHASES.has(value.phase)) return null; + if (typeof value.observationHealth !== "string" || !HEALTHS.has(value.observationHealth)) return null; + if (typeof value.enteredAt !== "string" || typeof value.updatedAt !== "string") return null; + if (value.deadline !== null && typeof value.deadline !== "string") return null; + if (value.sessionId !== null && typeof value.sessionId !== "string") return null; + if (!isBlockingInfo(value.blocking)) return null; + if (!Array.isArray(value.pendingRequests) || !value.pendingRequests.every(isPendingRequest)) return null; + if (value.monitor !== null && !isMonitorRecord(value.monitor)) return null; + if (!Array.isArray(value.evidence) || !value.evidence.every((e) => typeof e === "string")) return null; + if (!Array.isArray(value.history)) return null; + const phase = value.phase; + if ( + (phase === "blocked" || phase === "recovering" || phase === "needs-human" || phase === "quarantined") && + value.deadline === null + ) { + return null; + } + return value; +} + +/** + * Read and validate the state document. Never throws for bad content. + * @returns {{kind:"state",doc:object}|{kind:"absent"}|{kind:"corrupt",detail:string}} + */ +export function readSupervisionState(sessionDir) { + const path = supervisionStatePath(sessionDir); + let text; + try { + text = readFileSync(path, "utf-8"); + } catch (error) { + return error?.code === "ENOENT" + ? { kind: "absent" } + : { kind: "corrupt", detail: `state file exists but cannot be read: ${path}` }; + } + let parsed; + try { + parsed = JSON.parse(text); + } catch { + return { kind: "corrupt", detail: `state file is not valid JSON: ${path}` }; + } + const doc = decodeSupervisionDoc(parsed); + if (doc === null) { + return { kind: "corrupt", detail: `state file failed schema validation: ${path}` }; + } + return { kind: "state", doc }; +} + +/** + * Re-evaluate observation health at read time. The stored value is the + * monitor's last claim; the heartbeat clock is the truth. Ported from + * ae-a8n `evaluateObservationHealth` — same TTL default, same rules. + */ +export function evaluateObservationHealth(doc, now = new Date(), monitorTtlMs = DEFAULT_MONITOR_TTL_MS) { + if (doc.monitor === null) { + return { + health: doc.observationHealth === "ok" ? "unavailable" : doc.observationHealth, + detail: doc.observationHealth === "ok" ? "no monitor is recorded" : null, + }; + } + const heartbeatAt = Date.parse(doc.monitor.heartbeatAt); + if (Number.isNaN(heartbeatAt)) { + return { health: "monitor-lost", detail: "the recorded monitor heartbeat is unreadable" }; + } + if (now.getTime() - heartbeatAt > monitorTtlMs) { + return { + health: "monitor-lost", + detail: + `the monitor heartbeat is stale (last beat ${doc.monitor.heartbeatAt}, ` + + `ttl ${monitorTtlMs}ms); the target's current GUI state is unknown`, + }; + } + return { health: doc.observationHealth, detail: null }; +} + +/** + * Build the supervision report for a session directory — the same shape + * ae-a8n `supervisionReport()` returns (`ae-a8n.supervision/v1` report). + * `status:"unavailable"` is an honest answer, never an empty success. + */ +export function supervisionReport(sessionDir, options = {}) { + const now = options.now ?? new Date(); + const readAt = now.toISOString(); + const result = readSupervisionState(sessionDir); + if (result.kind === "absent") { + return { + status: "unavailable", + source: "absent", + reason: + "no supervision state exists for this session directory; " + + "either supervision never ran or the session dir is wrong", + readAt, + }; + } + if (result.kind === "corrupt") { + return { status: "unavailable", source: "corrupt", reason: result.detail, readAt }; + } + const evaluated = evaluateObservationHealth(result.doc, now, options.monitorTtlMs); + return { + status: "observed", + source: "state", + doc: result.doc, + health: evaluated.health, + healthDetail: evaluated.detail, + readAt, + }; +} + +/** + * Read the monitor lease record (`monitor.lease.json`) for evidence. + * Loose validation: the lease is informational for consumers — the + * authoritative liveness signal is the heartbeat inside the state doc. + * @returns {{kind:"lease",lease:object}|{kind:"absent"}|{kind:"corrupt",detail:string}} + */ +export function readMonitorLease(sessionDir) { + const path = monitorLeasePath(sessionDir); + if (!existsSync(path)) return { kind: "absent" }; + let parsed; + try { + parsed = JSON.parse(readFileSync(path, "utf-8")); + } catch { + return { kind: "corrupt", detail: `monitor lease file is not valid JSON: ${path}` }; + } + if (!isRecord(parsed) || parsed.schemaVersion !== MONITOR_LEASE_SCHEMA_VERSION) { + return { kind: "corrupt", detail: `monitor lease failed schema validation: ${path}` }; + } + return { kind: "lease", lease: parsed }; +} + +// ------------------------------------------------------------ assessment + +/** + * Compact, surface-safe snapshot of a supervision report for embedding + * in evidence/diagnostics payloads. Keeps the honesty axes (status, + * source, phase, health) and the structured human request; drops only + * fields consumers never act on (full history, raw evidence refs stay). + * Returns null for a null/undefined report. + */ +export function supervisionSnapshot(report) { + if (report === null || report === undefined || typeof report !== "object") return null; + if (report.status !== "observed") { + return { + status: "unavailable", + source: report.source ?? null, + reason: typeof report.reason === "string" ? report.reason : null, + readAt: report.readAt ?? null, + }; + } + const doc = report.doc; + return { + status: "observed", + source: report.source ?? "state", + schemaVersion: doc.schemaVersion ?? SUPERVISION_SCHEMA_VERSION, + phase: doc.phase ?? null, + health: report.health ?? doc.observationHealth ?? null, + healthDetail: report.healthDetail ?? null, + blocking: doc.blocking ?? null, + pendingRequests: Array.isArray(doc.pendingRequests) ? doc.pendingRequests : [], + deadline: doc.deadline ?? null, + enteredAt: doc.enteredAt ?? null, + updatedAt: doc.updatedAt ?? null, + monitor: doc.monitor ?? null, + needsHuman: needsHumanInfo(report), + readAt: report.readAt ?? null, + }; +} + +/** + * Structured human-escalation payload (spec US4): what is blocking, why + * automation stopped, the choices the human has, and how to resume. + * Returns null unless the phase actually requires a human + * (`needs-human` or `quarantined`). + * + * `options` lists the button labels the blocking windows expose — they + * are the measured choices a human may take, not automation permissions. + * `requiredAction` and `resumePath` are guidance text; consumers must + * surface them verbatim rather than re-deriving policy. + */ +export function needsHumanInfo(report) { + if (report === null || report === undefined || report.status !== "observed") return null; + const doc = report.doc; + if (doc.phase !== "needs-human" && doc.phase !== "quarantined") return null; + const blocking = doc.blocking ?? null; + const windows = (blocking?.windows ?? []).filter((w) => w.blocking === true); + const dialogs = windows.map((w) => ({ + title: w.title ?? "", + role: w.role ?? "", + subrole: w.subrole ?? null, + tier: w.tier ?? "unknown", + dialogClass: w.dialogClass ?? null, + code: w.code ?? null, + buttons: Array.isArray(w.buttons) ? [...w.buttons] : [], + texts: Array.isArray(w.texts) ? [...w.texts] : [], + })); + const options = [...new Set(dialogs.flatMap((d) => d.buttons))]; + const what = + dialogs.length > 0 + ? dialogs.map((d) => (d.title !== "" ? d.title : `${d.role}${d.dialogClass ? ` (${d.dialogClass})` : ""}`)).join(", ") + : (blocking?.detail ?? `supervision phase '${doc.phase}'`); + return { + phase: doc.phase, + reason: blocking?.detail ?? `After Effects supervision is '${doc.phase}'`, + host: blocking?.host ?? null, + dialogs, + options, + requiredAction: + doc.phase === "quarantined" + ? "Inspect the After Effects window and resolve the blocking state manually; automation will not press unmeasured dialogs." + : "A human decision is required in the After Effects window; automation is paused, not failed.", + resumePath: + "Resolve the dialog/state in After Effects, then re-read supervision status " + + "(ae-devtools supervision status / ae-a8n supervise status) — the session resumes when the monitor observes recovery.", + deadline: doc.deadline ?? null, + enteredAt: doc.enteredAt ?? null, + evidence: Array.isArray(doc.evidence) ? [...doc.evidence] : [], + readAt: report.readAt ?? null, + }; +} + +// ------------------------------------------------------------ verdict mapping + +/** + * Supervision health/phase → recovery-orchestrator verdict escalation + * (Issue #408). Returns one of: + * + * "unknown" — observation cannot be trusted (corrupt state, + * monitor-lost, unavailable health). NEVER clean. + * "quarantined" — phase quarantined or needs-human: a structured + * stop; a human must act. needsHumanInfo() carries + * the dialog/reason/options/resume detail. + * "await-original" — phase blocked/recovering: the affected request + * may still complete; wait within the phase + * deadline, never resend. + * null — no escalation (running/resumed with ok/degraded + * health, or no supervision state at all — "absent" + * is honest non-applicability, not a verdict). + * + * `degraded` health deliberately does NOT escalate: the monitor still + * reports, so the phase is evidence — but it is recorded on the + * snapshot and must never be read as "healthy" by callers. + */ +export function supervisionEscalation(report) { + if (report === null || report === undefined || typeof report !== "object") return null; + if (report.status !== "observed") { + // Corrupt state cannot be classified — unknown, never clean. + // "absent" means supervision never ran for this session dir: honest + // non-applicability, not a failure and not a healthy claim. + return report.source === "corrupt" ? "unknown" : null; + } + const health = report.health ?? report.doc?.observationHealth ?? null; + if (health === "monitor-lost" || health === "unavailable") return "unknown"; + const phase = report.doc?.phase ?? null; + if (phase === "quarantined" || phase === "needs-human") return "quarantined"; + if (phase === "blocked" || phase === "recovering") return "await-original"; + return null; +} + +/** + * Whether a supervision report forbids a "clean" verdict: observation + * health is not ok, or the phase still records an unresolved blocking + * state. Used by verify-exit style acceptance where "clean" asserts the + * GUI is provably unobstructed. + */ +export function supervisionBlocksClean(report) { + if (report === null || report === undefined || report.status !== "observed") { + // Absent supervision cannot disprove cleanliness either way — the + // caller's other evidence channels decide. Corrupt state, however, + // means the GUI state is unclassifiable: not clean. + return report?.source === "corrupt"; + } + const health = report.health ?? report.doc?.observationHealth ?? null; + if (health !== "ok") return true; + const phase = report.doc?.phase ?? null; + return phase !== "running" && phase !== "resumed"; +} + +/** + * Pick the stricter of an existing verdict and a supervision escalation. + * Ordering (most severe first): unknown > quarantined > refused > + * residue > await-original > clean/crash-*. Supervision can only ever + * escalate — it never downgrades a verdict the recovery path earned. + */ +const VERDICT_SEVERITY = { + unknown: 60, + quarantined: 50, + "crash-suspect": 45, + "crash-verified": 40, + "crash-unconfirmed": 35, + residue: 30, + refused: 20, + "await-original": 10, + clean: 0, +}; + +export function stricterVerdict(base, escalation) { + if (escalation === null || escalation === undefined) return base; + const a = VERDICT_SEVERITY[base] ?? 0; + const b = VERDICT_SEVERITY[escalation] ?? 0; + return b > a ? escalation : base; +} + +// ------------------------------------------------------------ session wiring + +/** + * The session directory a devtools session's supervision state lives + * in. `slice` is the raw openSliceSession/openAttachedSliceSession + * result (a8n-transport/session-open.mjs keeps it internal); the + * stripped session may also carry `sessionRoot` directly. + */ +export function sessionDirFor(session) { + const root = session?.slice?.sessionRoot ?? session?.sessionRoot ?? null; + return typeof root === "string" && root.length > 0 ? root : null; +} + +/** + * Read the supervision report for an open dev-loop session. Returns + * null when the session has no ae-a8n session root (fake sessions) — + * callers treat null as "supervision not applicable", which is honest: + * a fake host has no GUI to supervise. + * + * Read-only by construction: this only reads files ae-a8n's monitor + * published. It never starts a monitor, never takes a lease, never + * touches After Effects — safe for attached sessions (Issue #410). + */ +export function supervisionForSession(session, options = {}) { + const dir = sessionDirFor(session); + if (dir === null) return null; + return supervisionReport(dir, options); +} + +/** + * Whether a resolved ae-a8n module exports the supervision API + * (`supervisionReport` et al., ae-a8n #287). Informational only — the + * durable-file reader above works regardless; this tells consumers + * which read path a given ae-a8n build offers. + */ +export function supportsSupervisionApi(mod) { + return ( + mod !== null && + typeof mod === "object" && + typeof mod.supervisionReport === "function" + ); +} + +/** + * Bounded wait for a supervision phase transition (Issue #408: + * "eliminate indefinite waits"). Polls the durable state file — never + * AE — until `phases` includes the current phase, `timeoutMs` elapses, + * or the document's own phase `deadline` passes, whichever is first. + * The wait is ALWAYS bounded: a missing deadline does not extend it. + * + * @returns {Promise<{timedOut:boolean, deadlineExceeded:boolean, report:object}>} + */ +export async function waitForSupervisionPhase(sessionDir, { + phases = null, + timeoutMs = 10_000, + intervalMs = 250, + now = () => new Date(), + sleep = (ms) => new Promise((r) => setTimeout(r, ms)), +} = {}) { + const started = now().getTime(); + const cap = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10_000; + const poll = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : 250; + const wanted = Array.isArray(phases) ? new Set(phases) : null; + let last = supervisionReport(sessionDir, { now: now() }); + for (;;) { + const phase = last.status === "observed" ? last.doc.phase : null; + if (wanted === null || (phase !== null && wanted.has(phase))) { + return { timedOut: false, deadlineExceeded: false, report: last }; + } + const elapsed = now().getTime() - started; + // The phase deadline bounds the wait even when timeoutMs is larger. + const docDeadline = last.status === "observed" && typeof last.doc.deadline === "string" + ? Date.parse(last.doc.deadline) + : null; + const deadlineExceeded = docDeadline !== null && !Number.isNaN(docDeadline) && now().getTime() >= docDeadline; + if (elapsed >= cap || deadlineExceeded) { + return { timedOut: elapsed >= cap && !deadlineExceeded, deadlineExceeded, report: last }; + } + await sleep(Math.min(poll, cap - elapsed)); + last = supervisionReport(sessionDir, { now: now() }); + } +} diff --git a/packages/ae-devtools-cli/a8n-transport/tests/supervision.test.mjs b/packages/ae-devtools-cli/a8n-transport/tests/supervision.test.mjs new file mode 100644 index 00000000..d51b8e8f --- /dev/null +++ b/packages/ae-devtools-cli/a8n-transport/tests/supervision.test.mjs @@ -0,0 +1,281 @@ +/** + * supervision.test.mjs — ae-a8n supervision contract consumer tests + * (Issue #408). Fake level only: durable state files are written into + * temp dirs; no After Effects, no monitor, no GUI is involved. + */ +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; + +import { + SUPERVISION_SCHEMA_VERSION, + SUPERVISION_STATE_FILE, + decodeSupervisionDoc, + evaluateObservationHealth, + needsHumanInfo, + readMonitorLease, + readSupervisionState, + supervisionBlocksClean, + supervisionEscalation, + supervisionReport, + supervisionSnapshot, + stricterVerdict, + supervisionStatePath, + waitForSupervisionPhase, +} from "../supervision.mjs"; + +function tmp() { + return mkdtempSync(join(tmpdir(), "ae-sup-")); +} + +const NOW = new Date("2026-11-20T12:00:00.000Z"); + +function doc(overrides = {}) { + return { + schemaVersion: SUPERVISION_SCHEMA_VERSION, + sessionId: "sess-1", + phase: "running", + observationHealth: "ok", + blocking: null, + pendingRequests: [], + enteredAt: "2026-11-20T11:59:00.000Z", + deadline: null, + evidence: [], + monitor: { + ownerId: "mon-1", + pid: 1234, + pidStart: null, + acquiredAt: "2026-11-20T11:58:00.000Z", + heartbeatAt: "2026-11-20T11:59:59.000Z", + }, + history: [], + updatedAt: "2026-11-20T11:59:59.000Z", + ...overrides, + }; +} + +function writeState(dir, value) { + writeFileSync(supervisionStatePath(dir), typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`); +} + +// ------------------------------------------------------------ decode + +test("decodeSupervisionDoc accepts a valid running doc", () => { + assert.equal(decodeSupervisionDoc(doc()) !== null, true); +}); + +test("decodeSupervisionDoc rejects wrong schema version (future/corrupt)", () => { + assert.equal(decodeSupervisionDoc(doc({ schemaVersion: "ae-a8n.supervision/v2" })), null); + assert.equal(decodeSupervisionDoc(doc({ schemaVersion: "other/v9" })), null); +}); + +test("decodeSupervisionDoc enforces the bounded-wait invariant", () => { + // Non-running phases MUST carry a deadline — a doc without one is corrupt. + assert.equal(decodeSupervisionDoc(doc({ phase: "blocked", deadline: null })), null); + assert.equal( + decodeSupervisionDoc(doc({ phase: "needs-human", deadline: "2026-11-20T12:05:00.000Z" })) !== null, + true, + ); +}); + +test("decodeSupervisionDoc rejects malformed windows/pending/monitor", () => { + assert.equal(decodeSupervisionDoc(doc({ blocking: { host: "bogus", detail: "x", windows: [] } })), null); + assert.equal(decodeSupervisionDoc(doc({ pendingRequests: [{ id: 1 }] })), null); + assert.equal(decodeSupervisionDoc(doc({ monitor: { ownerId: "x" } })), null); +}); + +// ------------------------------------------------------------ read/report + +test("readSupervisionState: absent vs corrupt vs state", () => { + const dir = tmp(); + assert.deepEqual(readSupervisionState(dir), { kind: "absent" }); + writeState(dir, "{not json"); + assert.equal(readSupervisionState(dir).kind, "corrupt"); + writeState(dir, doc()); + assert.equal(readSupervisionState(dir).kind, "state"); +}); + +test("supervisionReport: absent is unavailable, never healthy", () => { + const r = supervisionReport(tmp(), { now: NOW }); + assert.equal(r.status, "unavailable"); + assert.equal(r.source, "absent"); +}); + +test("supervisionReport: corrupt is unavailable", () => { + const dir = tmp(); + writeState(dir, "garbage"); + const r = supervisionReport(dir, { now: NOW }); + assert.equal(r.status, "unavailable"); + assert.equal(r.source, "corrupt"); +}); + +test("evaluateObservationHealth: stale heartbeat is monitor-lost even when doc claims ok", () => { + const d = doc({ + monitor: { ownerId: "m", pid: 1, pidStart: null, acquiredAt: "x", heartbeatAt: "2026-11-20T11:00:00.000Z" }, + }); + const r = evaluateObservationHealth(d, NOW, 30_000); + assert.equal(r.health, "monitor-lost"); +}); + +test("evaluateObservationHealth: no monitor recorded downgrades stored ok to unavailable", () => { + const r = evaluateObservationHealth(doc({ monitor: null }), NOW); + assert.equal(r.health, "unavailable"); +}); + +test("evaluateObservationHealth: fresh heartbeat preserves stored degraded", () => { + const d = doc({ observationHealth: "degraded" }); + const r = evaluateObservationHealth(d, NOW, 30_000); + assert.equal(r.health, "degraded"); +}); + +test("readMonitorLease: absent/corrupt/lease", () => { + const dir = tmp(); + assert.equal(readMonitorLease(dir).kind, "absent"); + writeFileSync(join(dir, "monitor.lease.json"), "{}"); + assert.equal(readMonitorLease(dir).kind, "corrupt"); + writeFileSync( + join(dir, "monitor.lease.json"), + JSON.stringify({ schemaVersion: "ae-a8n.monitor-lease/v1", ownerId: "m", pid: 1, acquiredAt: "x", heartbeatAt: "y" }), + ); + assert.equal(readMonitorLease(dir).kind, "lease"); +}); + +// ------------------------------------------------------------ snapshot + needs-human + +test("supervisionSnapshot carries phase/health/needsHuman and stays honest on unavailable", () => { + const dir = tmp(); + const absent = supervisionReport(dir, { now: NOW }); + const snap = supervisionSnapshot(absent); + assert.equal(snap.status, "unavailable"); + assert.equal(snap.needsHuman ?? null, null); + + writeState(dir, doc({ + phase: "needs-human", + deadline: "2026-11-20T12:10:00.000Z", + blocking: { + host: "none", + detail: "sign-in dialog is up", + windows: [{ + title: "Sign In", role: "AXDialog", subrole: null, blocking: true, + tier: "human-required", dialogClass: "sign-in", code: "A8N-AUTH-001", + texts: ["Please sign in"], buttons: ["Cancel", "Sign In"], + }], + }, + })); + const report = supervisionReport(dir, { now: NOW }); + const s2 = supervisionSnapshot(report); + assert.equal(s2.phase, "needs-human"); + assert.equal(s2.health, "ok"); + assert.equal(s2.needsHuman.phase, "needs-human"); + assert.deepEqual(s2.needsHuman.options.sort(), ["Cancel", "Sign In"]); + assert.match(s2.needsHuman.resumePath, /supervision status/); +}); + +test("needsHumanInfo is null for non-human phases", () => { + const dir = tmp(); + writeState(dir, doc({ phase: "blocked", deadline: "2026-11-20T12:05:00.000Z" })); + assert.equal(needsHumanInfo(supervisionReport(dir, { now: NOW })), null); +}); + +// ------------------------------------------------------------ verdict mapping + +test("supervisionEscalation: corrupt → unknown, absent → null", () => { + const dir = tmp(); + assert.equal(supervisionEscalation(supervisionReport(dir, { now: NOW })), null); + writeState(dir, "junk"); + assert.equal(supervisionEscalation(supervisionReport(dir, { now: NOW })), "unknown"); +}); + +test("supervisionEscalation: monitor-lost/unavailable health → unknown regardless of phase", () => { + const dir = tmp(); + writeState(dir, doc({ + phase: "running", + monitor: { ownerId: "m", pid: 1, pidStart: null, acquiredAt: "x", heartbeatAt: "2026-11-20T10:00:00.000Z" }, + })); + assert.equal(supervisionEscalation(supervisionReport(dir, { now: NOW })), "unknown"); +}); + +test("supervisionEscalation: phase mapping", () => { + const cases = [ + ["quarantined", "quarantined"], + ["needs-human", "quarantined"], + ["blocked", "await-original"], + ["recovering", "await-original"], + ["running", null], + ["resumed", null], + ]; + for (const [phase, expected] of cases) { + const dir = tmp(); + writeState(dir, doc({ + phase, + deadline: phase === "running" || phase === "resumed" ? null : "2026-11-20T12:05:00.000Z", + })); + assert.equal(supervisionEscalation(supervisionReport(dir, { now: NOW })), expected, phase); + } +}); + +test("supervisionEscalation: degraded health does not escalate but is not clean", () => { + const dir = tmp(); + writeState(dir, doc({ observationHealth: "degraded" })); + const report = supervisionReport(dir, { now: NOW }); + assert.equal(report.health, "degraded"); + assert.equal(supervisionEscalation(report), null); + assert.equal(supervisionBlocksClean(report), true); +}); + +test("supervisionBlocksClean: ok+running passes; ok+blocked fails", () => { + const dir = tmp(); + writeState(dir, doc()); + assert.equal(supervisionBlocksClean(supervisionReport(dir, { now: NOW })), false); + writeState(dir, doc({ phase: "blocked", deadline: "2026-11-20T12:05:00.000Z" })); + assert.equal(supervisionBlocksClean(supervisionReport(dir, { now: NOW })), true); +}); + +test("stricterVerdict only escalates", () => { + assert.equal(stricterVerdict("await-original", "quarantined"), "quarantined"); + assert.equal(stricterVerdict("quarantined", "await-original"), "quarantined"); + assert.equal(stricterVerdict("clean", "unknown"), "unknown"); + assert.equal(stricterVerdict("unknown", null), "unknown"); + assert.equal(stricterVerdict("await-original", null), "await-original"); +}); + +// ------------------------------------------------------------ bounded wait + +test("waitForSupervisionPhase returns immediately on matching phase", async () => { + const dir = tmp(); + writeState(dir, doc({ phase: "blocked", deadline: "2026-11-20T12:05:00.000Z" })); + const r = await waitForSupervisionPhase(dir, { + phases: ["blocked"], timeoutMs: 50, now: () => NOW, + }); + assert.equal(r.timedOut, false); + assert.equal(r.report.doc.phase, "blocked"); +}); + +test("waitForSupervisionPhase real-clock bound: times out on running phase", async () => { + const dir = tmp(); + writeState(dir, doc()); + const started = Date.now(); + const r = await waitForSupervisionPhase(dir, { + phases: ["blocked"], timeoutMs: 120, intervalMs: 30, + }); + assert.equal(r.timedOut, true); + assert.ok(Date.now() - started < 2_000, "wait stayed bounded"); +}); + +test("waitForSupervisionPhase honours the phase deadline over a larger timeout", async () => { + const dir = tmp(); + // deadline already in the past relative to real now + writeState(dir, doc({ + phase: "needs-human", + deadline: new Date(Date.now() - 1_000).toISOString(), + blocking: { host: "none", detail: "x", windows: [] }, + })); + // phases excludes needs-human → must wait, but deadline already passed → deadlineExceeded + const r = await waitForSupervisionPhase(dir, { + phases: ["resumed"], timeoutMs: 60_000, intervalMs: 50, + }); + assert.equal(r.deadlineExceeded, true); + assert.equal(r.timedOut, false); +}); diff --git a/packages/ae-devtools-cli/dev-loop/failure-record.mjs b/packages/ae-devtools-cli/dev-loop/failure-record.mjs index f3cdb065..15f076ad 100644 --- a/packages/ae-devtools-cli/dev-loop/failure-record.mjs +++ b/packages/ae-devtools-cli/dev-loop/failure-record.mjs @@ -50,12 +50,17 @@ function pinSession(pin) { * session — { kind, pin? } session descriptor; kind drives the * evidence label, pin feeds the record's session block * requestId — dispatch request id when the caller has one + * supervision— optional ae-a8n supervision snapshot + * (dev-loop/supervision.mjs supervisionSnapshotForSession, + * Issue #408): attached verbatim as record.supervision so + * every surface reports the same phase/health/needs-human + * state. Additive — absent supervision changes nothing. * collectors — { fromAeError, fromTransportOutcome } from * diagnostics/collectors.mjs (injected, see header) * @returns {object|null} canonical diagnostics record, or null when * the result is not failure-shaped */ -export function recordFromExecuteResult({ result, outcome, session, requestId, collectors } = {}) { +export function recordFromExecuteResult({ result, outcome, session, requestId, supervision, collectors } = {}) { const state = failureOutcome(result, outcome); if (state === null) return null; if ( @@ -103,6 +108,15 @@ export function recordFromExecuteResult({ result, outcome, session, requestId, c ); } + // Additive supervision snapshot (Issue #408): the durable + // ae-a8n.supervision/v1 state observed for this session — phase, + // observation health and the structured needs-human request. The + // diagnostics schema allows forward-compatible fields; consumers + // that predate supervision simply ignore it. + if (supervision !== null && supervision !== undefined && typeof supervision === "object") { + record.supervision = supervision; + } + // Evidence label honesty: "fake" only for fake sessions; "real-host" // only when the failure was actually observed through the host / // transport on an owned AE session (a wire outcome or a host error diff --git a/packages/ae-devtools-cli/dev-loop/session-open.mjs b/packages/ae-devtools-cli/dev-loop/session-open.mjs index ea2030dc..4facc264 100644 --- a/packages/ae-devtools-cli/dev-loop/session-open.mjs +++ b/packages/ae-devtools-cli/dev-loop/session-open.mjs @@ -86,6 +86,10 @@ export async function openSession(kind = "fake", options = {}) { runner: s.runner, pin: s.pin, close: () => s.close(), + // ae-a8n session root — the directory the durable supervision + // contract (supervision.json) lives in. Read-only consumers use + // it; it grants no mutation authority (Issue #408/#410). + sessionRoot: typeof s.sessionRoot === "string" ? s.sessionRoot : null, meta: { aeVersion: s.info?.version ?? null, ownership: s.ownership?.kind ?? null, @@ -136,6 +140,8 @@ export async function openSession(kind = "fake", options = {}) { runner: s.runner, pin: s.pin, close: () => s.close(), + // ae-a8n session root — see a8n-attached above (Issue #408). + sessionRoot: typeof s.sessionRoot === "string" ? s.sessionRoot : null, meta: { aeVersion: s.info?.version ?? null, ownership: s.ownership?.kind ?? null, diff --git a/packages/ae-devtools-cli/dev-loop/supervision.mjs b/packages/ae-devtools-cli/dev-loop/supervision.mjs new file mode 100644 index 00000000..e5463a53 --- /dev/null +++ b/packages/ae-devtools-cli/dev-loop/supervision.mjs @@ -0,0 +1,82 @@ +/** + * supervision.mjs — dev-loop supervision snapshot helpers (Issue #408, + * Epic #407). + * + * dev-loop surfaces (CLI, MCP, VSCode) never implement GUI probing, + * dialog pressing or recovery policy. They consume the ae-a8n durable + * supervision contract through a8n-transport/supervision.mjs and attach + * an honest snapshot to evidence/diagnostics payloads: + * + * - the snapshot records phase + observation health + the structured + * needs-human request (dialog, reason, options, resume path); + * - monitor-lost/degraded/unavailable health is recorded verbatim — + * never folded into "healthy"; + * - waits on supervision are ALWAYS bounded (waitForSupervisionPhase + * honours both the caller's timeout and the phase's own deadline); + * - attached sessions get the same read-only view — this module only + * reads files, it never takes a lease or mutates the host. + */ +import { + supervisionForSession, + supervisionSnapshot, + supervisionStatePath, + waitForSupervisionPhase, +} from "../a8n-transport/supervision.mjs"; + +export { + supervisionForSession, + supervisionSnapshot, + supervisionStatePath, + waitForSupervisionPhase, +}; + +/** Phases that mean "supervision has something to report". */ +export const BLOCKING_SUPERVISION_PHASES = Object.freeze([ + "blocked", + "recovering", + "needs-human", + "quarantined", +]); + +/** + * Read the supervision report for an open dev-loop session and return + * the compact snapshot used in evidence/diagnostics payloads. Returns + * null for sessions without an ae-a8n session root (fake) — honest + * non-applicability, not a fabricated state. + */ +export function supervisionSnapshotForSession(session, options = {}) { + const report = supervisionForSession(session, options); + return report === null ? null : supervisionSnapshot(report); +} + +/** + * Bounded wait for supervision to classify a blocking state after a + * dispatch ended UNKNOWN (the modal-dialog case supervision exists + * for). Polls the durable state file only — never AE — until the phase + * reaches one of `phases`, `timeoutMs` elapses, or the document's own + * phase deadline passes, whichever comes first. There is no unbounded + * wait path: a phase without a deadline simply cannot extend the wait. + * + * @returns {Promise<{timedOut:boolean, deadlineExceeded:boolean, + * snapshot:object|null}>} + */ +export async function awaitSupervisionClassification(session, { + timeoutMs = 5_000, + intervalMs = 250, + phases = BLOCKING_SUPERVISION_PHASES, +} = {}) { + const root = session?.slice?.sessionRoot ?? session?.sessionRoot ?? null; + if (typeof root !== "string" || root.length === 0) { + return { timedOut: false, deadlineExceeded: false, snapshot: null }; + } + const outcome = await waitForSupervisionPhase(root, { + phases, + timeoutMs, + intervalMs, + }); + return { + timedOut: outcome.timedOut, + deadlineExceeded: outcome.deadlineExceeded, + snapshot: supervisionSnapshot(outcome.report), + }; +} diff --git a/packages/ae-devtools-cli/dev-loop/tests/supervision.test.mjs b/packages/ae-devtools-cli/dev-loop/tests/supervision.test.mjs new file mode 100644 index 00000000..3ccb60e5 --- /dev/null +++ b/packages/ae-devtools-cli/dev-loop/tests/supervision.test.mjs @@ -0,0 +1,138 @@ +/** + * supervision.test.mjs — dev-loop supervision snapshot tests + * (Issue #408). Fake level only: durable ae-a8n.supervision/v1 files in + * temp dirs; no AE, no monitor, no GUI. + */ +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; + +import { + supervisionSnapshotForSession, + awaitSupervisionClassification, +} from "../supervision.mjs"; +import { supervisionStatePath } from "../../a8n-transport/supervision.mjs"; +import { recordFromExecuteResult } from "../failure-record.mjs"; + +function tmp() { + return mkdtempSync(join(tmpdir(), "ae-dl-sup-")); +} + +function writeDoc(dir, overrides = {}) { + const doc = { + schemaVersion: "ae-a8n.supervision/v1", + sessionId: "s1", + phase: "running", + observationHealth: "ok", + blocking: null, + pendingRequests: [], + enteredAt: new Date().toISOString(), + deadline: null, + evidence: [], + monitor: { + ownerId: "m", pid: 1, pidStart: null, + acquiredAt: new Date().toISOString(), heartbeatAt: new Date().toISOString(), + }, + history: [], + updatedAt: new Date().toISOString(), + ...overrides, + }; + writeFileSync(supervisionStatePath(dir), `${JSON.stringify(doc, null, 2)}\n`); + return doc; +} + +test("supervisionSnapshotForSession: null for sessions without an ae-a8n root", () => { + assert.equal(supervisionSnapshotForSession({ kind: "fake" }), null); + assert.equal(supervisionSnapshotForSession(null), null); +}); + +test("supervisionSnapshotForSession reads sessionRoot and slice.sessionRoot", () => { + const dir = tmp(); + writeDoc(dir); + const snap = supervisionSnapshotForSession({ kind: "a8n", sessionRoot: dir }); + assert.equal(snap.status, "observed"); + assert.equal(snap.phase, "running"); + assert.equal(snap.health, "ok"); + const snap2 = supervisionSnapshotForSession({ kind: "a8n-attached", slice: { sessionRoot: dir } }); + assert.equal(snap2.phase, "running"); +}); + +test("supervisionSnapshotForSession: absent state is unavailable, corrupt is unavailable — never healthy", () => { + const absent = supervisionSnapshotForSession({ sessionRoot: tmp() }); + assert.equal(absent.status, "unavailable"); + assert.equal(absent.source, "absent"); + const dir = tmp(); + writeFileSync(supervisionStatePath(dir), "not json"); + const corrupt = supervisionSnapshotForSession({ sessionRoot: dir }); + assert.equal(corrupt.status, "unavailable"); + assert.equal(corrupt.source, "corrupt"); +}); + +test("awaitSupervisionClassification: bounded wait returns blocking phase or times out", async () => { + const dir = tmp(); + writeDoc(dir, { + phase: "blocked", + deadline: new Date(Date.now() + 60_000).toISOString(), + blocking: { host: "busy-suspected", detail: "AE busy", windows: [] }, + }); + const hit = await awaitSupervisionClassification({ sessionRoot: dir }, { timeoutMs: 2_000 }); + assert.equal(hit.timedOut, false); + assert.equal(hit.snapshot.phase, "blocked"); + + // running phase never classifies → bounded timeout, not a hang + const dir2 = tmp(); + writeDoc(dir2); + const started = Date.now(); + const miss = await awaitSupervisionClassification({ sessionRoot: dir2 }, { timeoutMs: 150, intervalMs: 30 }); + assert.equal(miss.timedOut, true); + assert.ok(Date.now() - started < 2_000); +}); + +test("awaitSupervisionClassification: no session root returns immediately", async () => { + const r = await awaitSupervisionClassification({ kind: "fake" }, { timeoutMs: 60_000 }); + assert.equal(r.snapshot, null); + assert.equal(r.timedOut, false); +}); + +test("recordFromExecuteResult attaches supervision snapshot additively", () => { + const dir = tmp(); + writeDoc(dir, { + phase: "needs-human", + deadline: new Date(Date.now() + 60_000).toISOString(), + blocking: { + host: "none", detail: "license expired", + windows: [{ + title: "License", role: "AXWindow", subrole: "AXDialog", blocking: true, + tier: "human-required", dialogClass: "license", code: "X", + texts: [], buttons: ["OK"], + }], + }, + }); + const supervision = supervisionSnapshotForSession({ sessionRoot: dir }); + const record = recordFromExecuteResult({ + result: { status: "FAILED", error: { code: "E_TIMEOUT", message: "timed out" } }, + outcome: "FAILED", + session: { kind: "a8n-attached", pin: null }, + supervision, + collectors: { + fromAeError: () => ({ kind: "transport-outcome", severity: "error" }), + fromTransportOutcome: () => ({ kind: "transport-outcome", severity: "error" }), + }, + }); + assert.ok(record !== null); + assert.equal(record.supervision.phase, "needs-human"); + assert.equal(record.supervision.needsHuman.reason, "license expired"); + // Without supervision the record shape is unchanged. + const plain = recordFromExecuteResult({ + result: { status: "FAILED", error: { code: "E_TIMEOUT", message: "timed out" } }, + outcome: "FAILED", + session: { kind: "a8n-attached", pin: null }, + collectors: { + fromAeError: () => ({ kind: "transport-outcome", severity: "error" }), + fromTransportOutcome: () => ({ kind: "transport-outcome", severity: "error" }), + }, + }); + assert.equal("supervision" in plain, false); +}); diff --git a/packages/ae-devtools-cli/devtools-cli/cli.mjs b/packages/ae-devtools-cli/devtools-cli/cli.mjs index ae44ddc2..3bc89f47 100644 --- a/packages/ae-devtools-cli/devtools-cli/cli.mjs +++ b/packages/ae-devtools-cli/devtools-cli/cli.mjs @@ -19,6 +19,7 @@ * [--consent grant|deny] [--out ] * [--close-timeout-ms ] * node cli.mjs verify [--read-op ] [--args ''] [same session flags] + * [--supervision-wait-ms ] * node cli.mjs runs — list run-guard markers (residue detection) * node cli.mjs reap [--confirm] — recover a stale owned leftover * node cli.mjs diagnose @@ -32,6 +33,15 @@ * marker) and reports fresh resolution. Both are read-only; neither * adds a dispatch path. * + * Supervision (Issue #408): a8n/a8n-attached sessions expose the ae-a8n + * session root; the durable `ae-a8n.supervision/v1` state is read + * (never written, never probed) into `evidence.supervision` and the + * diagnostics block. For UNKNOWN outcomes only, `--supervision-wait-ms` + * (default 5000, 0 disables) gives the monitor a BOUNDED window — also + * capped by the phase's own deadline — to classify a blocking state + * before the evidence is recorded. monitor-lost/degraded/unavailable + * health is reported verbatim, never as healthy. + * * Sessions: * fake — codec-faithful vm host (FAKE/MOCK evidence only) * a8n — owned AE session via a8n-transport (Issue #49); requires that @@ -81,6 +91,7 @@ import { closeSessionWithTimeout, parseCloseTimeoutMs } from "../dev-loop/sessio import { beginRun, markSession, endRun, listRuns, reapRun, recordRequestEvent, noteSessionProcess, processStartStamp, attachEvidence, RUNS_DIR, ATTESTATION_SOURCE } from "./session-guard.mjs"; import { buildFailureDiagnostics, runDiagnose } from "./diagnostics.mjs"; import { failureOutcome, normalizedOutcome, isUnknownOutcome } from "../dev-loop/outcomes.mjs"; +import { supervisionSnapshotForSession, awaitSupervisionClassification } from "../dev-loop/supervision.mjs"; import { aeDevtoolsSourceRef } from "./real-run-kit.mjs"; import { createConsentAudit } from "../trusted-execution/consent-audit.mjs"; @@ -462,6 +473,28 @@ async function main() { : await verify({ ...shared, readOpId: flags["read-op"] ?? "read.projectSummary", readArgs: args }); evidence.result = result; evidence.outcome = normalizedOutcome(result); + // Durable supervision snapshot (Issue #408): read-only consume of + // the ae-a8n supervision contract for a8n sessions. For UNKNOWN + // outcomes the monitor gets a BOUNDED window (flag or 5s default, + // 0 disables; also capped by the phase deadline) to classify a + // blocking state — there is no unbounded wait path. + let supervisionSnap = supervisionSnapshotForSession(state.session); + if (isUnknownOutcome(result) && state.session?.sessionRoot) { + const rawWait = flags["supervision-wait-ms"]; + const waitMs = rawWait === undefined + ? 5_000 + : (rawWait === "0" ? 0 : positiveMsFlag(rawWait) ?? 0); + if (waitMs > 0) { + const waited = await awaitSupervisionClassification(state.session, { timeoutMs: waitMs }); + if (waited.snapshot !== null) supervisionSnap = waited.snapshot; + evidence.supervisionWait = { + timeoutMs: waitMs, + timedOut: waited.timedOut, + deadlineExceeded: waited.deadlineExceeded, + }; + } + } + if (supervisionSnap !== null) evidence.supervision = supervisionSnap; // Additive failure diagnostics (Issue #103): a unified // ae-devtools.diagnostics/v1 record plus sourcemap resolution. // Completed runs carry no block; failures always do — an @@ -477,6 +510,7 @@ async function main() { outcome: failState, session: state.session, requestId, + supervision: supervisionSnap, mapDir: typeof flags["map-dir"] === "string" ? flags["map-dir"] : undefined, }); } diff --git a/packages/ae-devtools-cli/devtools-cli/diagnostics.mjs b/packages/ae-devtools-cli/devtools-cli/diagnostics.mjs index 5ddb65c3..b963f860 100644 --- a/packages/ae-devtools-cli/devtools-cli/diagnostics.mjs +++ b/packages/ae-devtools-cli/devtools-cli/diagnostics.mjs @@ -69,7 +69,7 @@ export function loadDiagnosticsLibs() { * status "error" — the two are distinct so consumers can tell "module * not installed" from "module ran but failed". */ -export async function buildFailureDiagnostics({ result, outcome, session, requestId, mapDir } = {}) { +export async function buildFailureDiagnostics({ result, outcome, session, requestId, supervision, mapDir } = {}) { const block = { schema: DIAGNOSTICS_BLOCK_SCHEMA, status: "ok", @@ -77,6 +77,10 @@ export async function buildFailureDiagnostics({ result, outcome, session, reques records: [], resolutions: [], mapDir: typeof mapDir === "string" ? mapDir : null, + // Additive supervision snapshot (Issue #408): the durable + // ae-a8n.supervision/v1 state for the session — same block every + // surface reports; absent when the session has no supervision. + ...(supervision !== null && supervision !== undefined ? { supervision } : {}), }; const libs = await loadDiagnosticsLibs(); if (libs.error) { @@ -89,7 +93,7 @@ export async function buildFailureDiagnostics({ result, outcome, session, reques // includes the evidence-label honesty rule, so no post-hoc fixup // is needed here. const record = recordFromExecuteResult({ - result, outcome, session, requestId, + result, outcome, session, requestId, supervision, collectors: libs.collectors, }); if (record !== null) { diff --git a/packages/ae-devtools-cli/mcp-server/tools.mjs b/packages/ae-devtools-cli/mcp-server/tools.mjs index 50652953..666ef03e 100644 --- a/packages/ae-devtools-cli/mcp-server/tools.mjs +++ b/packages/ae-devtools-cli/mcp-server/tools.mjs @@ -30,6 +30,7 @@ import { discover, inspect, execute, verify, sessionStatus, DEVLOOP_SCHEMA } from "../dev-loop/devloop.mjs"; import { failureOutcome, normalizedOutcome, isUnknownOutcome } from "../dev-loop/outcomes.mjs"; import { recordFromExecuteResult } from "../dev-loop/failure-record.mjs"; +import { supervisionSnapshotForSession } from "../dev-loop/supervision.mjs"; export const MCP_SCHEMA = "ae-devtools.mcp/v1"; @@ -148,14 +149,25 @@ async function failureDiagnostics({ result, session, requestId }) { if (state === null) return null; try { const collectors = await diagnosticsCollectors(); + // Durable supervision snapshot (Issue #408): read-only consume of + // the ae-a8n supervision contract; attached sessions get the same + // view — this never mutates the host. + const supervision = supervisionSnapshotForSession(session); const record = recordFromExecuteResult({ result, outcome: state, session: { kind: session.kind, pin: session.pin }, requestId, + supervision, collectors, }); - return record === null ? null : { status: "ok", records: [record] }; + return record === null + ? null + : { + status: "ok", + records: [record], + ...(supervision !== null ? { supervision } : {}), + }; } catch (e) { return { status: "unavailable", reason: String(e?.message ?? e), records: [] }; } diff --git a/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs b/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs index fa26aaa0..fe74bc94 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/cli.mjs @@ -19,6 +19,15 @@ * [--reports-dir d]... [--sentry-dir d]... * [--ae-a8n-root ] * + * Supervision (Issue #408): observe/recover/verify-exit accept + * --session-root naming the ae-a8n session directory that holds + * the durable `ae-a8n.supervision/v1` state (supervision.json + + * monitor.lease.json). `recover` also derives it from the run marker's + * recorded workdir when the flag is absent. The report is consumed + * read-only — this CLI never starts a monitor and never presses a + * dialog; a monitor-lost/degraded/needs-human state escalates the + * verdict instead of being read as healthy. + * * Authorization model: * * observe — read-only. Needs only a resolvable GUI session. Never @@ -58,6 +67,7 @@ import { verifyHostExit, } from "./orchestrator.mjs"; import { resolveAeA8n } from "../a8n-transport/ae-a8n-resolve.mjs"; +import { supervisionReport } from "../a8n-transport/supervision.mjs"; import { RUNS_DIR, RUN_ID_RE, @@ -237,6 +247,25 @@ function guiLeaseState(a8n, session) { } } +/** + * Resolve the ae-a8n session directory holding durable supervision + * state (Issue #408). Explicit --session-root wins; `recover` falls + * back to the run marker's recorded workdir (session.mjs lays the + * session root out as /a8n-session). Returns null when no + * directory can be proven — supervision then reads as absent, never + * as healthy. + */ +function supervisionDirFor(flags, marker = null) { + if (typeof flags["session-root"] === "string" && flags["session-root"].length > 0) { + return flags["session-root"]; + } + const workdir = marker?.session?.workdir; + if (typeof workdir === "string" && workdir.length > 0) { + return join(workdir, "a8n-session"); + } + return null; +} + function targetFromFlags(flags) { const target = {}; if (Number.isFinite(Number(flags.pid))) target.pid = Number(flags.pid); @@ -334,6 +363,12 @@ async function main() { const allowConsole = flags["allow-console"] === true; const shotDir = typeof flags["shot-dir"] === "string" ? flags["shot-dir"] : undefined; const timeoutMs = Number.isFinite(Number(flags["timeout-ms"])) ? Number(flags["timeout-ms"]) : 30_000; + // Durable supervision state for this run's session (Issue #408): + // read before AND after the attempt inside runTimeoutRecovery; the + // report can only escalate the verdict (needs-human → quarantined, + // monitor-lost → unknown), never downgrade it. + const supDir = supervisionDirFor(flags, loaded.marker); + const readSupervision = supDir === null ? null : () => supervisionReport(supDir); const gui = new a8n.MacGuiRecovery({ session, pid, screenshotDir: shotDir, allowConsoleSession: allowConsole }); const recovery = new a8n.MacHostRecovery({ @@ -346,6 +381,7 @@ async function main() { recovery, gui, requestId, method, timeoutMs, ownerId: auth.ownerId, screenshotDir: shotDir, + readSupervision, }); // Evidence, not authorization: the ae-a8n GUI lease state before the // attempt. MacHostRecovery.attempt acquires the lease itself; this @@ -366,7 +402,14 @@ async function main() { if (cmd === "observe") { const gui = new a8n.MacGuiRecovery({ session, pid, screenshotDir: shotDir, allowConsoleSession: allowConsole }); const state = observeScreen({ gui, screenshotDir: shotDir, requestId: "observe" }); - emit({ schema: "ae-devtools.recovery-orchestrator.observe/v1", ...state }); + // Additive supervision snapshot when --session-root names the + // session dir (Issue #408); absent otherwise — never fabricated. + const supDir = supervisionDirFor(flags); + emit({ + schema: "ae-devtools.recovery-orchestrator.observe/v1", + ...state, + ...(supDir !== null ? { supervision: supervisionReport(supDir) } : {}), + }); return state.ok ? 0 : 1; } @@ -384,6 +427,7 @@ async function main() { } } const expectation = flags.expectation === "crash" ? "crash" : "exit"; + const supDir = supervisionDirFor(flags); const result = verifyHostExit({ pid, pidAlive, @@ -402,6 +446,10 @@ async function main() { since: typeof flags.since === "string" ? flags.since : null, reportsDirs: multi["reports-dir"].length ? multi["reports-dir"] : undefined, sentryDirs: multi["sentry-dir"].length ? multi["sentry-dir"] : undefined, + // Durable supervision report when --session-root names the session + // dir (Issue #408): recorded on the result and gating "clean" — + // monitor-lost/degraded is never a clean bill. + supervision: supDir !== null ? supervisionReport(supDir) : null, }); emit(result); return result.verdict === "clean" || result.verdict === "crash-verified" ? 0 : 1; diff --git a/packages/ae-devtools-cli/recovery-orchestrator/diagnostics.mjs b/packages/ae-devtools-cli/recovery-orchestrator/diagnostics.mjs index f2e17a1a..2ca95834 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/diagnostics.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/diagnostics.mjs @@ -84,6 +84,29 @@ function base(ctx, kind, severity, message, outcome) { }); } +/** + * Additive supervision suffix for record messages (Issue #408): when a + * result carries the durable supervision snapshot, the phase + health + + * needs-human detail ride the message so diagnostics consumers see the + * same state every other surface reports. Absent supervision adds + * nothing — the record contract is unchanged. + */ +function supervisionSuffix(result) { + const s = result?.supervision; + // timeout-recovery nests {before, after}; exit-verification carries the + // snapshot directly on result.supervision. + const sup = s !== null && typeof s === "object" && ("before" in s || "after" in s) + ? (s.after ?? s.before ?? null) + : s; + if (sup === null || sup === undefined || typeof sup !== "object") return ""; + const parts = [`supervision=${sup.phase ?? sup.status ?? "?"}`]; + if (sup.health) parts.push(`health=${sup.health}`); + if (sup.needsHuman) { + parts.push(`needs-human: ${sup.needsHuman.reason ?? "human action required"}`); + } + return ` [${parts.join("; ")}]`; +} + /** * exit-verification result → diagnostics record(s). Always exactly one * record: every verdict is either a finding or an explicit acceptance. @@ -99,7 +122,7 @@ export function exitVerificationToDiagnostics(result, ctx = {}) { ctx, VERDICT_KIND[verdict], VERDICT_SEVERITY[verdict], - `exit-verification ${verdict} (expectation ${result.expectation ?? "?"}, pid ${result.pid ?? "?"}): ${reasons || "no reasons recorded"}`, + `exit-verification ${verdict} (expectation ${result.expectation ?? "?"}, pid ${result.pid ?? "?"}): ${reasons || "no reasons recorded"}${supervisionSuffix(result)}`, verdict, ), ]; @@ -121,7 +144,7 @@ export function timeoutRecoveryToDiagnostics(result, ctx = {}) { ctx, "transport-outcome", VERDICT_SEVERITY[verdict], - `timeout-recovery ${verdict} for ${result.method ?? "?"} (request ${result.requestId ?? "?"}): ${detail || "no outcome detail"} — original request is never resent`, + `timeout-recovery ${verdict} for ${result.method ?? "?"} (request ${result.requestId ?? "?"}): ${detail || "no outcome detail"} — original request is never resent${supervisionSuffix(result)}`, verdict, ), ]; diff --git a/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs b/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs index dbbb0e97..0bef1fd3 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/orchestrator.mjs @@ -45,6 +45,12 @@ import { copyFileSync, mkdirSync, readdirSync, readFileSync, statSync, writeFile import { join } from "node:path"; import { ATTESTATION_SOURCE, GUARD_SCHEMA, latestRequestEvent } from "../devtools-cli/session-guard.mjs"; +import { + supervisionEscalation, + supervisionSnapshot, + stricterVerdict, + supervisionBlocksClean, +} from "../a8n-transport/supervision.mjs"; export const SCHEMA = "ae-devtools.recovery-orchestrator/v2"; export { ATTESTATION_SOURCE, GUARD_SCHEMA }; @@ -647,6 +653,23 @@ export function authorizeRecovery({ marker, requestId, method, probes }) { * `recovery` is ae-a8n's HostRecovery (MacHostRecovery in production). * The original request is NEVER resent — the driver waits for its result. * `ownerId` comes from the verified run proof, not from a flag. + * + * `readSupervision` (Issue #408) is an optional injected reader for the + * ae-a8n durable supervision report (`ae-a8n.supervision/v1`, + * a8n-transport/supervision.mjs). When supplied it is called once BEFORE + * and once AFTER the recovery attempt; both snapshots are recorded on the + * result and the AFTER report (falling back to BEFORE) may ESCALATE the + * verdict — never downgrade it: + * + * - health monitor-lost/unavailable or corrupt state → "unknown" + * (a dead monitor is never read as a healthy target) + * - phase needs-human/quarantined → "quarantined" with the structured + * human request (dialog, reason, options, resume path) attached + * - phase blocked/recovering → "await-original" (bounded wait; the + * phase deadline is recorded, never an indefinite wait) + * + * The orchestrator still never presses a dialog itself and never + * implements GUI probing — supervision is consumed, not re-owned. */ export async function runTimeoutRecovery({ recovery, @@ -656,7 +679,10 @@ export async function runTimeoutRecovery({ timeoutMs, ownerId, screenshotDir, + readSupervision = null, }) { + const supervisionBefore = + typeof readSupervision === "function" ? await readSupervision().catch(() => null) : null; const before = observeScreen({ gui, screenshotDir, requestId }); let outcome; try { @@ -669,6 +695,15 @@ export async function runTimeoutRecovery({ }; } const after = observeScreen({ gui, screenshotDir, requestId: `${requestId}-post` }); + const supervisionAfter = + typeof readSupervision === "function" ? await readSupervision().catch(() => null) : null; + // The freshest trustworthy supervision report decides escalation; + // BEFORE is the fallback when AFTER could not be read. + const supervisionReport = supervisionAfter ?? supervisionBefore; + const verdict = stricterVerdict( + verdictForRecovery(outcome), + supervisionEscalation(supervisionReport), + ); return { schema: SCHEMA, kind: "timeout-recovery", @@ -685,7 +720,11 @@ export async function runTimeoutRecovery({ screenshotPath: outcome.screenshotPath ?? null, }, after, - verdict: verdictForRecovery(outcome), + supervision: { + before: supervisionSnapshot(supervisionBefore), + after: supervisionSnapshot(supervisionAfter), + }, + verdict, rules: [ "the timed-out request is never resent — its result may still arrive", "a quarantined or refused state is reported, never retried", @@ -727,6 +766,13 @@ function verdictForRecovery(outcome) { * (ae-a8n `censusRunnerInSession`); `session` records whether uid/asid * were confirmed. An unconfirmed session degrades the census channel to * unavailable → unknown, never clean. + * + * `supervision` (Issue #408) is an optional ae-a8n SupervisionReport read + * from the session's durable state (a8n-transport/supervision.mjs). It is + * recorded on the result as `supervision`, and it GATES the "clean" + * verdict: degraded/monitor-lost/unavailable observation health or a + * still-blocking phase means the GUI state is not provably unobstructed, + * so "clean" degrades to "unknown" — monitor-lost is never healthy. */ export function verifyHostExit({ pid, @@ -740,6 +786,7 @@ export function verifyHostExit({ collectEvidence = collectCrashEvidence, reportsDirs, sentryDirs, + supervision = null, }) { const result = { schema: SCHEMA, @@ -754,6 +801,10 @@ export function verifyHostExit({ }, verdict: "unknown", reasons: [], + // Additive supervision snapshot (Issue #408): the durable + // ae-a8n.supervision/v1 report for the session dir, or null when no + // report was supplied. Recorded on EVERY outcome, not only clean. + supervision: supervisionSnapshot(supervision), }; result.channels.windows.pidAttribution = session?.pidAttribution ?? null; @@ -867,6 +918,20 @@ export function verifyHostExit({ result.reasons.push("process gone, census clean, evidence collected, no correlated crash reports"); } } + // Supervision gate (Issue #408): "clean" asserts the GUI is provably + // unobstructed — that claim requires ok observation health AND a + // running/resumed phase. monitor-lost/degraded/unavailable health or + // a still-blocking phase degrades clean to unknown; it is never read + // as healthy. Other verdicts already carry their own honesty and are + // not rewritten here. + if (result.verdict === "clean" && supervisionBlocksClean(supervision)) { + result.verdict = "unknown"; + result.reasons.push( + "supervision observation does not prove a clean GUI state " + + `(health=${supervision?.health ?? supervision?.doc?.observationHealth ?? "?"}, ` + + `phase=${supervision?.doc?.phase ?? "?"}) — monitor-lost/degraded is never clean`, + ); + } return result; } diff --git a/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs b/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs index 3bc31e50..66f69557 100644 --- a/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs +++ b/packages/ae-devtools-cli/recovery-orchestrator/tests/run.mjs @@ -985,6 +985,178 @@ t("crashEvidenceToDiagnostics: incomplete collection -> warning, empty complete assert.deepEqual(empty, []); }); +// ------------------------------------------------ supervision verdicts (Issue #408) +// Fake level only: supervision reports are built as plain objects matching +// the ae-a8n.supervision/v1 contract consumed by a8n-transport/supervision.mjs. +// No AE, no monitor, no GUI. + +function supDoc(overrides = {}) { + return { + schemaVersion: "ae-a8n.supervision/v1", + sessionId: "sess-1", + phase: "running", + observationHealth: "ok", + blocking: null, + pendingRequests: [], + enteredAt: "2026-11-20T11:59:00.000Z", + deadline: null, + evidence: [], + monitor: { + ownerId: "mon-1", pid: 1, pidStart: null, + acquiredAt: "2026-11-20T11:58:00.000Z", heartbeatAt: new Date().toISOString(), + }, + history: [], + updatedAt: new Date().toISOString(), + ...overrides, + }; +} + +function supReport(docOverrides = {}, reportOverrides = {}) { + const doc = supDoc(docOverrides); + return { + status: "observed", + source: "state", + doc, + health: doc.observationHealth, + healthDetail: null, + readAt: new Date().toISOString(), + ...reportOverrides, + }; +} + +await at("runTimeoutRecovery: needs-human supervision escalates to quarantined with structured detail", async () => { + const report = supReport({ + phase: "needs-human", + deadline: "2026-11-20T12:10:00.000Z", + blocking: { + host: "none", + detail: "sign-in dialog is up", + windows: [{ + title: "Sign In", role: "AXWindow", subrole: "AXDialog", blocking: true, + tier: "human-required", dialogClass: "sign-in", code: "A8N-AUTH-001", + texts: ["Please sign in"], buttons: ["Cancel", "Sign In"], + }], + }, + }); + const r = await runTimeoutRecovery({ + recovery: fakeRecovery({ recovered: true, outcome: "dismissed", evidence: "pressed OK" }), + gui: fakeGui({ windows: [win("x")] }), + requestId: "req-1", method: "app.info", timeoutMs: 1000, + ownerId: "run:run-test-1", + readSupervision: async () => report, + }); + // Recovery claimed dismissed → await-original, but supervision says a + // human must act: escalation wins, never downgrade. + assert.equal(r.verdict, "quarantined"); + assert.equal(r.supervision.after.phase, "needs-human"); + assert.equal(r.supervision.after.needsHuman.phase, "needs-human"); + assert.deepEqual(r.supervision.after.needsHuman.options.sort(), ["Cancel", "Sign In"]); + assert.match(r.supervision.after.needsHuman.resumePath, /supervision status/); + assert.match(r.supervision.after.needsHuman.requiredAction, /human/i); +}); + +await at("runTimeoutRecovery: monitor-lost/unavailable health escalates to unknown, never clean", async () => { + for (const health of ["monitor-lost", "unavailable"]) { + const report = supReport({ phase: "running" }, { health }); + const r = await runTimeoutRecovery({ + recovery: fakeRecovery({ recovered: true, outcome: "dismissed" }), + gui: fakeGui({}), requestId: "r", method: "m", timeoutMs: 1, ownerId: "o", + readSupervision: async () => report, + }); + assert.equal(r.verdict, "unknown", `${health} must not be read as recovered`); + assert.equal(r.supervision.after.health, health); + } +}); + +await at("runTimeoutRecovery: blocked phase maps to await-original within deadline", async () => { + const report = supReport({ phase: "blocked", deadline: "2026-11-20T12:05:00.000Z" }); + // Base verdict await-original (recovered) + supervision blocked → + // still await-original: the request may complete inside the deadline. + const r = await runTimeoutRecovery({ + recovery: fakeRecovery({ recovered: true, outcome: "dismissed" }), + gui: fakeGui({}), requestId: "r", method: "m", timeoutMs: 1, ownerId: "o", + readSupervision: async () => report, + }); + assert.equal(r.verdict, "await-original"); + assert.equal(r.supervision.after.phase, "blocked"); + assert.equal(r.supervision.after.deadline, "2026-11-20T12:05:00.000Z"); +}); + +await at("runTimeoutRecovery: blocked supervision never downgrades an unknown verdict", async () => { + const report = supReport({ phase: "blocked", deadline: "2026-11-20T12:05:00.000Z" }); + const r = await runTimeoutRecovery({ + recovery: fakeRecovery({ recovered: false, outcome: "still-blocked", evidence: "dialog remains" }), + gui: fakeGui({}), requestId: "r", method: "m", timeoutMs: 1, ownerId: "o", + readSupervision: async () => report, + }); + assert.equal(r.verdict, "unknown"); +}); + +await at("runTimeoutRecovery: corrupt supervision state escalates to unknown", async () => { + const r = await runTimeoutRecovery({ + recovery: fakeRecovery({ recovered: true, outcome: "dismissed" }), + gui: fakeGui({}), requestId: "r", method: "m", timeoutMs: 1, ownerId: "o", + readSupervision: async () => ({ status: "unavailable", source: "corrupt", reason: "bad json", readAt: new Date().toISOString() }), + }); + assert.equal(r.verdict, "unknown"); +}); + +await at("runTimeoutRecovery: absent supervision does not change the verdict", async () => { + const r = await runTimeoutRecovery({ + recovery: fakeRecovery({ recovered: true, outcome: "dismissed" }), + gui: fakeGui({}), requestId: "r", method: "m", timeoutMs: 1, ownerId: "o", + readSupervision: async () => null, + }); + assert.equal(r.verdict, "await-original"); + assert.equal(r.supervision.after, null); +}); + +t("verifyHostExit: degraded/monitor-lost supervision never allows clean", () => { + const base = { + pid: 4242, pidAlive: () => false, census: CENSUS_CLEAN, session: SESSION_OK, + evidenceDir: tmp(), collectEvidence: fakeEvidence({}), expectation: "exit", + }; + for (const [doc, health] of [ + [{ phase: "running" }, "degraded"], + [{ phase: "running" }, "monitor-lost"], + [{ phase: "blocked", deadline: "2999-01-01T00:00:00.000Z" }, "ok"], + ]) { + const r = verifyHostExit({ ...base, supervision: supReport(doc, { health }) }); + assert.equal(r.verdict, "unknown", `health=${health} phase=${doc.phase}`); + assert.equal(r.supervision.status, "observed"); + } + // ok + running stays clean — the gate only blocks untrustworthy observation. + const clean = verifyHostExit({ ...base, supervision: supReport() }); + assert.equal(clean.verdict, "clean"); +}); + +t("verifyHostExit: corrupt supervision state is unknown, not clean", () => { + const r = verifyHostExit({ + pid: 4242, pidAlive: () => false, census: CENSUS_CLEAN, session: SESSION_OK, + evidenceDir: tmp(), collectEvidence: fakeEvidence({}), expectation: "exit", + supervision: { status: "unavailable", source: "corrupt", reason: "bad json", readAt: new Date().toISOString() }, + }); + assert.equal(r.verdict, "unknown"); +}); + +t("supervision diagnostics suffix carries phase/health/needs-human", () => { + const report = supReport({ + phase: "needs-human", + deadline: "2026-11-20T12:10:00.000Z", + blocking: { host: "none", detail: "license dialog", windows: [] }, + }); + const r = verifyHostExit({ + pid: 4242, pidAlive: () => false, census: CENSUS_CLEAN, session: SESSION_OK, + evidenceDir: tmp(), collectEvidence: fakeEvidence({}), expectation: "exit", + supervision: report, + }); + assert.equal(r.verdict, "unknown"); // needs-human blocks clean + const [rec] = exitVerificationToDiagnostics(r, {}); + assert.match(rec.message, /supervision=needs-human/); + assert.match(rec.message, /needs-human: license dialog/); + validateDiagnosticsRecord(rec); +}); + t("diagnostics converters refuse unknown verdicts instead of guessing", () => { assert.throws(() => exitVerificationToDiagnostics({ verdict: "looks-fine", reasons: [] }, {}), /unknown verdict/); assert.throws(() => recoveryActionFor("looks-fine"), /unknown verdict/);