import { z } from "zod"; import { canonicalJson, isDiagnosticToken, iterateReviewPlan, matchesExecutedReviewNode, snapshotDiagnosticJson, verifyAnalysisReference, type AnalysisReference, type CompiledReviewPlan, type JsonValue, type ReviewNodeResult, type ReviewPlanCache, type ReviewPlanRun, } from "@actuarial-ts/core"; import { parseReviewPlan } from "./reviewPlanContracts.js"; import { parseReviewBoundary } from "./reviewBoundary.js"; import { analysisReferenceSchema } from "./reviewContracts.js"; export const REVIEW_CHECKPOINT_CONTRACT_VERSION = "actuarial-review-checkpoint/1" as const; export const REVIEW_EXECUTION_LIMITS = Object.freeze({ maximumAttemptedNodes: 256, maximumCheckpointCharacters: 100_000_000 }); export interface ReviewCheckpointKey { readonly plan: AnalysisReference; readonly node: string; readonly dependencyIdentity: string; } export interface ReviewNodeCheckpoint { readonly contractVersion: typeof REVIEW_CHECKPOINT_CONTRACT_VERSION; readonly key: ReviewCheckpointKey; readonly result: ReviewNodeResult; } /** * Host-owned, tenant-scoped storage. putIfAbsent must be atomic and must never replace an existing * value. read must observe committed writes. A thrown write may have committed; the runner queries * the same key before reporting its outcome. Fingerprints are lookup keys, not authentication. */ export interface ReviewCheckpointStore { read(key: ReviewCheckpointKey): Promise; putIfAbsent(key: ReviewCheckpointKey, checkpoint: ReviewNodeCheckpoint): Promise; } export interface ReviewCheckpointReceipt { readonly key: ReviewCheckpointKey; readonly read: "not-requested" | "missing" | "matched" | "conflict" | "failed"; readonly write: "not-requested" | "confirmed" | "outcome-unknown" | "conflict"; readonly acknowledgement: "received" | "failed" | null; readonly verification: "not-applicable" | "current-sdk-execution" | "verified-memory"; readonly retainedEvidence: "not-applicable" | "within-limit" | "exceeded"; } export interface ReviewExecutionStep { readonly calculation: ReviewPlanRun["nodes"][number]; readonly checkpoint: ReviewCheckpointReceipt; readonly progress: { readonly kind: "review-node-completed"; readonly completedNodes: number; readonly totalNodes: number; readonly remainingNodes: number; }; } export interface ReviewExecutionLimits { readonly maximumAttemptedNodes: number; readonly maximumCheckpointCharacters: number; } export interface ReviewExecutionOptions { readonly checkpointFailure: "stop" | "continue"; readonly store?: ReviewCheckpointStore; readonly cache?: ReviewPlanCache; readonly signal?: AbortSignal; readonly limits?: ReviewExecutionLimits; /** Checked before each node. Cancellation never interrupts a synchronous mathematical kernel. */ readonly cancelled?: () => boolean | Promise; /** Hosts may yield to their event loop or worker scheduler between nodes. */ readonly yieldControl?: () => Promise; readonly onProgress?: (step: ReviewExecutionStep) => void | Promise; } export interface ReviewExecutionResult { readonly plan: CompiledReviewPlan; readonly state: "finished" | "cancelled" | "stopped"; readonly reason: "CHECKPOINT_UNRESOLVED" | "HOST_CALLBACK_FAILED" | "RESOURCE_LIMIT_EXCEEDED" | null; readonly steps: readonly ReviewExecutionStep[]; readonly remaining: readonly string[]; /** Present only when every planned node has been attempted, including failed/blocked operations. */ readonly run: ReviewPlanRun | null; readonly persistence: { readonly scope: "completed-nodes-attempted-in-this-execution"; readonly status: "not-requested" | "confirmed" | "incomplete" | "uncertain" | "conflict"; }; readonly assurance: { readonly restoredCalculations: "compared-with-current-process-execution"; readonly independentVerification: "not-performed"; readonly storageAuthenticity: "host-responsibility"; readonly publication: "not-requested"; }; } const checkpointSchema = z.object({ contractVersion: z.literal(REVIEW_CHECKPOINT_CONTRACT_VERSION), key: z.object({ plan: analysisReferenceSchema, node: z.string(), dependencyIdentity: z.string() }).strict(), result: z.unknown(), }).strict(); const executionLimitsSchema = z.object({ maximumAttemptedNodes: z.number().int().positive().max(REVIEW_EXECUTION_LIMITS.maximumAttemptedNodes), maximumCheckpointCharacters: z.number().int().positive().max(REVIEW_EXECUTION_LIMITS.maximumCheckpointCharacters), }).strict(); function matchesCheckpoint(saved: unknown, expected: ReviewNodeCheckpoint): boolean { try { const parsed = parseReviewBoundary(checkpointSchema, saved), left = parsed.key, right = expected.key; return left.node === right.node && left.dependencyIdentity === right.dependencyIdentity && left.plan.kind === right.plan.kind && left.plan.id === right.plan.id && left.plan.version === right.plan.version && left.plan.contentIdentity === right.plan.contentIdentity && matchesExecutedReviewNode(expected.result, parsed.result); } catch { return false; } } async function checkpointNode(plan: CompiledReviewPlan, entry: ReviewPlanRun["nodes"][number], maximumCheckpointCharacters: number, store?: ReviewCheckpointStore): Promise { const key = snapshotDiagnosticJson({ plan: plan.reference, node: entry.result.node.id, dependencyIdentity: entry.result.dependencyIdentity }); const receipt: ReviewCheckpointReceipt = { key, read: "not-requested", write: "not-requested", acknowledgement: null, verification: "not-applicable", retainedEvidence: "not-applicable" }; if (!store || entry.result.status !== "completed") return receipt; const checkpoint: ReviewNodeCheckpoint = Object.freeze({ contractVersion: REVIEW_CHECKPOINT_CONTRACT_VERSION, key, result: entry.result }); if (canonicalJson(checkpoint).length > maximumCheckpointCharacters) return { ...receipt, retainedEvidence: "exceeded" }; const bounded = { ...receipt, retainedEvidence: "within-limit" as const }; const verification = entry.reuse === "verified-memory" ? "verified-memory" as const : "current-sdk-execution" as const; let saved: unknown; try { saved = await store.read(key); } catch { return { ...bounded, read: "failed" }; } if (saved !== undefined) return matchesCheckpoint(saved, checkpoint) ? { ...bounded, read: "matched", verification } : { ...bounded, read: "conflict" }; let acknowledgement: ReviewCheckpointReceipt["acknowledgement"] = "received"; try { await store.putIfAbsent(key, checkpoint); } catch { acknowledgement = "failed"; } // Query even after a successful acknowledgement: a calculation is not a durable save receipt. try { saved = await store.read(key); } catch { return { ...bounded, read: "missing", write: "outcome-unknown", acknowledgement }; } if (saved === undefined) return { ...bounded, read: "missing", write: "outcome-unknown", acknowledgement }; return matchesCheckpoint(saved, checkpoint) ? { ...bounded, read: "missing", write: "confirmed", acknowledgement, verification } : { ...bounded, read: "missing", write: "conflict", acknowledgement }; } const confirmed = (receipt: ReviewCheckpointReceipt) => receipt.read === "matched" || receipt.write === "confirmed"; /** * Sequential host orchestration of the pure graph. A restart recalculates saved nodes (or uses * verified in-process cache evidence), compares their complete contents and avoids duplicate saves. * No serialized checkpoint can skip mathematical verification. No mid-kernel checkpoint is claimed. */ export async function executeReviewPlan(input: unknown, options: ReviewExecutionOptions): Promise { if (!options || !["stop", "continue"].includes(options.checkpointFailure)) throw new TypeError("Declare checkpointFailure as stop or continue"); const limits = executionLimitsSchema.parse(options.limits ?? REVIEW_EXECUTION_LIMITS); const plan = parseReviewPlan(input); if (plan.order.length > limits.maximumAttemptedNodes) throw new TypeError(`Review execution exceeds maximumAttemptedNodes ${limits.maximumAttemptedNodes}`); const execution = iterateReviewPlan(plan.plan, { cache: options.cache }); const steps: ReviewExecutionStep[] = []; let state: ReviewExecutionResult["state"] = "finished", reason: ReviewExecutionResult["reason"] = null, run: ReviewPlanRun | null = null; try { for (const _id of plan.order) { try { await options.yieldControl?.(); if (options.signal?.aborted || await options.cancelled?.()) { state = "cancelled"; break; } } catch { state = "stopped"; reason = "HOST_CALLBACK_FAILED"; break; } const next = execution.next(); if (next.done) throw new Error("Review execution ended before its compiled order"); const checkpoint = await checkpointNode(plan, next.value, limits.maximumCheckpointCharacters, options.store); const completedNodes = steps.length + 1; const step = Object.freeze({ calculation: next.value, checkpoint: snapshotDiagnosticJson(checkpoint), progress: Object.freeze({ kind: "review-node-completed" as const, completedNodes, totalNodes: plan.order.length, remainingNodes: plan.order.length - completedNodes }) }); steps.push(step); try { await options.onProgress?.(step); } catch { state = "stopped"; reason = "HOST_CALLBACK_FAILED"; break; } if (options.store && next.value.result.status === "completed" && !confirmed(checkpoint) && options.checkpointFailure === "stop") { state = "stopped"; reason = checkpoint.retainedEvidence === "exceeded" ? "RESOURCE_LIMIT_EXCEEDED" : "CHECKPOINT_UNRESOLVED"; break; } } if (steps.length === plan.order.length) { const last = execution.next(); if (!last.done) throw new Error("Review execution exceeded its compiled order"); run = last.value; } } finally { if (run === null) execution.return(undefined as never); } const receipts = steps.filter((step) => step.calculation.result.status === "completed").map((step) => step.checkpoint); const persistence: ReviewExecutionResult["persistence"]["status"] = !options.store ? "not-requested" : receipts.some((receipt) => receipt.read === "conflict" || receipt.write === "conflict") ? "conflict" : receipts.some((receipt) => receipt.write === "outcome-unknown") ? "uncertain" : receipts.length === 0 || receipts.some((receipt) => !confirmed(receipt)) ? "incomplete" : "confirmed"; return Object.freeze({ plan, state, reason, steps: Object.freeze(steps), remaining: Object.freeze(plan.order.slice(steps.length)), run, persistence: Object.freeze({ scope: "completed-nodes-attempted-in-this-execution", status: persistence }), assurance: Object.freeze({ restoredCalculations: "compared-with-current-process-execution", independentVerification: "not-performed", storageAuthenticity: "host-responsibility", publication: "not-requested" }), }); } export const REVIEW_ARTIFACT_LIFECYCLE_CONTRACT_VERSION = "actuarial-review-artifact-lifecycle/1" as const; export const REVIEW_ARTIFACT_LIFECYCLE_LIMITS = Object.freeze({ maximumInputCharacters: 120_000_000, maximumArtifactCharacters: 120_000_000, maximumPublicationReceiptCharacters: 1_000_000, }); export interface ReviewArtifactKey { readonly snapshot: AnalysisReference; readonly destination: { readonly id: string; readonly version: string }; } export interface ReviewArtifactRecord { readonly contractVersion: typeof REVIEW_ARTIFACT_LIFECYCLE_CONTRACT_VERSION; readonly key: ReviewArtifactKey; readonly artifact: Readonly>; readonly state: "saved" | "published"; readonly publication: JsonValue | null; } export interface ReviewArtifactLifecycleRequest { readonly contractVersion: typeof REVIEW_ARTIFACT_LIFECYCLE_CONTRACT_VERSION; readonly artifact: Readonly>; readonly destination: { readonly id: string; readonly version: string }; readonly action: "compute-only" | "save" | "save-and-publish"; readonly limits: { readonly [K in keyof typeof REVIEW_ARTIFACT_LIFECYCLE_LIMITS]: number }; } /** * Host-owned durable storage and publication. Both mutations must be idempotent by key. A thrown * call may have committed, so callers always query the same key before deciding the outcome. * publishIfSaved must refuse a different artifact and retain a host receipt when it publishes. */ export interface ReviewArtifactStore { read(key: ReviewArtifactKey): Promise; saveIfAbsent(key: ReviewArtifactKey, record: ReviewArtifactRecord): Promise; publishIfSaved(key: ReviewArtifactKey): Promise; } export type ReviewArtifactLifecycleState = "computed" | "save-pending" | "saved" | "publication-pending" | "published" | "failed" | "cancelled"; export interface ReviewArtifactLifecycleEvent { readonly kind: "review-artifact-lifecycle"; readonly sequence: number; readonly state: ReviewArtifactLifecycleState; readonly key: ReviewArtifactKey; } export interface ReviewArtifactLifecycleResult { readonly key: ReviewArtifactKey; readonly state: "computed" | "saved" | "published" | "failed" | "cancelled"; readonly reason: "HOST_CALLBACK_FAILED" | "HOST_READ_FAILED" | "SAVE_NOT_CONFIRMED" | "SAVE_OUTCOME_UNKNOWN" | "PUBLICATION_NOT_CONFIRMED" | "PUBLICATION_OUTCOME_UNKNOWN" | "ARTIFACT_CONFLICT" | null; readonly events: readonly ReviewArtifactLifecycleEvent[]; readonly record: ReviewArtifactRecord | null; readonly persistence: "not-requested" | "confirmed" | "unknown" | "conflict"; readonly publication: "not-requested" | "confirmed" | "not-confirmed" | "unknown" | "conflict"; readonly assurance: { readonly artifactIdentity: "verified-from-complete-content"; readonly storageAuthenticity: "host-responsibility"; readonly publicationIdempotency: "host-contract-by-snapshot-and-destination"; }; } export interface ReviewArtifactLifecycleOptions { readonly store: ReviewArtifactStore; readonly signal?: AbortSignal; readonly cancelled?: () => boolean | Promise; readonly onProgress?: (event: ReviewArtifactLifecycleEvent) => void | Promise; } const token = z.string().refine(isDiagnosticToken, "Expected a valid nonempty identifier"); const artifactLifecycleLimitsSchema = z.object({ maximumInputCharacters: z.number().int().positive().max(REVIEW_ARTIFACT_LIFECYCLE_LIMITS.maximumInputCharacters), maximumArtifactCharacters: z.number().int().positive().max(REVIEW_ARTIFACT_LIFECYCLE_LIMITS.maximumArtifactCharacters), maximumPublicationReceiptCharacters: z.number().int().positive().max(REVIEW_ARTIFACT_LIFECYCLE_LIMITS.maximumPublicationReceiptCharacters), }).strict(); const artifactLifecycleRequestSchema = z.object({ contractVersion: z.literal(REVIEW_ARTIFACT_LIFECYCLE_CONTRACT_VERSION), artifact: z.record(z.string(), z.unknown()), destination: z.object({ id: token, version: token }).strict(), action: z.enum(["compute-only", "save", "save-and-publish"]), limits: artifactLifecycleLimitsSchema, }).strict() as z.ZodType; const artifactKeySchema = z.object({ snapshot: analysisReferenceSchema, destination: z.object({ id: token, version: token }).strict() }).strict(); const artifactRecordSchema = z.object({ contractVersion: z.literal(REVIEW_ARTIFACT_LIFECYCLE_CONTRACT_VERSION), key: artifactKeySchema, artifact: z.record(z.string(), z.unknown()), state: z.enum(["saved", "published"]), publication: z.unknown().nullable(), }).strict(); type ArtifactRead = { readonly kind: "missing" } | { readonly kind: "failed" } | { readonly kind: "conflict" } | { readonly kind: "matched"; readonly record: ReviewArtifactRecord }; function parseArtifactRecord(value: unknown, expected: ReviewArtifactRecord, maximumPublicationReceiptCharacters: number): ReviewArtifactRecord | null { try { const parsed = parseReviewBoundary(artifactRecordSchema, value) as ReviewArtifactRecord; if (parsed.state === "saved" && parsed.publication !== null || parsed.state === "published" && parsed.publication === null) return null; if (parsed.publication !== null && canonicalJson(parsed.publication).length > maximumPublicationReceiptCharacters) return null; if (canonicalJson(parsed.key) !== canonicalJson(expected.key) || canonicalJson(parsed.artifact) !== canonicalJson(expected.artifact)) return null; return snapshotDiagnosticJson(parsed); } catch { return null; } } async function readArtifact(store: ReviewArtifactStore, expected: ReviewArtifactRecord, maximumPublicationReceiptCharacters: number): Promise { let value: unknown; try { value = await store.read(expected.key); } catch { return { kind: "failed" }; } if (value === undefined) return { kind: "missing" }; const record = parseArtifactRecord(value, expected, maximumPublicationReceiptCharacters); return record === null ? { kind: "conflict" } : { kind: "matched", record }; } /** * Coordinates a computed artifact with host-owned save and publication effects. It never infers * review approval and cannot attest an external destination. Cancellation is observed only between * host calls; a host must use its own worker/process boundary to interrupt synchronous work. */ export async function executeReviewArtifactLifecycle(input: unknown, options: ReviewArtifactLifecycleOptions): Promise { if (!options?.store) throw new TypeError("A host artifact store is required"); const request = parseReviewBoundary(artifactLifecycleRequestSchema, input); if (canonicalJson(request).length > request.limits.maximumInputCharacters) throw new TypeError("Review artifact lifecycle request exceeds maximumInputCharacters"); if (canonicalJson(request.artifact).length > request.limits.maximumArtifactCharacters) throw new TypeError("Review artifact exceeds maximumArtifactCharacters"); const reference = analysisReferenceSchema.parse(request.artifact.reference); const { reference: _reference, ...content } = request.artifact; verifyAnalysisReference(reference, content); const key = snapshotDiagnosticJson({ snapshot: reference, destination: request.destination }); const artifact = snapshotDiagnosticJson(request.artifact) as Readonly>; const expected = Object.freeze({ contractVersion: REVIEW_ARTIFACT_LIFECYCLE_CONTRACT_VERSION, key, artifact, state: "saved" as const, publication: null }); const events: ReviewArtifactLifecycleEvent[] = []; const assurance = Object.freeze({ artifactIdentity: "verified-from-complete-content" as const, storageAuthenticity: "host-responsibility" as const, publicationIdempotency: "host-contract-by-snapshot-and-destination" as const }); const result = (state: ReviewArtifactLifecycleResult["state"], reason: ReviewArtifactLifecycleResult["reason"], record: ReviewArtifactRecord | null, persistence: ReviewArtifactLifecycleResult["persistence"], publication: ReviewArtifactLifecycleResult["publication"]): ReviewArtifactLifecycleResult => Object.freeze({ key, state, reason, events: Object.freeze([...events]), record, persistence, publication, assurance }); const append = async (state: ReviewArtifactLifecycleState, notify = true): Promise => { const event = Object.freeze({ kind: "review-artifact-lifecycle" as const, sequence: events.length + 1, state, key }); events.push(event); if (!notify) return true; try { await options.onProgress?.(event); return true; } catch { return false; } }; const fail = async (reason: Exclude, record: ReviewArtifactRecord | null, persistence: ReviewArtifactLifecycleResult["persistence"], publication: ReviewArtifactLifecycleResult["publication"], notify = true) => { await append("failed", notify); return result("failed", reason, record, persistence, publication); }; const isCancelled = async (): Promise<"cancelled" | "failed" | null> => { if (options.signal?.aborted) return "cancelled"; try { return await options.cancelled?.() ? "cancelled" : null; } catch { return "failed"; } }; if (!await append("computed")) return fail("HOST_CALLBACK_FAILED", null, "not-requested", "not-requested", false); if (request.action === "compute-only") return result("computed", null, null, "not-requested", "not-requested"); const stop = async (record: ReviewArtifactRecord | null, persistence: ReviewArtifactLifecycleResult["persistence"]): Promise => { const state = await isCancelled(); if (state === "failed") return fail("HOST_CALLBACK_FAILED", record, persistence, "not-requested", false); if (state === "cancelled") { await append("cancelled"); return result("cancelled", null, record, persistence, "not-requested"); } return null; }; const early = await stop(null, "not-requested"); if (early) return early; let read = await readArtifact(options.store, expected, request.limits.maximumPublicationReceiptCharacters); if (read.kind === "failed") return fail("HOST_READ_FAILED", null, "unknown", "not-requested"); if (read.kind === "conflict") return fail("ARTIFACT_CONFLICT", null, "conflict", "conflict"); let record = read.kind === "matched" ? read.record : null; if (record === null) { if (!await append("save-pending")) return fail("HOST_CALLBACK_FAILED", null, "not-requested", "not-requested", false); const cancelled = await stop(null, "not-requested"); if (cancelled) return cancelled; try { await options.store.saveIfAbsent(key, expected); } catch { /* Readback determines whether a throwing write committed. */ } read = await readArtifact(options.store, expected, request.limits.maximumPublicationReceiptCharacters); if (read.kind === "failed") return fail("SAVE_OUTCOME_UNKNOWN", null, "unknown", "not-requested"); if (read.kind === "missing") return fail("SAVE_NOT_CONFIRMED", null, "unknown", "not-requested"); if (read.kind === "conflict") return fail("ARTIFACT_CONFLICT", null, "conflict", "conflict"); record = read.record; } if (record === null) throw new Error("Review artifact read completed without a record"); if (!await append("saved")) return fail("HOST_CALLBACK_FAILED", record, "confirmed", record.state === "published" ? "confirmed" : "not-requested", false); if (request.action === "save") return result(record.state, null, record, "confirmed", record.state === "published" ? "confirmed" : "not-requested"); if (record.state === "published") { if (!await append("published")) return fail("HOST_CALLBACK_FAILED", record, "confirmed", "confirmed", false); return result("published", null, record, "confirmed", "confirmed"); } const beforePublish = await stop(record, "confirmed"); if (beforePublish) return beforePublish; if (!await append("publication-pending")) return fail("HOST_CALLBACK_FAILED", record, "confirmed", "not-confirmed", false); const cancelled = await stop(record, "confirmed"); if (cancelled) return cancelled; try { await options.store.publishIfSaved(key); } catch { /* Readback determines whether a throwing publication committed. */ } read = await readArtifact(options.store, expected, request.limits.maximumPublicationReceiptCharacters); if (read.kind === "failed") return fail("PUBLICATION_OUTCOME_UNKNOWN", record, "confirmed", "unknown"); if (read.kind === "missing") return fail("PUBLICATION_OUTCOME_UNKNOWN", null, "unknown", "unknown"); if (read.kind === "conflict") return fail("ARTIFACT_CONFLICT", null, "conflict", "conflict"); record = read.record; const published = record; if (published.state !== "published") return fail("PUBLICATION_NOT_CONFIRMED", published, "confirmed", "not-confirmed"); if (!await append("published")) return fail("HOST_CALLBACK_FAILED", published, "confirmed", "confirmed", false); return result("published", null, published, "confirmed", "confirmed"); }