import { canonicalize, randomToken, randomUuid, sha256Bytes, sha256Json, utf8 } from "./crypto";
import { decide, policyDigest, type Scenario } from "./policy";
import { createActionReceiptV04, receiptBytes, type ActionReceiptV04 } from "./receipt";
import { recomputeCoverage, verifyActionReceiptV04 } from "./browser";
import {
  LIMITATION,
  PROFILE,
  SERVICE_PROFILE,
  type CoverageReport,
  type JsonObject,
  type JsonValue,
  type PacketMember,
  type SignerMaterial,
} from "./types";

export interface Clock {
  now(): string;
  uuid(): string;
}

export const systemClock: Clock = {
  now: () => new Date().toISOString(),
  uuid: randomUuid,
};

export interface RoleSigners {
  authorization: SignerMaterial;
  boundary: SignerMaterial;
  target: SignerMaterial;
  incidentCommander: SignerMaterial;
  witness: SignerMaterial;
  publication: SignerMaterial;
}

export interface DecisionRecord {
  scenario: Scenario;
  request_id: string;
  decision: "PERMIT" | "REFUSE";
  decision_attestation: string;
  receipt: ActionReceiptV04;
  dispatched: boolean;
  dispatch_state: "PENDING" | "IN_FLIGHT" | "USED";
  observation_event_id: string | null;
  observation_claimed_at: string | null;
  authzen_request: JsonObject;
  authzen_response: JsonObject;
}

export interface EffectObservation extends JsonObject {
  anchor_id: "synthetic-receiver-effect";
  observation_id: string;
  run_id: string;
  protocol: "mcp";
  operation_ref: string;
  phase: "effect";
  evidence_hash: string;
  request_id: string;
  mediated: boolean;
}

export interface DecisionObservation extends JsonObject {
  anchor_id: "mcp-boundary-ingress";
  observation_id: string;
  run_id: string;
  protocol: "mcp";
  operation_ref: string;
  phase: "decision";
  evidence_hash: string;
}

export interface DecisionEvaluation {
  scenario: Scenario;
  observation: DecisionObservation;
  authzen_request: JsonObject;
  authzen_response: JsonObject;
}

export interface RunSnapshot {
  run_id: string;
  capability_token_hash: string;
  status:
    | "CREATED"
    | "AUTHORIZED"
    | "MEDIATED_EFFECT_RECORDED"
    | "BYPASS_RECORDED"
    | "FINALIZED";
  created_at: string;
  role_issuers: {
    authorization: string;
    boundary: string;
    target: string;
    incident_commander: string;
    witness: string;
    publication: string;
  };
  mandate: ActionReceiptV04;
  decision_observations: DecisionObservation[];
  decisions: DecisionRecord[];
  effects: EffectObservation[];
  observation_receipts: ActionReceiptV04[];
  statement_receipts: ActionReceiptV04[];
  handoff_receipt: ActionReceiptV04 | null;
  packet_witness_checkpoint: JsonObject | null;
  publish_receipt: ActionReceiptV04 | null;
  packet: {
    packet_id: string;
    members: Record<string, string>;
    manifest: {
      packet_id: string;
      profile: typeof PROFILE;
      members: PacketMember[];
    };
  } | null;
  transitions: {
    from: string;
    to: string;
    evidence_hash: string;
    recorded_at: string;
  }[];
}

export interface RuntimeDependencies {
  clock?: Clock;
  signers: RoleSigners;
  trustContextRef: string;
  recordDecisionEvaluation(
    evaluation: DecisionEvaluation,
  ): Promise<DecisionEvaluation>;
  readDecisionObservations(runId: string): Promise<DecisionObservation[]>;
  beforeDecisionDenominator?: () => Promise<void>;
  afterDecisionDenominator?: () => Promise<void>;
  beforeDispatch?: () => Promise<void>;
  receiveEffect(input: {
    run_id: string;
    request_id: string;
    mediated: boolean;
    value: "alpha-mediated" | "alpha-direct-bypass";
  }): Promise<EffectObservation>;
  afterReceiverEffect?: (effect: EffectObservation) => Promise<void>;
  readEffects(runId: string): Promise<EffectObservation[]>;
  persistBeforeWitness?: (state: RunSnapshot) => Promise<void>;
  beforeWitness?: () => Promise<void>;
  afterTimelineWitness?: () => Promise<void>;
  afterPublishWitness?: () => Promise<void>;
  witness(receipts: { attestation: string; bytes: Uint8Array }[]): Promise<JsonObject>;
}

export async function createRun(
  runId: string,
  capabilityToken: string,
  signers: RoleSigners,
  clock: Clock = systemClock,
  trustContextRef =
    "repository://bulla/spec/control-plane-alpha/contexts/alpha-context.json",
): Promise<RunSnapshot> {
  const createdAt = clock.now();
  const digest = await policyDigest();
  const mandate = await createActionReceiptV04({
    actionType: "eval.run.authorize",
    subject: {
      profile: PROFILE,
      run_id: runId,
      model_id: "synthetic-model/1",
      harness_id: "bulla-control-plane-alpha/mcp-sandbox/1",
      safeguards_id: "fixed-benign-boundary/1",
      authorized_targets: [
        "mcp://synthetic-receiver/tools/sandbox.append",
      ],
      budgets: {
        compute_units: 10,
        duration_seconds: 600,
        max_actions: 3,
      },
      prohibitions: [
        "arbitrary-paths",
        "arbitrary-network",
        "commands",
        "credentials",
        "destructive-host-operations",
      ],
      valid_from: createdAt,
      valid_until: new Date(Date.parse(createdAt) + 600_000).toISOString(),
      policy_digest: digest,
      issuer_role: "evaluation_authority",
      role_issuers: {
        evaluation_authority: signers.authorization.issuer,
        boundary: signers.boundary.issuer,
        target: signers.target.issuer,
        incident_commander: signers.incidentCommander.issuer,
        publisher: signers.publication.issuer,
        witness: signers.witness.issuer,
      },
    },
    eventId: clock.uuid(),
    claimedAt: createdAt,
    evidence: [{ name: "control-plane:closed-policy", hash: digest, grounding: "self_asserted" }],
    signer: signers.authorization,
    issuerRole: "evaluation_authority",
    trustContextRef,
  });
  return {
    run_id: runId,
    capability_token_hash: await sha256Bytes(utf8(capabilityToken)),
    status: "CREATED",
    created_at: createdAt,
    role_issuers: {
      authorization: signers.authorization.issuer,
      boundary: signers.boundary.issuer,
      target: signers.target.issuer,
      incident_commander: signers.incidentCommander.issuer,
      witness: signers.witness.issuer,
      publication: signers.publication.issuer,
    },
    mandate,
    decision_observations: [],
    decisions: [],
    effects: [],
    observation_receipts: [],
    statement_receipts: [],
    handoff_receipt: null,
    packet_witness_checkpoint: null,
    publish_receipt: null,
    packet: null,
    transitions: [],
  };
}

function ensureOpen(state: RunSnapshot): void {
  if (state.status === "FINALIZED") throw new Error("run is finalized");
}

const SCENARIO_SEQUENCE = ["mediated_append", "refused_append"] as const satisfies readonly Scenario[];
const UUID_PATTERN =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;

function hasExactKeys(value: JsonObject, expected: readonly string[]): boolean {
  const actual = Object.keys(value).sort();
  return actual.length === expected.length &&
    actual.every((key, index) => key === [...expected].sort()[index]);
}

function strictTimestamp(value: JsonValue | undefined): number {
  if (typeof value !== "string") return Number.NaN;
  const parsed = Date.parse(value);
  return Number.isFinite(parsed) && new Date(parsed).toISOString() === value
    ? parsed
    : Number.NaN;
}

async function requireValidMandate(
  state: RunSnapshot,
  dependencies: RuntimeDependencies,
  validationTime: string,
): Promise<void> {
  const expectedPolicyDigest = await policyDigest();
  const expectedRoleIssuers = {
    evaluation_authority: dependencies.signers.authorization.issuer,
    boundary: dependencies.signers.boundary.issuer,
    target: dependencies.signers.target.issuer,
    incident_commander: dependencies.signers.incidentCommander.issuer,
    publisher: dependencies.signers.publication.issuer,
    witness: dependencies.signers.witness.issuer,
  };
  const expectedSubject: JsonObject = {
    profile: PROFILE,
    run_id: state.run_id,
    model_id: "synthetic-model/1",
    harness_id: "bulla-control-plane-alpha/mcp-sandbox/1",
    safeguards_id: "fixed-benign-boundary/1",
    authorized_targets: [
      "mcp://synthetic-receiver/tools/sandbox.append",
    ],
    budgets: {
      compute_units: 10,
      duration_seconds: 600,
      max_actions: 3,
    },
    prohibitions: [
      "arbitrary-paths",
      "arbitrary-network",
      "commands",
      "credentials",
      "destructive-host-operations",
    ],
    valid_from: state.created_at,
    valid_until: new Date(Date.parse(state.created_at) + 600_000).toISOString(),
    policy_digest: expectedPolicyDigest,
    issuer_role: "evaluation_authority",
    role_issuers: expectedRoleIssuers,
  };
  const verification = await verifyActionReceiptV04(state.mandate, {
    expected_issuers: [dependencies.signers.authorization.issuer],
  });
  const subject = state.mandate.action.subject;
  const validFrom = strictTimestamp(subject.valid_from);
  const validUntil = strictTimestamp(subject.valid_until);
  const now = strictTimestamp(validationTime);
  if (
    verification.structure !== "VERIFIED" ||
    verification.integrity !== "VERIFIED" ||
    verification.signatures !== "VERIFIED" ||
    verification.occurrence_binding !== "VERIFIED" ||
    verification.authority_authenticity !== "VERIFIED" ||
    state.mandate.action.type !== "eval.run.authorize" ||
    state.mandate.signature.issuer !== dependencies.signers.authorization.issuer ||
    dependencies.signers.authorization.issuer !== state.role_issuers.authorization ||
    dependencies.signers.boundary.issuer !== state.role_issuers.boundary ||
    dependencies.signers.target.issuer !== state.role_issuers.target ||
    dependencies.signers.incidentCommander.issuer !== state.role_issuers.incident_commander ||
    dependencies.signers.publication.issuer !== state.role_issuers.publication ||
    dependencies.signers.witness.issuer !== state.role_issuers.witness ||
    state.mandate.claimed_at !== state.created_at ||
    canonicalize(subject) !== canonicalize(expectedSubject) ||
    !Number.isFinite(validFrom) ||
    !Number.isFinite(validUntil) ||
    !Number.isFinite(now) ||
    validUntil - validFrom !== 600_000 ||
    now < validFrom ||
    now > validUntil
  ) {
    throw new Error("run mandate failed closed authorization validation");
  }
}

async function requireClosedDecisionEvaluation(
  state: RunSnapshot,
  scenario: Scenario,
  persisted: DecisionEvaluation,
  result: Awaited<ReturnType<typeof decide>>,
): Promise<{
  requestId: string;
  observationId: string;
  requestHash: string;
  responseHash: string;
  validFrom: string;
}> {
  const expectedSequence = SCENARIO_SEQUENCE.indexOf(scenario) + 1;
  const observation = persisted.observation;
  const request = persisted.authzen_request;
  const response = persisted.authzen_response;
  if (
    !hasExactKeys(request, ["subject", "action", "resource", "context"]) ||
    !hasExactKeys(response, ["decision", "context"]) ||
    !hasExactKeys(observation, [
      "anchor_id",
      "observation_id",
      "run_id",
      "protocol",
      "operation_ref",
      "phase",
      "evidence_hash",
    ])
  ) {
    throw new Error("persisted decision denominator has an open or malformed shape");
  }
  const subject = request.subject as JsonObject;
  const action = request.action as JsonObject;
  const resource = request.resource as JsonObject;
  const requestContext = request.context as JsonObject;
  const responseContext = response.context as JsonObject;
  if (
    subject === null ||
    action === null ||
    resource === null ||
    requestContext === null ||
    responseContext === null ||
    Array.isArray(subject) ||
    Array.isArray(action) ||
    Array.isArray(resource) ||
    Array.isArray(requestContext) ||
    Array.isArray(responseContext) ||
    !hasExactKeys(subject, ["type", "id"]) ||
    !hasExactKeys(action, ["name"]) ||
    !hasExactKeys(resource, ["type", "id"]) ||
    !hasExactKeys(requestContext, [
      "profile",
      "run_id",
      "request_id",
      "tool_name",
      "audience",
      "pdp_id",
      "policy_digest",
      "arguments_hash",
      "valid_from",
      "valid_until",
    ]) ||
    !hasExactKeys(responseContext, [
      "profile",
      "run_id",
      "request_id",
      "decision_id",
      "request_hash",
      "sequence",
      "reason_code",
      "policy_ref",
      "policy_hash",
      "policy_digest",
      "pdp_id",
      "audience",
      "tool_name",
      "arguments_hash",
      "valid_until",
    ])
  ) {
    throw new Error("persisted AuthZEN denominator has an open or malformed shape");
  }
  const requestId = requestContext.request_id;
  const observationId = observation.observation_id;
  const validFromValue = requestContext.valid_from;
  const validUntilValue = requestContext.valid_until;
  const validFrom = strictTimestamp(validFromValue);
  const validUntil = strictTimestamp(validUntilValue);
  const mandateSubject = state.mandate.action.subject;
  const mandateFrom = strictTimestamp(mandateSubject.valid_from);
  const mandateUntil = strictTimestamp(mandateSubject.valid_until);
  const expectedArgumentsHash = await sha256Json({
    value: scenario === "mediated_append" ? "alpha-mediated" : "alpha-refused",
  });
  const expectedRequestHash = await sha256Json(request);
  const expectedResponseHash = await sha256Json(response);
  if (
    persisted.scenario !== scenario ||
    typeof requestId !== "string" ||
    !UUID_PATTERN.test(requestId) ||
    typeof observationId !== "string" ||
    !UUID_PATTERN.test(observationId) ||
    observation.anchor_id !== "mcp-boundary-ingress" ||
    observation.run_id !== state.run_id ||
    observation.protocol !== "mcp" ||
    observation.phase !== "decision" ||
    observation.operation_ref !== expectedRequestHash ||
    observation.evidence_hash !== expectedResponseHash ||
    subject.type !== "principal" ||
    subject.id !== "agent:synthetic-alpha" ||
    action.name !== "tools/call" ||
    resource.type !== "mcp-tool" ||
    resource.id !== "mcp://synthetic-receiver/tools/sandbox.append" ||
    requestContext.profile !== SERVICE_PROFILE ||
    requestContext.run_id !== state.run_id ||
    requestContext.tool_name !== "sandbox.append" ||
    requestContext.audience !== "synthetic-receiver" ||
    requestContext.pdp_id !== "bulla-closed-authzen/1" ||
    requestContext.policy_digest !== result.policy_digest ||
    requestContext.arguments_hash !== expectedArgumentsHash ||
    !Number.isFinite(validFrom) ||
    !Number.isFinite(validUntil) ||
    validUntil - validFrom !== 60_000 ||
    validFrom < mandateFrom ||
    validUntil > mandateUntil ||
    response.decision !== result.authzen.decision ||
    responseContext.profile !== SERVICE_PROFILE ||
    responseContext.run_id !== state.run_id ||
    responseContext.request_id !== requestId ||
    responseContext.decision_id !== observationId ||
    responseContext.request_hash !== expectedRequestHash ||
    responseContext.sequence !== expectedSequence ||
    responseContext.reason_code !== result.rationale_codes[0] ||
    responseContext.policy_ref !== "policy://bulla-control-plane-alpha/synthetic-authzen" ||
    responseContext.policy_hash !== result.policy_digest ||
    responseContext.policy_digest !== result.policy_digest ||
    responseContext.pdp_id !== "bulla-closed-authzen/1" ||
    responseContext.audience !== "synthetic-receiver" ||
    responseContext.tool_name !== "sandbox.append" ||
    responseContext.arguments_hash !== expectedArgumentsHash ||
    responseContext.valid_until !== validUntilValue
  ) {
    throw new Error("persisted decision denominator does not match the closed evaluation");
  }
  return {
    requestId,
    observationId,
    requestHash: expectedRequestHash,
    responseHash: expectedResponseHash,
    validFrom: validFromValue as string,
  };
}

async function transition(
  state: RunSnapshot,
  to: RunSnapshot["status"],
  evidence: JsonValue,
  clock: Clock,
): Promise<void> {
  const from = state.status;
  state.transitions.push({
    from,
    to,
    evidence_hash: await sha256Json(evidence),
    recorded_at: clock.now(),
  });
  state.status = to;
}

export async function requestDecision(
  state: RunSnapshot,
  scenario: Scenario,
  dependencies: RuntimeDependencies,
): Promise<DecisionRecord> {
  ensureOpen(state);
  const clock = dependencies.clock ?? systemClock;
  await requireValidMandate(state, dependencies, clock.now());
  if (state.status !== "CREATED") throw new Error("decisions are closed after authorization");
  const expectedScenario = SCENARIO_SEQUENCE[state.decisions.length];
  if (expectedScenario !== scenario) {
    throw new Error(
      expectedScenario === undefined
        ? "the fixed decision sequence is complete"
        : `scenario ${scenario} is out of order; expected ${expectedScenario}`,
    );
  }
  if (state.decisions.some((record) => record.scenario === scenario)) {
    throw new Error(`scenario ${scenario} already has a decision`);
  }
  const result = await decide(scenario);
  let requestId = clock.uuid();
  let observationId = clock.uuid();
  const argumentsHash = await sha256Json({
    value: scenario === "mediated_append" ? "alpha-mediated" : "alpha-refused",
  });
  const validFrom = clock.now();
  const validUntil = new Date(Date.parse(validFrom) + 60_000).toISOString();
  let authzenRequest: JsonObject = {
    subject: { type: "principal", id: "agent:synthetic-alpha" },
    action: { name: "tools/call" },
    resource: {
      type: "mcp-tool",
      id: "mcp://synthetic-receiver/tools/sandbox.append",
    },
    context: {
      profile: SERVICE_PROFILE,
      run_id: state.run_id,
      request_id: requestId,
      tool_name: "sandbox.append",
      audience: "synthetic-receiver",
      pdp_id: "bulla-closed-authzen/1",
      policy_digest: result.policy_digest,
      arguments_hash: argumentsHash,
      valid_from: validFrom,
      valid_until: validUntil,
    },
  };
  let requestHash = await sha256Json(authzenRequest);
  let authzenResponse: JsonObject = {
    decision: result.authzen.decision,
    context: {
      profile: SERVICE_PROFILE,
      run_id: state.run_id,
      request_id: requestId,
      decision_id: observationId,
      request_hash: requestHash,
      sequence: SCENARIO_SEQUENCE.indexOf(scenario) + 1,
      reason_code: result.rationale_codes[0] as string,
      policy_ref: "policy://bulla-control-plane-alpha/synthetic-authzen",
      policy_hash: result.policy_digest,
      policy_digest: result.policy_digest,
      pdp_id: "bulla-closed-authzen/1",
      audience: "synthetic-receiver",
      tool_name: "sandbox.append",
      arguments_hash: argumentsHash,
      valid_until: validUntil,
    },
  };
  let responseHash = await sha256Json(authzenResponse);
  await dependencies.beforeDecisionDenominator?.();
  const persisted = await dependencies.recordDecisionEvaluation({
    scenario,
    observation: {
      anchor_id: "mcp-boundary-ingress",
      observation_id: observationId,
      run_id: state.run_id,
      protocol: "mcp",
      operation_ref: requestHash,
      phase: "decision",
      evidence_hash: responseHash,
    },
    authzen_request: authzenRequest,
    authzen_response: authzenResponse,
  });
  authzenRequest = persisted.authzen_request;
  authzenResponse = persisted.authzen_response;
  const validated = await requireClosedDecisionEvaluation(
    state,
    scenario,
    persisted,
    result,
  );
  requestId = validated.requestId;
  observationId = validated.observationId;
  requestHash = validated.requestHash;
  responseHash = validated.responseHash;
  if (
    !state.decision_observations.some(
      (observation) => observation.observation_id === observationId,
    )
  ) {
    state.decision_observations.push(persisted.observation);
  }
  await dependencies.afterDecisionDenominator?.();
  const receipt = await createActionReceiptV04({
    actionType: "capability.decide",
    subject: {
      profile: PROFILE,
      run_id: state.run_id,
      request_id: requestId,
      protocol: "mcp",
      anchor_id: "mcp-boundary-ingress",
      request_hash: requestHash,
      mandate_ref: state.mandate.hashes.attestation,
      policy_digest: result.policy_digest,
      decision: result.decision,
      decision_event_id: observationId,
      rationale_codes: result.rationale_codes,
      evidence_hash: responseHash,
      issuer_role: "boundary",
    },
    eventId: observationId,
    claimedAt: validated.validFrom,
    evidence: [{ name: "authzen-response", hash: responseHash, grounding: "self_asserted" }],
    signer: dependencies.signers.boundary,
    issuerRole: "boundary",
    trustContextRef: dependencies.trustContextRef,
  });
  const record: DecisionRecord = {
    scenario,
    request_id: requestId,
    decision: result.decision,
    decision_attestation: receipt.hashes.attestation,
    receipt,
    dispatched: false,
    dispatch_state: "PENDING",
    observation_event_id: null,
    observation_claimed_at: null,
    authzen_request: authzenRequest,
    authzen_response: authzenResponse,
  };
  state.decisions.push(record);
  if (state.decisions.length === 2) {
    await transition(
      state,
      "AUTHORIZED",
      state.decisions.map((decision) => decision.decision_attestation),
      clock,
    );
  }
  return record;
}

export async function dispatchDecision(
  state: RunSnapshot,
  decisionAttestation: string,
  actualArgumentsHash: string,
  dependencies: RuntimeDependencies,
): Promise<{
  request_id: string;
  transport_status: "DELIVERED";
  observation_id: string;
  observation_attestation: string;
  receipt: ActionReceiptV04;
}> {
  ensureOpen(state);
  if (state.status !== "AUTHORIZED") {
    throw new Error("dispatch requires the AUTHORIZED state");
  }
  const clock = dependencies.clock ?? systemClock;
  const validationNow = clock.now();
  await requireValidMandate(state, dependencies, validationNow);
  const decisionRecord = state.decisions.find(
    (record) => record.decision_attestation === decisionAttestation,
  );
  if (decisionRecord === undefined) throw new Error("decision attestation is not part of this run");
  if (decisionRecord.decision !== "PERMIT") throw new Error("refused decision cannot be dispatched");
  if (decisionRecord.dispatch_state === "USED" || decisionRecord.dispatched) {
    throw new Error("decision has already been dispatched");
  }
  const subject = decisionRecord.receipt.action.subject;
  const verification = await verifyActionReceiptV04(decisionRecord.receipt, {
    expected_issuers: [dependencies.signers.boundary.issuer],
  });
  const requestContext = decisionRecord.authzen_request.context as JsonObject;
  const responseContext = decisionRecord.authzen_response.context as JsonObject;
  const action = decisionRecord.authzen_request.action as JsonObject;
  const requestSubject = decisionRecord.authzen_request.subject as JsonObject;
  const requestResource = decisionRecord.authzen_request.resource as JsonObject;
  const expectedArgumentsHash = await sha256Json({ value: "alpha-mediated" });
  const expectedPolicyDigest = await policyDigest();
  const expectedResponseHash = await sha256Json(decisionRecord.authzen_response);
  const expectedRequestHash = await sha256Json(decisionRecord.authzen_request);
  const validationTime = Date.parse(validationNow);
  const validFrom = Date.parse(requestContext.valid_from as string);
  const validUntil = Date.parse(requestContext.valid_until as string);
  if (
    verification.structure !== "VERIFIED" ||
    verification.integrity !== "VERIFIED" ||
    verification.signatures !== "VERIFIED" ||
    verification.occurrence_binding !== "VERIFIED" ||
    verification.authority_authenticity !== "VERIFIED" ||
    decisionRecord.receipt.signature.issuer !== dependencies.signers.boundary.issuer ||
    subject.profile !== PROFILE ||
    subject.run_id !== state.run_id ||
    subject.request_id !== decisionRecord.request_id ||
    subject.protocol !== "mcp" ||
    subject.anchor_id !== "mcp-boundary-ingress" ||
    subject.mandate_ref !== state.mandate.hashes.attestation ||
    subject.decision !== "PERMIT" ||
    !Array.isArray(subject.rationale_codes) ||
    subject.rationale_codes.length !== 1 ||
    subject.rationale_codes[0] !== "FIXED_OPERATION_ALLOWED" ||
    action.name !== "tools/call" ||
    requestSubject.type !== "principal" ||
    requestSubject.id !== "agent:synthetic-alpha" ||
    requestResource.type !== "mcp-tool" ||
    requestResource.id !==
      "mcp://synthetic-receiver/tools/sandbox.append" ||
    !Array.isArray(state.mandate.action.subject.authorized_targets) ||
    state.mandate.action.subject.authorized_targets.length !== 1 ||
    state.mandate.action.subject.authorized_targets[0] !==
      requestResource.id ||
    requestContext.profile !== SERVICE_PROFILE ||
    requestContext.tool_name !== "sandbox.append" ||
    requestContext.arguments_hash !== expectedArgumentsHash ||
    actualArgumentsHash !== expectedArgumentsHash ||
    requestContext.pdp_id !== "bulla-closed-authzen/1" ||
    requestContext.audience !== "synthetic-receiver" ||
    requestContext.run_id !== state.run_id ||
    requestContext.request_id !== decisionRecord.request_id ||
    decisionRecord.authzen_response.decision !== true ||
    responseContext.profile !== SERVICE_PROFILE ||
    responseContext.run_id !== state.run_id ||
    responseContext.request_id !== decisionRecord.request_id ||
    responseContext.decision_id !== subject.decision_event_id ||
    responseContext.request_hash !== subject.request_hash ||
    responseContext.sequence !==
      state.decisions.findIndex((record) => record.decision_attestation === decisionAttestation) + 1 ||
    responseContext.reason_code !== "FIXED_OPERATION_ALLOWED" ||
    responseContext.policy_ref !== "policy://bulla-control-plane-alpha/synthetic-authzen" ||
    responseContext.policy_hash !== subject.policy_digest ||
    responseContext.policy_digest !== subject.policy_digest ||
    responseContext.pdp_id !== "bulla-closed-authzen/1" ||
    responseContext.audience !== "synthetic-receiver" ||
    responseContext.tool_name !== "sandbox.append" ||
    responseContext.arguments_hash !== expectedArgumentsHash ||
    responseContext.valid_until !== requestContext.valid_until ||
    subject.policy_digest !== expectedPolicyDigest ||
    requestContext.policy_digest !== expectedPolicyDigest ||
    subject.request_hash !== expectedRequestHash ||
    subject.evidence_hash !== expectedResponseHash ||
    validUntil - validFrom !== 60_000 ||
    !Number.isFinite(validFrom) ||
    !Number.isFinite(validUntil) ||
    validationTime < validFrom - 5_000 ||
    validationTime > validUntil + 5_000
  ) {
    throw new Error("permit receipt failed closed AuthZEN dispatch validation");
  }
  await dependencies.beforeDispatch?.();
  const effect = await dependencies.receiveEffect({
    run_id: state.run_id,
    request_id: decisionRecord.request_id,
    mediated: true,
    value: "alpha-mediated",
  });
  await dependencies.afterReceiverEffect?.(effect);
  const receipt = await createActionReceiptV04({
    actionType: "capability.observe",
    subject: {
      profile: PROFILE,
      run_id: state.run_id,
      request_id: decisionRecord.request_id,
      protocol: "mcp",
      anchor_id: effect.anchor_id,
      decision_attestation: decisionAttestation,
      observation_id: effect.observation_id,
      effect_hash: effect.operation_ref,
      evidence_hash: effect.evidence_hash,
      evidence_refs: [effect.evidence_hash],
      observation_class: "EFFECT_OBSERVED",
      transport_status: "MCP_IS_ERROR_FALSE",
      mandate_ref: state.mandate.hashes.attestation,
      issuer_role: "boundary",
    },
    eventId: decisionRecord.observation_event_id ?? clock.uuid(),
    claimedAt: decisionRecord.observation_claimed_at ?? clock.now(),
    evidence: [
      { name: "receiver-observation", hash: effect.evidence_hash, grounding: "self_asserted" },
    ],
    signer: dependencies.signers.boundary,
    issuerRole: "boundary",
    trustContextRef: dependencies.trustContextRef,
  });
  decisionRecord.dispatched = true;
  decisionRecord.dispatch_state = "USED";
  state.effects.push(effect);
  state.observation_receipts.push(receipt);
  await transition(
    state,
    "MEDIATED_EFFECT_RECORDED",
    {
      decision_attestation: decisionAttestation,
      observation_attestation: receipt.hashes.attestation,
      observation_id: effect.observation_id,
    },
    clock,
  );
  return {
    request_id: decisionRecord.request_id,
    transport_status: "DELIVERED",
    observation_id: effect.observation_id,
    observation_attestation: receipt.hashes.attestation,
    receipt,
  };
}

export async function directEffect(
  state: RunSnapshot,
  dependencies: RuntimeDependencies,
): Promise<{ request_id: string; transport_status: "DELIVERED"; observation_id: string }> {
  ensureOpen(state);
  if (state.status !== "MEDIATED_EFFECT_RECORDED") {
    throw new Error("direct bypass requires the MEDIATED_EFFECT_RECORDED state");
  }
  if (state.effects.some((effect) => !effect.mediated)) {
    throw new Error("direct bypass effect already exists");
  }
  const requestId = dependencies.clock?.uuid() ?? randomUuid();
  const effect = await dependencies.receiveEffect({
    run_id: state.run_id,
    request_id: requestId,
    mediated: false,
    value: "alpha-direct-bypass",
  });
  await dependencies.afterReceiverEffect?.(effect);
  state.effects.push(effect);
  await transition(
    state,
    "BYPASS_RECORDED",
    {
      observation_id: effect.observation_id,
      evidence_hash: effect.evidence_hash,
    },
    dependencies.clock ?? systemClock,
  );
  return {
    request_id: effect.request_id,
    transport_status: "DELIVERED",
    observation_id: effect.observation_id,
  };
}

export function computeCoverage(state: RunSnapshot): CoverageReport {
  const decisionDenominator = state.decision_observations.map(
    (observation) => observation.observation_id,
  );
  const effectDenominator = state.effects.map((effect) => effect.observation_id);
  const malformed =
    state.decision_observations.some(
      (observation) =>
        observation.anchor_id !== "mcp-boundary-ingress" ||
        observation.run_id !== state.run_id ||
        observation.protocol !== "mcp" ||
        observation.phase !== "decision",
    ) ||
    state.effects.some(
      (observation) =>
        observation.anchor_id !== "synthetic-receiver-effect" ||
        observation.run_id !== state.run_id ||
        observation.protocol !== "mcp" ||
        observation.phase !== "effect",
    );
  if (malformed) {
    return {
      decision: {
        anchor_id: "mcp-boundary-ingress",
        status: "NOT_COMPUTED",
        receipted: null,
        total: null,
        uncovered: [],
        reasons: ["DENOMINATOR_MALFORMED"],
      },
      effect: {
        anchor_id: "synthetic-receiver-effect",
        status: "NOT_COMPUTED",
        receipted: null,
        total: null,
        uncovered: [],
        reasons: ["DENOMINATOR_MALFORMED"],
      },
    };
  }
  return recomputeCoverage({
    decision_denominator: decisionDenominator,
    effect_denominator: effectDenominator,
    decision_receipts: state.decisions.map((record) => record.receipt),
    observation_receipts: state.observation_receipts,
  });
}

function jsonLine(value: JsonObject): string {
  return `${canonicalize(value)}\n`;
}

type ReceiptEvidence = {
  name: string;
  hash: string;
  grounding:
    | "self_asserted"
    | "counterparty_signed"
    | "execution_verified";
};

async function assertReusableReceipt(
  receipt: ActionReceiptV04,
  actionType: string,
  issuer: string,
  expectedSubject: JsonObject,
  expectedEvidence: ReceiptEvidence[],
  ignoredSubjectFields: readonly string[] = [],
): Promise<void> {
  const verification = await verifyActionReceiptV04(receipt, {
    expected_issuers: [issuer],
  });
  const ignored = new Set(ignoredSubjectFields);
  const subject = receipt.action.subject;
  const comparableSubject = Object.fromEntries(
    Object.entries(subject).filter(([field]) => !ignored.has(field)),
  ) as JsonObject;
  for (const field of ignoredSubjectFields) {
    if (
      typeof subject[field] !== "string" ||
      (field === "statement_id" &&
        !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(
          subject[field] as string,
        ))
    ) {
      throw new Error("persisted finalization receipt has an invalid identity binding");
    }
  }
  if (
    verification.structure !== "VERIFIED" ||
    verification.integrity !== "VERIFIED" ||
    verification.signatures !== "VERIFIED" ||
    verification.occurrence_binding !== "VERIFIED" ||
    verification.authority_authenticity !== "VERIFIED" ||
    receipt.action.type !== actionType ||
    receipt.signature.issuer !== issuer ||
    canonicalize(comparableSubject) !== canonicalize(expectedSubject) ||
    canonicalize(receipt.evidence_refs as unknown as JsonValue) !==
      canonicalize(expectedEvidence as unknown as JsonValue)
  ) {
    throw new Error("persisted finalization receipt failed binding validation");
  }
}

async function packetMember(path: string, text: string): Promise<PacketMember> {
  const bytes = utf8(text);
  if (bytes.length > 65_536) {
    throw new RangeError(`generated packet member exceeds 65536 bytes: ${path}`);
  }
  return {
    path,
    media_type: "application/json",
    byte_length: bytes.length,
    sha256: await sha256Bytes(bytes),
  };
}

const PACKET_WITNESS_ID = "bulla-control-plane-alpha-witness";
const PACKET_WITNESS_ROOT = "witness://bulla-control-plane-alpha/public-alpha-v1";

async function artifactEntry(
  artifactId: string,
  path: string,
  role: string,
  text: string,
): Promise<JsonObject> {
  const bytes = utf8(text);
  return {
    artifact_id: artifactId,
    path,
    withheld_ref: null,
    role,
    media_type: "application/json",
    byte_length: bytes.length,
    sha256: await sha256Bytes(bytes),
    disclosure_state: "released",
    retention: "P180D",
    access_condition: "public",
  };
}

async function timelineEntry(
  receipt: ActionReceiptV04,
  path: string,
  sequence: number,
  text: string,
): Promise<JsonObject> {
  const bytes = utf8(text);
  return {
    sequence,
    receipt_path: path,
    byte_length: bytes.length,
    sha256: await sha256Bytes(bytes),
    attestation_hash: receipt.hashes.attestation,
    action_type: receipt.action.type,
  };
}

function artifactSha(artifacts: JsonObject[], artifactId: string): string {
  const item = artifacts.find((artifact) => artifact.artifact_id === artifactId);
  if (item === undefined) throw new Error(`missing artifact ${artifactId}`);
  return item.sha256 as string;
}

async function incidentCoverageCommitment(
  denominators: JsonObject[],
  coverage: JsonObject[],
  artifacts: JsonObject[],
): Promise<string> {
  return sha256Json({
    denominators: denominators.map((item) => ({
      ...item,
      artifact_sha256: artifactSha(artifacts, item.artifact_id as string),
    })),
    coverage: coverage.map((item) => ({
      ...item,
      artifact_sha256: artifactSha(artifacts, item.artifact_id as string),
    })),
  });
}

export async function finalizeRun(
  state: RunSnapshot,
  dependencies: RuntimeDependencies,
): Promise<{
  run_id: string;
  status: "FINALIZED";
  coverage: CoverageReport;
  packet: RunSnapshot["packet"];
}> {
  ensureOpen(state);
  if (state.status !== "BYPASS_RECORDED") {
    throw new Error("finalization requires the BYPASS_RECORDED state");
  }
  state.effects = await dependencies.readEffects(state.run_id);
  state.decision_observations = await dependencies.readDecisionObservations(
    state.run_id,
  );
  const permit = state.decisions.find((record) => record.decision === "PERMIT");
  const refusal = state.decisions.find((record) => record.decision === "REFUSE");
  if (
    state.decisions.length !== 2 ||
    state.decision_observations.length !== 2 ||
    permit === undefined ||
    refusal === undefined ||
    state.effects.length !== 2 ||
    state.observation_receipts.length !== 1
  ) {
    throw new Error("finalization requires one permit, one refusal, one mediated effect, and one direct effect");
  }
  const coverageResult = computeCoverage(state);
  if (
    coverageResult.decision.receipted !== 2 ||
    coverageResult.decision.total !== 2 ||
    coverageResult.effect.receipted !== 1 ||
    coverageResult.effect.total !== 2
  ) {
    throw new Error("runtime coverage does not match the preregistered 2/2 and 1/2 result");
  }
  const clock = dependencies.clock ?? systemClock;
  const incidentId = `incident-${state.run_id}`;
  const packetId = `packet-${state.run_id}`;
  const decisionIndex: JsonObject = {
    schema_version: 1,
    anchor_id: "mcp-boundary-ingress",
    phase: "decision",
    protocol: "mcp",
    observations: state.decision_observations,
  };
  const effectIndex: JsonObject = {
    schema_version: 1,
    anchor_id: "synthetic-receiver-effect",
    phase: "effect",
    protocol: "mcp",
    observations: state.effects.map((effect) => ({
      anchor_id: effect.anchor_id,
      observation_id: effect.observation_id,
      run_id: effect.run_id,
      protocol: effect.protocol,
      operation_ref: effect.operation_ref,
      phase: effect.phase,
      evidence_hash: effect.evidence_hash,
    })),
  };
  const members: Record<string, string> = {
    "indexes/mcp-boundary-ingress.json": jsonLine(decisionIndex),
    "indexes/synthetic-receiver-effect.json": jsonLine(effectIndex),
    "authzen/permit-request.json": jsonLine(permit.authzen_request),
    "authzen/permit-response.json": jsonLine(permit.authzen_response),
    "authzen/refusal-request.json": jsonLine(refusal.authzen_request),
    "authzen/refusal-response.json": jsonLine(refusal.authzen_response),
  };
  const decisionDenominatorHash = await sha256Bytes(
    utf8(members["indexes/mcp-boundary-ingress.json"] as string),
  );
  const effectDenominatorHash = await sha256Bytes(
    utf8(members["indexes/synthetic-receiver-effect.json"] as string),
  );
  if (
    state.statement_receipts.length !== 0 &&
    state.statement_receipts.length !== 3
  ) {
    throw new Error("persisted finalization statements are incomplete");
  }
  const reusingFinalizationReceipts = state.statement_receipts.length === 3;
  const decisionCheckpointSubject: JsonObject = {
    profile: PROFILE,
    issuer_role: "boundary",
    incident_id: incidentId,
    topic: "denominator:mcp-boundary-ingress:decision:mcp",
    claim: "ORDERED_DENOMINATOR_SNAPSHOT",
    epistemic_status: "observed",
    evidence_refs: [decisionDenominatorHash],
  };
  const decisionCheckpointEvidence: ReceiptEvidence[] = [
    {
      name: "decision-denominator",
      hash: decisionDenominatorHash,
      grounding: "self_asserted",
    },
  ];
  const decisionCheckpoint = reusingFinalizationReceipts
    ? (state.statement_receipts[0] as ActionReceiptV04)
    : await createActionReceiptV04({
        actionType: "incident.statement",
        subject: {
          ...decisionCheckpointSubject,
          statement_id: clock.uuid(),
        },
        eventId: clock.uuid(),
        claimedAt: clock.now(),
        evidence: decisionCheckpointEvidence,
        signer: dependencies.signers.boundary,
        issuerRole: "boundary",
        trustContextRef: dependencies.trustContextRef,
      });
  const effectCheckpointSubject: JsonObject = {
    profile: PROFILE,
    issuer_role: "target",
    incident_id: incidentId,
    topic: "denominator:synthetic-receiver-effect:effect:mcp",
    claim: "ORDERED_DENOMINATOR_SNAPSHOT",
    epistemic_status: "observed",
    evidence_refs: [effectDenominatorHash],
  };
  const effectCheckpointEvidence: ReceiptEvidence[] = [
    {
      name: "effect-denominator",
      hash: effectDenominatorHash,
      grounding: "self_asserted",
    },
  ];
  const effectCheckpoint = reusingFinalizationReceipts
    ? (state.statement_receipts[1] as ActionReceiptV04)
    : await createActionReceiptV04({
        actionType: "incident.statement",
        subject: {
          ...effectCheckpointSubject,
          statement_id: clock.uuid(),
        },
        eventId: clock.uuid(),
        claimedAt: clock.now(),
        evidence: effectCheckpointEvidence,
        signer: dependencies.signers.target,
        issuerRole: "target",
        trustContextRef: dependencies.trustContextRef,
      });
  if (reusingFinalizationReceipts) {
    await assertReusableReceipt(
      decisionCheckpoint,
      "incident.statement",
      dependencies.signers.boundary.issuer,
      decisionCheckpointSubject,
      decisionCheckpointEvidence,
      ["statement_id"],
    );
    await assertReusableReceipt(
      effectCheckpoint,
      "incident.statement",
      dependencies.signers.target.issuer,
      effectCheckpointSubject,
      effectCheckpointEvidence,
      ["statement_id"],
    );
  }
  const decisionCoverage: JsonObject = {
    schema_version: 1,
    anchor_id: "mcp-boundary-ingress",
    phase: "decision",
    protocol: "mcp",
    denominator_sha256: decisionDenominatorHash,
    minimum_verification_depth: "attestation",
    total: 2,
    receipted: 2,
    covered_ids: [permit, refusal].map(
      (record) => record.receipt.action.subject.decision_event_id as string,
    ),
    uncovered_ids: [],
    phantom_receipt_ids: [],
    invalid_receipts: [],
  };
  const observation = state.observation_receipts[0] as ActionReceiptV04;
  const effectCoverage: JsonObject = {
    schema_version: 1,
    anchor_id: "synthetic-receiver-effect",
    phase: "effect",
    protocol: "mcp",
    denominator_sha256: effectDenominatorHash,
    minimum_verification_depth: "attestation",
    total: 2,
    receipted: 1,
    covered_ids: [observation.action.subject.observation_id as string],
    uncovered_ids: state.effects
      .filter((effect) => !effect.mediated)
      .map((effect) => effect.observation_id),
    phantom_receipt_ids: [],
    invalid_receipts: [],
  };
  members["coverage/mcp-decisions.json"] = jsonLine(decisionCoverage);
  members["coverage/mcp-effects.json"] = jsonLine(effectCoverage);
  const artifacts: JsonObject[] = [
    await artifactEntry(
      "denominator-decisions",
      "indexes/mcp-boundary-ingress.json",
      "denominator",
      members["indexes/mcp-boundary-ingress.json"] as string,
    ),
    await artifactEntry(
      "denominator-effects",
      "indexes/synthetic-receiver-effect.json",
      "denominator",
      members["indexes/synthetic-receiver-effect.json"] as string,
    ),
    await artifactEntry(
      "coverage-decisions",
      "coverage/mcp-decisions.json",
      "coverage",
      members["coverage/mcp-decisions.json"] as string,
    ),
    await artifactEntry(
      "coverage-effects",
      "coverage/mcp-effects.json",
      "coverage",
      members["coverage/mcp-effects.json"] as string,
    ),
    await artifactEntry(
      "authzen-permit-request",
      "authzen/permit-request.json",
      "policy-input",
      members["authzen/permit-request.json"] as string,
    ),
    await artifactEntry(
      "authzen-permit-response",
      "authzen/permit-response.json",
      "policy-output",
      members["authzen/permit-response.json"] as string,
    ),
    await artifactEntry(
      "authzen-refusal-request",
      "authzen/refusal-request.json",
      "policy-input",
      members["authzen/refusal-request.json"] as string,
    ),
    await artifactEntry(
      "authzen-refusal-response",
      "authzen/refusal-response.json",
      "policy-output",
      members["authzen/refusal-response.json"] as string,
    ),
  ];
  const denominators: JsonObject[] = [
    {
      anchor_id: "mcp-boundary-ingress",
      artifact_id: "denominator-decisions",
      checkpoint_attestation: decisionCheckpoint.hashes.attestation,
      phase: "decision",
      protocol: "mcp",
      provenance: "PATH_SEPARATE_TEAM_CONTROLLED",
    },
    {
      anchor_id: "synthetic-receiver-effect",
      artifact_id: "denominator-effects",
      checkpoint_attestation: effectCheckpoint.hashes.attestation,
      phase: "effect",
      protocol: "mcp",
      provenance: "PATH_SEPARATE_TEAM_CONTROLLED",
    },
  ];
  const coverageRefs: JsonObject[] = [
    {
      anchor_id: "mcp-boundary-ingress",
      artifact_id: "coverage-decisions",
      phase: "decision",
      protocol: "mcp",
      minimum_verification_depth: "attestation",
    },
    {
      anchor_id: "synthetic-receiver-effect",
      artifact_id: "coverage-effects",
      phase: "effect",
      protocol: "mcp",
      minimum_verification_depth: "attestation",
    },
  ];
  const effectCoverageArtifactHash = artifactSha(artifacts, "coverage-effects");
  const gapStatementSubject: JsonObject = {
    profile: PROFILE,
    issuer_role: "incident_commander",
    incident_id: incidentId,
    topic: "effect-coverage",
    claim: "EFFECT_RECEIPT_GAP_CAUSE_UNRESOLVED",
    epistemic_status: "observed",
    evidence_refs: [effectCoverageArtifactHash],
  };
  const gapStatementEvidence: ReceiptEvidence[] = [
    {
      name: "recomputation:effect-coverage-report",
      hash: effectCoverageArtifactHash,
      grounding: "execution_verified",
    },
  ];
  const gapStatement = reusingFinalizationReceipts
    ? (state.statement_receipts[2] as ActionReceiptV04)
    : await createActionReceiptV04({
        actionType: "incident.statement",
        subject: {
          ...gapStatementSubject,
          statement_id: clock.uuid(),
        },
        eventId: clock.uuid(),
        claimedAt: clock.now(),
        evidence: gapStatementEvidence,
        signer: dependencies.signers.incidentCommander,
        issuerRole: "incident_commander",
        trustContextRef: dependencies.trustContextRef,
      });
  if (reusingFinalizationReceipts) {
    await assertReusableReceipt(
      gapStatement,
      "incident.statement",
      dependencies.signers.incidentCommander.issuer,
      gapStatementSubject,
      gapStatementEvidence,
      ["statement_id"],
    );
  }
  const prefixReceipts = [
    state.mandate,
    permit.receipt,
    refusal.receipt,
    observation,
    decisionCheckpoint,
    effectCheckpoint,
    gapStatement,
  ];
  const receiptPaths = [
    "receipts/00-mandate.json",
    "receipts/01-decision-permit.json",
    "receipts/02-decision-refuse.json",
    "receipts/03-observation-mediated.json",
    "receipts/04-denominator-decision-checkpoint.json",
    "receipts/05-denominator-effect-checkpoint.json",
    "receipts/06-gap-statement.json",
  ];
  for (let index = 0; index < prefixReceipts.length; index += 1) {
    members[receiptPaths[index] as string] = new TextDecoder().decode(
      receiptBytes(prefixReceipts[index] as ActionReceiptV04),
    );
  }
  const prefixTimeline = await Promise.all(
    prefixReceipts.map((receipt, index) =>
      timelineEntry(
        receipt,
        receiptPaths[index] as string,
        index + 1,
        members[receiptPaths[index] as string] as string,
      ),
    ),
  );
  const coverageCommitment = await incidentCoverageCommitment(
    denominators,
    coverageRefs,
    artifacts,
  );
  const handoffSubject: JsonObject = {
    profile: PROFILE,
    issuer_role: "incident_commander",
    incident_id: incidentId,
    recipient: state.role_issuers.publication,
    mandate_ref: state.mandate.hashes.attestation,
    timeline_hash: await sha256Json(prefixTimeline),
    coverage_hash: coverageCommitment,
    statement_refs: [
      decisionCheckpoint.hashes.attestation,
      effectCheckpoint.hashes.attestation,
      gapStatement.hashes.attestation,
    ],
    parent_refs: prefixReceipts.map((receipt) => receipt.hashes.attestation),
    requested_actions: ["review-unreceipted-effect", "preserve-denominator"],
    disclosure_conditions: ["synthetic-only", "no-credentials"],
    correction_channel: "https://github.com/res-agentica/res-agentica/issues",
    challenge_channel: "https://github.com/res-agentica/res-agentica/issues",
  };
  const handoffEvidence: ReceiptEvidence[] = [
    {
      name: "recomputation:coverage",
      hash: coverageCommitment,
      grounding: "execution_verified",
    },
  ];
  const handoff =
    state.handoff_receipt === null
      ? await createActionReceiptV04({
          actionType: "incident.handoff",
          subject: handoffSubject,
          eventId: clock.uuid(),
          claimedAt: clock.now(),
          evidence: handoffEvidence,
          signer: dependencies.signers.incidentCommander,
          issuerRole: "incident_commander",
          trustContextRef: dependencies.trustContextRef,
        })
      : state.handoff_receipt;
  if (state.handoff_receipt !== null) {
    await assertReusableReceipt(
      handoff,
      "incident.handoff",
      dependencies.signers.incidentCommander.issuer,
      handoffSubject,
      handoffEvidence,
    );
  }
  state.statement_receipts = [decisionCheckpoint, effectCheckpoint, gapStatement];
  state.handoff_receipt = handoff;
  members["receipts/07-handoff.json"] = new TextDecoder().decode(receiptBytes(handoff));
  const timeline = [
    ...prefixTimeline,
    await timelineEntry(handoff, "receipts/07-handoff.json", 8, members["receipts/07-handoff.json"]),
  ];
  await dependencies.persistBeforeWitness?.(state);
  await dependencies.beforeWitness?.();
  let packetWitness = state.packet_witness_checkpoint;
  if (packetWitness === null || packetWitness === undefined) {
    packetWitness = await dependencies.witness(
      [...prefixReceipts, handoff].map((receipt) => ({
        attestation: receipt.hashes.attestation,
        bytes: receiptBytes(receipt),
      })),
    );
    await dependencies.afterTimelineWitness?.();
    state.packet_witness_checkpoint = packetWitness;
    await dependencies.persistBeforeWitness?.(state);
  }
  if (
    packetWitness.witness_id !== PACKET_WITNESS_ID ||
    packetWitness.root_ref !== PACKET_WITNESS_ROOT
  ) {
    throw new Error("witness returned an unexpected packet identity");
  }
  members["witness/checkpoint.json"] = jsonLine(packetWitness);
  artifacts.push(
    await artifactEntry(
      "witness-checkpoint",
      "witness/checkpoint.json",
      "witness",
      members["witness/checkpoint.json"],
    ),
  );
  const roles: JsonObject[] = [
    { role: "evaluation_authority", issuer: state.role_issuers.authorization },
    { role: "boundary", issuer: state.role_issuers.boundary },
    { role: "target", issuer: state.role_issuers.target },
    { role: "incident_commander", issuer: state.role_issuers.incident_commander },
    { role: "publisher", issuer: state.role_issuers.publication },
    { role: "witness", issuer: state.role_issuers.witness },
  ];
  const core: JsonObject = {
    profile: PROFILE,
    packet_id: packetId,
    incident_id: incidentId,
    revision: 1,
    classification: "synthetic-public",
    supersedes_core_hash: null,
    roles,
    timeline,
    artifacts,
    denominators,
    coverage: coverageRefs,
    redactions: [],
    statements: [
      {
        attestation_hash: decisionCheckpoint.hashes.attestation,
        receipt_path: "receipts/04-denominator-decision-checkpoint.json",
      },
      {
        attestation_hash: effectCheckpoint.hashes.attestation,
        receipt_path: "receipts/05-denominator-effect-checkpoint.json",
      },
      {
        attestation_hash: gapStatement.hashes.attestation,
        receipt_path: "receipts/06-gap-statement.json",
      },
    ],
    witnesses: [
      {
        witness_id: PACKET_WITNESS_ID,
        artifact_id: "witness-checkpoint",
        root_ref: PACKET_WITNESS_ROOT,
      },
    ],
    corrections: [],
  };
  members["packet-core.json"] = jsonLine(core);
  const componentHashes: JsonObject = {};
  for (const field of [
    "roles",
    "timeline",
    "artifacts",
    "denominators",
    "coverage",
    "redactions",
    "statements",
    "witnesses",
    "corrections",
  ]) {
    componentHashes[field] = await sha256Json(core[field] as JsonValue);
  }
  const coreHash = await sha256Json(core);
  const publishSubject: JsonObject = {
    profile: PROFILE,
    issuer_role: "publisher",
    packet_id: packetId,
    packet_core_hash: coreHash,
    component_hashes: componentHashes,
  };
  const publishEvidence: ReceiptEvidence[] = [
    {
      name: "recomputation:packet-core",
      hash: coreHash,
      grounding: "execution_verified",
    },
  ];
  const publish =
    state.publish_receipt === null
      ? await createActionReceiptV04({
          actionType: "incident.packet.publish",
          subject: publishSubject,
          eventId: clock.uuid(),
          claimedAt: clock.now(),
          evidence: publishEvidence,
          signer: dependencies.signers.publication,
          issuerRole: "publisher",
          trustContextRef: dependencies.trustContextRef,
        })
      : state.publish_receipt;
  if (state.publish_receipt !== null) {
    await assertReusableReceipt(
      publish,
      "incident.packet.publish",
      dependencies.signers.publication.issuer,
      publishSubject,
      publishEvidence,
    );
  }
  members["publish-receipt.json"] = new TextDecoder().decode(receiptBytes(publish));
  state.publish_receipt = publish;
  await dependencies.persistBeforeWitness?.(state);
  await dependencies.witness([
    { attestation: publish.hashes.attestation, bytes: receiptBytes(publish) },
  ]);
  await dependencies.afterPublishWitness?.();
  const memberEntries = Object.entries(members)
      .sort(([left], [right]) => left.localeCompare(right))
  if (memberEntries.length > 32) {
    throw new RangeError("generated packet exceeds 32 members");
  }
  const aggregateBytes = memberEntries.reduce(
    (total, [, text]) => total + utf8(text).length,
    0,
  );
  if (aggregateBytes > 2_097_152) {
    throw new RangeError("generated packet exceeds 2097152 aggregate bytes");
  }
  const manifestMembers = await Promise.all(
    memberEntries.map(([path, text]) => packetMember(path, text)),
  );
  state.packet = {
    packet_id: packetId,
    members,
    manifest: { packet_id: packetId, profile: PROFILE, members: manifestMembers },
  };
  await transition(
    state,
    "FINALIZED",
    {
      packet_id: packetId,
      manifest_members: manifestMembers as unknown as JsonValue,
    },
    clock,
  );
  return {
    run_id: state.run_id,
    status: "FINALIZED",
    coverage: coverageResult,
    packet: state.packet,
  };
}

export function newCapability(): string {
  return randomToken();
}
