/** * Runtime acceptance guard (specs/2026-10-27-adaptive-decisions, TECH §6, E5.1). * * A consultant result may influence a decision only while every binding it was * launched under still holds. `acceptConsultantResult` checks, in order: * * - identity: the record exists, its decisionId is the goal's activeDecisionId, * the record is still `open`, and this childRunId is not already settled in * the record (idempotent: a duplicate is ignored, never re-applied); * - bindings (fresh at acceptance): goal status is `active` (not paused or * otherwise stopped); the project settings file is re-read from disk, its * mode is not `manual`, and its snapshot id equals the record's policyVersion; * the current objective hash equals the record's requestAnchor.objectiveHash; * the current scheduler generation equals the record's generation; * - delivery: not past the launch deadline; the consultant run succeeded and its * payload passes the role schema. * * Stale, duplicate, out-of-order, and terminal-record deliveries are ignored and * write nothing. A result that arrives for the current decision but fails a * binding or the delivery checks invalidates the record (`invalidated`; the * acceptance guard is its only writer). Acceptance itself writes nothing: the * caller persists the accepted result (and any `decided` status) afterwards. * * Cancellation and restart (TECH §6, E5.2) also invalidate, through the same * single writer: `invalidateOpenDecision` for a deliberation stopped while its * consultants ran, and `invalidateInterruptedDecisions` for open records left by * a session that no longer exists. Nothing is relaunched. A late delivery for an * invalidated record is `not-open` and is ignored, so it can never resume a * stopped goal. `acceptDecisionResolution` accepts the final outcome of a deliberation (E6.1): * an autonomous outcome is checked fresh (mode, snapshot, objective, generation) before it is decided. */ import { Value } from "typebox/value"; import { CriticPayloadSchema, ResearcherPayloadSchema, type ConsultantRole, type ConsultantRunResult, type CriticPayload, type ResearcherPayload, } from "./goal-decision-consultant.ts"; import { readModeFreshFromDisk, type GoalDecisionMode } from "./goal-decision-policy.ts"; import { getDecisions, objectiveAnchor, setDecisionStatus, updateDecision, type DecisionRecord } from "./goal-decision-record.ts"; import type { GoalStatus } from "./goal-record.ts"; import type { GoalStorageContext } from "./storage/goal-root.ts"; /** Goal state read at acceptance time. `generation` is the scheduler generation (undefined when the goal has no scheduler state). */ export interface GoalAcceptanceView { status: GoalStatus; objective: string; activeDecisionId?: string; generation?: string; } /** What the launcher captured when the consultant was started. */ export interface ConsultantLaunchBinding { decisionId: string; childRunId: string; role: ConsultantRole; /** Epoch milliseconds after which the result is no longer accepted (launch time + consultantDeadlineMs). */ deadlineAt: number; } export interface AcceptanceInput { storage: GoalStorageContext; goalId: string; /** Project root whose settings file is re-read from disk (cache-bypassing). */ cwd: string; env?: NodeJS.ProcessEnv; goal: GoalAcceptanceView; launch: ConsultantLaunchBinding; result: ConsultantRunResult; /** Epoch milliseconds; defaults to Date.now(). */ now?: number; } export type IgnoredReason = "unknown-decision" | "stale-decision" | "not-open" | "duplicate"; export type InvalidationReason = | "goal-not-active" | "mode-manual" | "settings-snapshot" | "objective-changed" | "generation-changed" | "deadline-exceeded" | "consultant-failed" | "schema-invalid" | "cancelled" | "restarted"; export type AcceptanceVerdict = | { kind: "accepted"; decisionId: string; childRunId: string; role: ConsultantRole; payload: ResearcherPayload | CriticPayload; mode: GoalDecisionMode } | { kind: "ignored"; reason: IgnoredReason } | { kind: "invalidated"; reason: InvalidationReason; detail: string } | { kind: "store-error"; reason: string }; const PAYLOAD_SCHEMAS = { researcher: ResearcherPayloadSchema, critic: CriticPayloadSchema, } as const; interface Problem { reason: InvalidationReason; detail: string; } type FreshSettings = ReturnType; /** * Checks that the goal, settings, objective, and generation still match the record. * `settings` is the project settings read fresh from disk by the caller. */ function bindingProblem(goal: GoalAcceptanceView | null, record: DecisionRecord, settings: FreshSettings): Problem | undefined { if (goal === null) return { reason: "goal-not-active", detail: "no goal is focused" }; if (goal.status !== "active") return { reason: "goal-not-active", detail: `goal status is ${goal.status}` }; if (settings.mode === "manual") return { reason: "mode-manual", detail: "decisionMode is manual" }; if (settings.snapshotId !== record.policyVersion) { return { reason: "settings-snapshot", detail: `settings snapshot ${settings.snapshotId} differs from ${record.policyVersion}` }; } if (objectiveAnchor(goal.objective).objectiveHash !== record.requestAnchor.objectiveHash) { return { reason: "objective-changed", detail: "goal objective changed since the decision" }; } if (goal.generation !== record.generation) { return { reason: "generation-changed", detail: "goal scheduler generation changed since the decision" }; } return undefined; } /** Deadline, run success, and role schema of the delivered result. Narrows to the validated payload on success. */ function deliveredPayload(input: AcceptanceInput): { ok: true; payload: ResearcherPayload | CriticPayload } | { ok: false; problem: Problem } { const { launch, result } = input; const now = input.now ?? Date.now(); if (now > launch.deadlineAt) { return { ok: false, problem: { reason: "deadline-exceeded", detail: `result arrived ${now - launch.deadlineAt} ms after the deadline` } }; } if (!result.ok) return { ok: false, problem: { reason: "consultant-failed", detail: `${result.errorCode}: ${result.message}` } }; const schema = PAYLOAD_SCHEMAS[launch.role]; if (!Value.Check(schema, result.payload)) { const [first] = Value.Errors(schema, result.payload); return { ok: false, problem: { reason: "schema-invalid", detail: `${first?.instancePath || "/"}: ${first?.message ?? "does not match the role schema"}` } }; } return { ok: true, payload: result.payload as ResearcherPayload | CriticPayload }; } /** * Decides whether a consultant result may be accepted for the goal's active * decision. See the module comment for the order of checks and the write rules. */ export function acceptConsultantResult(input: AcceptanceInput): AcceptanceVerdict { const { storage, goalId, launch, goal } = input; const listed = getDecisions(storage, goalId); if (!listed.ok) return { kind: "store-error", reason: `decision store ${listed.error.code}: ${listed.error.message}` }; const record = listed.value.find((candidate) => candidate.id === launch.decisionId); if (!record) return { kind: "ignored", reason: "unknown-decision" }; if (goal.activeDecisionId !== record.id) return { kind: "ignored", reason: "stale-decision" }; if (record.status !== "open") return { kind: "ignored", reason: "not-open" }; if (record.consultants.some((entry) => entry.childRunId === launch.childRunId)) return { kind: "ignored", reason: "duplicate" }; const settings = readModeFreshFromDisk(input.cwd, input.env); const binding = bindingProblem(goal, record, settings); if (binding) return invalidate(input.storage, input.goalId, record, binding); const delivered = deliveredPayload(input); if (!delivered.ok) return invalidate(input.storage, input.goalId, record, delivered.problem); return { kind: "accepted", decisionId: record.id, childRunId: launch.childRunId, role: launch.role, payload: delivered.payload, mode: settings.mode, }; } /** Moves the open record to `invalidated` (acceptance guard is its only writer). A concurrent change is a store error, nothing else. */ function invalidate(storage: GoalStorageContext, goalId: string, record: DecisionRecord, problem: Problem): AcceptanceVerdict { const written = setDecisionStatus(storage, goalId, record.id, "invalidated", { writer: "acceptance-guard", expectedRevision: record.revision }); if (!written.ok) return { kind: "store-error", reason: `decision store ${written.error.code}: ${written.error.message}` }; return { kind: "invalidated", reason: problem.reason, detail: problem.detail }; } /** * Invalidates one deliberation that was stopped while its consultants ran (pause, * interrupt, abort). Only an `open` record moves; a terminal record is `ignored`. */ export function invalidateOpenDecision( storage: GoalStorageContext, goalId: string, decisionId: string, reason: Extract, detail: string, ): AcceptanceVerdict { const listed = getDecisions(storage, goalId); if (!listed.ok) return { kind: "store-error", reason: `decision store ${listed.error.code}: ${listed.error.message}` }; const record = listed.value.find((candidate) => candidate.id === decisionId); if (!record) return { kind: "ignored", reason: "unknown-decision" }; if (record.status !== "open") return { kind: "ignored", reason: "not-open" }; return invalidate(storage, goalId, record, { reason, detail }); } /** * Restart (TECH §6): every open record of the goal belongs to a deliberation whose * in-flight consultants died with the previous session, so each one is invalidated * (`restarted`). Nothing is relaunched; a later deliberation starts fresh. Records * that were consulted but not yet accepted are open too and are invalidated the * same way (fail closed). Returns the ids moved, or the first store error. */ export function invalidateInterruptedDecisions( storage: GoalStorageContext, goalId: string, ): { kind: "done"; invalidated: string[] } | { kind: "store-error"; reason: string } { const listed = getDecisions(storage, goalId); if (!listed.ok) return { kind: "store-error", reason: `decision store ${listed.error.code}: ${listed.error.message}` }; const invalidated: string[] = []; for (const record of listed.value) { if (record.status !== "open") continue; const verdict = invalidate(storage, goalId, record, { reason: "restarted", detail: "the session that ran this deliberation was restarted" }); if (verdict.kind === "store-error") return verdict; invalidated.push(record.id); } return { kind: "done", invalidated }; } /** The final resolution of a deliberation: what the model continues with (TECH §3 `outcome`). */ export type DecisionResolutionOutcome = NonNullable; export interface ResolutionAcceptanceInput { storage: GoalStorageContext; goalId: string; /** Project root whose settings file is re-read from disk (cache-bypassing). */ cwd: string; env?: NodeJS.ProcessEnv; /** The focused goal read at acceptance; null when no goal is focused. */ goal: GoalAcceptanceView | null; decisionId: string; /** * `agent`: an autonomous resolution (bounded-auto) — fresh mode, snapshot, objective, and * generation checks apply. `human`: the owner's own answer, not autonomous — only the * record's identity and open status are checked. */ source: "agent" | "human"; outcome: DecisionResolutionOutcome; } export type ResolutionAcceptanceVerdict = | { kind: "decided"; record: DecisionRecord } | { kind: "ignored"; reason: IgnoredReason } | { kind: "invalidated"; reason: InvalidationReason; detail: string } | { kind: "store-error"; reason: string }; /** * Accepts the final resolution of an open record (TECH §6, §8): on success the outcome * is written and the record moves to `decided` (acceptance guard is the only writer). An * autonomous resolution that fails a binding check moves the record to `invalidated` * instead and writes no outcome. A terminal or unknown record is `ignored`. */ export function acceptDecisionResolution(input: ResolutionAcceptanceInput): ResolutionAcceptanceVerdict { const { storage, goalId, goal } = input; const listed = getDecisions(storage, goalId); if (!listed.ok) return { kind: "store-error", reason: `decision store ${listed.error.code}: ${listed.error.message}` }; const record = listed.value.find((candidate) => candidate.id === input.decisionId); if (!record) return { kind: "ignored", reason: "unknown-decision" }; if (record.status !== "open") return { kind: "ignored", reason: "not-open" }; if (input.source === "agent") { const binding = bindingProblem(goal, record, readModeFreshFromDisk(input.cwd, input.env)); if (binding) { const written = setDecisionStatus(storage, goalId, record.id, "invalidated", { writer: "acceptance-guard", expectedRevision: record.revision }); if (!written.ok) return { kind: "store-error", reason: `decision store ${written.error.code}: ${written.error.message}` }; return { kind: "invalidated", reason: binding.reason, detail: binding.detail }; } } const withOutcome = updateDecision(storage, goalId, record.id, (draft) => ({ ...draft, outcome: input.outcome }), record.revision); if (!withOutcome.ok) return { kind: "store-error", reason: `decision store ${withOutcome.error.code}: ${withOutcome.error.message}` }; const settled = setDecisionStatus(storage, goalId, record.id, "decided", { writer: "acceptance-guard", expectedRevision: withOutcome.value.revision }); if (!settled.ok) return { kind: "store-error", reason: `decision store ${settled.error.code}: ${settled.error.message}` }; return { kind: "decided", record: settled.value }; }