Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions packages/ae-devtools-cli/dev-loop/supervision.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
supervisionReport,
supervisionSnapshot,
supervisionStatePath,
sessionDirFor,
waitForSupervisionPhase,
} from "../a8n-transport/supervision.mjs";

Expand All @@ -29,6 +30,7 @@ export {
supervisionSnapshot,
supervisionStatePath,
waitForSupervisionPhase,
sessionDirFor,
};

/** Phases that mean "supervision has something to report". */
Expand Down Expand Up @@ -89,6 +91,111 @@ export async function awaitSupervisionPhaseForDir(sessionDir, {
};
}

// ------------------------------------------------------------ attached sessions (Issue #410)

/**
* Whether a session is an explicit-attached session (Issue #366
* contract): kind a8n-attached, or a session whose policy declares the
* attached/read-only mode. Owned-disposable sessions are NOT attached —
* they keep their own lifecycle and need no target re-validation to
* read their own supervision state.
*/
export function isAttachedSession(session) {
if (session === null || typeof session !== "object") return false;
if (session.kind === "a8n-attached") return true;
const policy = session.policy;
return (
policy !== null && typeof policy === "object" &&
(policy.mode === "attached" || policy.readOnly === true)
);
}

/**
* Honest "cannot prove the target" snapshot for attached sessions whose
* identity guard fails or is absent. Deliberately NOT the durable
* report: after a session change / PID reuse / second instance the
* state file may describe a DIFFERENT After Effects, and serving it
* as current would be a false green. Fail closed — unavailable.
*/
function guardUnavailableSnapshot(reason, code = null) {
return {
status: "unavailable",
source: "target-guard",
code,
reason,
readAt: new Date().toISOString(),
};
}

/**
* Re-validate an attached session's target identity through the SAME
* `targetGuard` runOperation invokes before mutating dispatches
* (a8n-transport/attached-session.mjs revalidateTarget: census,
* pid/start-stamp, version, project — fail closed on ambiguity). The
* guard itself performs only ae-a8n attested reads; it never mutates.
*
* @returns {Promise<{ok:boolean, code:string|null, detail:string|null}>}
* ok:true for non-attached sessions (guard not required) and for
* attached sessions whose guard passes; ok:false with the guard's
* own code/detail otherwise. Never throws.
*/
export async function attachedTargetGuardVerdict(session) {
if (!isAttachedSession(session)) return { ok: true, code: null, detail: null };
if (typeof session?.targetGuard !== "function") {
return {
ok: false,
code: "ATTACHED_TARGET_UNGUARDED",
detail: "attached session carries no targetGuard — supervision state cannot be tied to a proven AE instance",
};
}
try {
const verdict = await session.targetGuard();
if (verdict !== null && typeof verdict === "object" && verdict.ok === true) {
return { ok: true, code: null, detail: null };
}
return {
ok: false,
code: typeof verdict?.code === "string" ? verdict.code : "ATTACHED_TARGET_UNVERIFIED",
detail: typeof verdict?.detail === "string" ? verdict.detail : "attached target re-validation did not attest the session",
};
} catch (error) {
return {
ok: false,
code: "ATTACHED_TARGET_UNVERIFIED",
detail: `attached target re-validation threw: ${String(error?.message ?? error)}`,
};
}
}

/**
* Guarded supervision snapshot for any dev-loop session (Issue #410).
*
* - fake / no ae-a8n root → null (honest non-applicability)
* - owned a8n session → the durable report, unguarded (the session
* owns its AE; its own lifecycle bounds staleness)
* - attached session → the target identity is re-validated FIRST;
* a failed/missing guard yields an honest `unavailable`
* (source "target-guard") snapshot instead of a possibly-stale
* report. Reading never promotes ownership and never mutates.
*
* @returns {Promise<object|null>} supervisionSnapshot() shape, or null
*/
export async function guardedSupervisionSnapshot(session, options = {}) {
const dir = sessionDirFor(session);
if (dir === null) return null;
if (isAttachedSession(session)) {
const verdict = await attachedTargetGuardVerdict(session);
if (!verdict.ok) {
return guardUnavailableSnapshot(
`attached target re-validation failed (${verdict.code}): ${verdict.detail} — ` +
"the durable supervision state may describe a different After Effects instance",
verdict.code,
);
}
}
return supervisionSnapshot(supervisionReport(dir, options));
}

/**
* Bounded wait for supervision to classify a blocking state after a
* dispatch ended UNKNOWN (the modal-dialog case supervision exists
Expand Down
80 changes: 80 additions & 0 deletions packages/ae-devtools-cli/dev-loop/tests/supervision.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { test } from "node:test";
import {
supervisionSnapshotForSession,
awaitSupervisionClassification,
isAttachedSession,
attachedTargetGuardVerdict,
guardedSupervisionSnapshot,
} from "../supervision.mjs";
import { supervisionStatePath } from "../../a8n-transport/supervision.mjs";
import { recordFromExecuteResult } from "../failure-record.mjs";
Expand Down Expand Up @@ -96,6 +99,83 @@ test("awaitSupervisionClassification: no session root returns immediately", asyn
assert.equal(r.timedOut, false);
});

// ------------------------------------------------ attached sessions (Issue #410)
// Read-only report access for explicit-attached sessions: the durable
// report is served ONLY while the session's target identity
// re-validates. Session change / PID reuse / second instance /
// missing guard all fail closed — never a possibly-stale report.

function attachedSession(dir, { guard, policy } = {}) {
return {
kind: "a8n-attached",
evidenceLevel: "verified on real host (attach to a running AE)",
sessionRoot: dir,
policy: policy ?? { readOnly: true, mode: "attached", mutation: { allowedOps: [] } },
targetGuard: guard ?? (async () => ({ ok: true })),
runner: { call: async () => { throw new Error("runner must never be invoked by supervision reads"); } },
pin: null,
close: async () => {},
};
}

test("isAttachedSession: kind and policy shapes, owned sessions excluded", () => {
assert.equal(isAttachedSession(attachedSession(tmp())), true);
assert.equal(isAttachedSession({ kind: "a8n", policy: null }), false);
assert.equal(isAttachedSession({ kind: "fake", policy: { readOnly: true } }), true);
assert.equal(isAttachedSession(null), false);
});

test("guardedSupervisionSnapshot: attached + passing guard serves the report", async () => {
const dir = tmp();
writeDoc(dir, { phase: "blocked", deadline: new Date(Date.now() + 60_000).toISOString() });
const snap = await guardedSupervisionSnapshot(attachedSession(dir));
assert.equal(snap.status, "observed");
assert.equal(snap.phase, "blocked");
});

test("guardedSupervisionSnapshot: failing guard fails closed — stale report never served", async () => {
const dir = tmp();
writeDoc(dir, { phase: "needs-human", deadline: new Date(Date.now() + 60_000).toISOString() });
const snap = await guardedSupervisionSnapshot(attachedSession(dir, {
guard: async () => ({ ok: false, code: "ATTACHED_TARGET_CHANGED", detail: "pid changed 111 -> 222" }),
}));
assert.equal(snap.status, "unavailable");
assert.equal(snap.source, "target-guard");
assert.equal(snap.code, "ATTACHED_TARGET_CHANGED");
assert.match(snap.reason, /pid changed/);
// The durable phase must NOT leak through a failed guard.
assert.equal(snap.phase ?? null, null);
});

test("guardedSupervisionSnapshot: attached session without targetGuard fails closed", async () => {
const dir = tmp();
writeDoc(dir);
const s = attachedSession(dir);
s.targetGuard = null;
const snap = await guardedSupervisionSnapshot(s);
assert.equal(snap.status, "unavailable");
assert.equal(snap.code, "ATTACHED_TARGET_UNGUARDED");
});

test("guardedSupervisionSnapshot: owned a8n session reads unguarded; fake is null", async () => {
const dir = tmp();
writeDoc(dir);
const owned = { kind: "a8n", sessionRoot: dir, policy: null, targetGuard: null };
const snap = await guardedSupervisionSnapshot(owned);
assert.equal(snap.status, "observed");
assert.equal(snap.phase, "running");
assert.equal(await guardedSupervisionSnapshot({ kind: "fake" }), null);
});

test("attachedTargetGuardVerdict: non-attached is trivially ok; throwing guard is honest", async () => {
assert.deepEqual(await attachedTargetGuardVerdict({ kind: "a8n" }), { ok: true, code: null, detail: null });
const s = attachedSession(tmp(), { guard: async () => { throw new Error("census boom"); } });
const v = await attachedTargetGuardVerdict(s);
assert.equal(v.ok, false);
assert.equal(v.code, "ATTACHED_TARGET_UNVERIFIED");
assert.match(v.detail, /census boom/);
});

test("recordFromExecuteResult attaches supervision snapshot additively", () => {
const dir = tmp();
writeDoc(dir, {
Expand Down
31 changes: 23 additions & 8 deletions packages/ae-devtools-cli/devtools-cli/cli.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,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 { awaitSupervisionClassification, guardedSupervisionSnapshot, attachedTargetGuardVerdict } from "../dev-loop/supervision.mjs";
import {
supervisionReport,
supervisionSnapshot,
Expand Down Expand Up @@ -550,20 +550,35 @@ 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);
// Durable supervision snapshot (Issue #408/#410): read-only
// consume of the ae-a8n supervision contract for a8n sessions.
// Attached sessions are served only while their target identity
// re-validates (session change / PID reuse fails closed). 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 = await guardedSupervisionSnapshot(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;
// Re-validate the attached target after the wait — a guard
// failure discards the snapshot rather than serving state
// that may describe a different AE instance.
const afterGuard = await attachedTargetGuardVerdict(state.session);
if (waited.snapshot !== null && afterGuard.ok) supervisionSnap = waited.snapshot;
else if (!afterGuard.ok) {
supervisionSnap = {
status: "unavailable",
source: "target-guard",
code: afterGuard.code,
reason: `attached target re-validation failed after wait (${afterGuard.code}): ${afterGuard.detail}`,
readAt: new Date().toISOString(),
};
}
evidence.supervisionWait = {
timeoutMs: waitMs,
timedOut: waited.timedOut,
Expand Down
111 changes: 111 additions & 0 deletions packages/ae-devtools-cli/mcp-server/tests/server.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,117 @@ test("ae_session carries the supervision snapshot when a session with a root is
await c.server.close();
});

// ------------------------------------------------ attached supervision (Issue #410)
// Read-only report access for explicit-attached sessions, fail-closed on
// target-identity drift. Fake level only: session objects are shaped
// like the stripped a8n-attached session; the guard is a stub — the
// real revalidateTarget census/pid/project checks are covered by
// a8n-transport/tests/attached-session.test.mjs.

function fakeAttachedSession(dir, { guard } = {}) {
// Codec-faithful fake host underneath: read dispatches complete so the
// session can be opened; mutating ops are refused by session policy
// BEFORE the runner is ever invoked.
const base = openFakeSession();
return {
kind: "a8n-attached",
evidenceLevel: "verified on real host (attach to a running AE)",
sessionRoot: dir,
policy: { readOnly: true, mode: "attached", mutation: { allowedOps: [] } },
targetGuard: guard ?? (async () => ({ ok: true })),
runner: base.runner,
pin: base.pin,
meta: { aeVersion: "26.5-fake", ownership: "attached", attached: true },
close: async () => {},
};
}

test("ae_supervision on attached session: passing guard serves report, no dispatch", async () => {
const dir = mkdtempSync(join(tmpdir(), "ae-sup-att-"));
writeSupervisionDoc(dir, { phase: "running" });
const s = fakeAttachedSession(dir);
const c = makeClient({ sessionFactory: async () => s });
// Open the session first via a read dispatch.
await c.request("tools/call", {
name: "ae_execute",
arguments: { opId: "read.projectSummary", consent: "grant" },
});
const { payload } = toolPayload(await c.request("tools/call", {
name: "ae_supervision", arguments: {},
}));
assert.equal(payload.resolvedFrom, "open-session");
assert.equal(payload.supervision.status, "observed");
assert.equal(payload.supervision.phase, "running");
rmSync(dir, { recursive: true, force: true });
await c.server.close();
});

test("ae_supervision on attached session: failed target guard fails closed", async () => {
const dir = mkdtempSync(join(tmpdir(), "ae-sup-att-fail-"));
writeSupervisionDoc(dir, { phase: "needs-human", deadline: new Date(Date.now() + 60_000).toISOString() });
const s = fakeAttachedSession(dir, {
guard: async () => ({ ok: false, code: "ATTACHED_TARGET_AMBIGUOUS", detail: "2 AE processes match" }),
});
const c = makeClient({ sessionFactory: async () => s });
await c.request("tools/call", {
name: "ae_execute",
arguments: { opId: "read.projectSummary", consent: "grant" },
});
const { payload } = toolPayload(await c.request("tools/call", {
name: "ae_supervision", arguments: {},
}));
assert.equal(payload.supervision.status, "unavailable");
assert.equal(payload.supervision.source, "target-guard");
assert.equal(payload.supervision.code, "ATTACHED_TARGET_AMBIGUOUS");
// The durable phase must not leak through a failed guard.
assert.equal(payload.supervision.phase ?? null, null);
rmSync(dir, { recursive: true, force: true });
await c.server.close();
});

test("ae_supervision on attached session without targetGuard fails closed", async () => {
const dir = mkdtempSync(join(tmpdir(), "ae-sup-att-noguard-"));
writeSupervisionDoc(dir);
const s = fakeAttachedSession(dir);
s.targetGuard = null;
const c = makeClient({ sessionFactory: async () => s });
await c.request("tools/call", {
name: "ae_execute",
arguments: { opId: "read.projectSummary", consent: "grant" },
});
const { payload } = toolPayload(await c.request("tools/call", {
name: "ae_supervision", arguments: {},
}));
assert.equal(payload.supervision.status, "unavailable");
assert.equal(payload.supervision.code, "ATTACHED_TARGET_UNGUARDED");
rmSync(dir, { recursive: true, force: true });
await c.server.close();
});

test("attached read-only session: mutating op refused before dispatch, supervision rides diagnostics", async () => {
const dir = mkdtempSync(join(tmpdir(), "ae-sup-att-mut-"));
writeSupervisionDoc(dir, {
phase: "needs-human",
deadline: new Date(Date.now() + 60_000).toISOString(),
blocking: { host: "none", detail: "modal needs a human", windows: [] },
});
const s = fakeAttachedSession(dir);
const c = makeClient({ sessionFactory: async () => s });
const { payload, isError } = toolPayload(await c.request("tools/call", {
name: "ae_execute",
arguments: { opId: "item.addComp", args: { name: "x" }, consent: "grant" },
}));
assert.equal(isError, true);
assert.equal(payload.result.status, "refused");
assert.equal(payload.result.reason, "READ_ONLY_SESSION");
// The refusal never reached the runner — supervision still reports
// the human-required state as structured diagnostics.
assert.equal(payload.diagnostics.supervision.phase, "needs-human");
assert.equal(payload.diagnostics.supervision.needsHuman.reason, "modal needs a human");
rmSync(dir, { recursive: true, force: true });
await c.server.close();
});

test("ae_execute without consent is refused BEFORE any session opens (default deny)", async () => {
const { factory, calls } = countingSessionFactory();
const c = makeClient({ sessionFactory: factory });
Expand Down
Loading
Loading