"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/spec/index.ts
var spec_exports = {};
__export(spec_exports, {
  RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION: () => RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION: () => RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
  RIDDLE_PROOF_RUN_CARD_VERSION: () => RIDDLE_PROOF_RUN_CARD_VERSION,
  RIDDLE_PROOF_RUN_STATE_VERSION: () => RIDDLE_PROOF_RUN_STATE_VERSION,
  appendRunEvent: () => appendRunEvent,
  appendStageHeartbeat: () => appendStageHeartbeat,
  applyPrLifecycleState: () => applyPrLifecycleState,
  applyTerminalMetadata: () => applyTerminalMetadata,
  authorPacketPayloadFromCheckpointResponse: () => authorPacketPayloadFromCheckpointResponse,
  buildAuthorCheckpointPacket: () => buildAuthorCheckpointPacket,
  buildCheckpointPacketForEngineResult: () => buildCheckpointPacketForEngineResult,
  buildProofAssessmentCheckpointPacket: () => buildProofAssessmentCheckpointPacket,
  buildStageCheckpointPacket: () => buildStageCheckpointPacket,
  checkpointResponseIdentity: () => checkpointResponseIdentity,
  checkpointSummaryFromState: () => checkpointSummaryFromState,
  compactRecord: () => compactRecord,
  createCheckpointResponseTemplate: () => createCheckpointResponseTemplate,
  createRiddleProofRunCard: () => createRiddleProofRunCard,
  createRunResult: () => createRunResult,
  createRunState: () => createRunState,
  createRunStatusSnapshot: () => createRunStatusSnapshot,
  isDuplicateCheckpointResponse: () => isDuplicateCheckpointResponse,
  isSuccessfulStatus: () => isSuccessfulStatus,
  isTerminalStatus: () => isTerminalStatus,
  nonEmptyString: () => nonEmptyString,
  normalizeCheckpointResponse: () => normalizeCheckpointResponse,
  normalizeIntegrationContext: () => normalizeIntegrationContext,
  normalizePrLifecycleState: () => normalizePrLifecycleState,
  normalizeRunParams: () => normalizeRunParams,
  normalizeTerminalMetadata: () => normalizeTerminalMetadata,
  proofContractFromAuthorCheckpointResponse: () => proofContractFromAuthorCheckpointResponse,
  recordValue: () => recordValue,
  setRunStatus: () => setRunStatus,
  statePathsForRunState: () => statePathsForRunState
});
module.exports = __toCommonJS(spec_exports);

// src/result.ts
function isTerminalStatus(status) {
  return status === "blocked" || status === "failed" || status === "ready_to_ship" || status === "shipped" || status === "completed";
}
function isSuccessfulStatus(status) {
  return status !== "blocked" && status !== "failed";
}
function compactRecord(input) {
  return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0 && value !== null && value !== ""));
}
function nonEmptyString(value) {
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
}
function recordValue(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
}
function firstNonEmptyString(...values) {
  for (const value of values) {
    const normalized = nonEmptyString(value);
    if (normalized) return normalized;
  }
  return void 0;
}
function firstBoolean(...values) {
  for (const value of values) {
    if (typeof value === "boolean") return value;
  }
  return void 0;
}
function normalizePrStatus(value) {
  const status = nonEmptyString(value)?.toLowerCase();
  if (status === "merged") return "merged";
  if (status === "open") return "open";
  if (status === "closed") return "closed";
  if (status === "not_found" || status === "not-found") return "not_found";
  if (status === "unavailable") return "unavailable";
  return status || "unknown";
}
function normalizePrLifecycleStateInput(input) {
  if (!input) return void 0;
  const cleanup = recordValue(input.cleanup);
  const mergeCommit = nonEmptyString(input.merge_commit) || nonEmptyString(input.mergeCommit) || nonEmptyString(recordValue(input.mergeCommit)?.oid);
  return compactRecord({
    status: normalizePrStatus(input.status || input.state),
    pr_url: nonEmptyString(input.pr_url) || nonEmptyString(input.prUrl) || nonEmptyString(input.url),
    pr_number: nonEmptyString(input.pr_number) || nonEmptyString(input.prNumber) || (typeof input.number === "number" ? String(input.number) : void 0),
    repo: nonEmptyString(input.repo) || nonEmptyString(input.repository),
    head_branch: nonEmptyString(input.head_branch) || nonEmptyString(input.headBranch) || nonEmptyString(input.headRefName),
    base_branch: nonEmptyString(input.base_branch) || nonEmptyString(input.baseBranch) || nonEmptyString(input.baseRefName),
    merge_commit: mergeCommit,
    merged_at: nonEmptyString(input.merged_at) || nonEmptyString(input.mergedAt),
    closed_at: nonEmptyString(input.closed_at) || nonEmptyString(input.closedAt),
    checked_at: nonEmptyString(input.checked_at) || nonEmptyString(input.checkedAt),
    source: nonEmptyString(input.source),
    next_action: nonEmptyString(input.next_action) || nonEmptyString(input.nextAction),
    cleanup: cleanup && Object.keys(cleanup).length ? cleanup : void 0
  });
}
function normalizeTerminalMetadata(input) {
  const riddleState = recordValue(input.riddleState) || {};
  const result = recordValue(input.engineResult) || {};
  const contract = recordValue(result.checkpointContract) || {};
  const details = recordValue(input.checkpointDetails) || recordValue(contract.details) || {};
  const shipReport = recordValue(riddleState.ship_report) || recordValue(result.ship_report) || recordValue(result.shipReport) || recordValue(details.ship_report) || recordValue(details.shipReport) || {};
  const markedReady = firstBoolean(
    riddleState.marked_ready,
    result.marked_ready,
    result.markedReady,
    details.marked_ready,
    details.markedReady,
    shipReport.marked_ready
  );
  const leftDraft = firstBoolean(
    riddleState.left_draft,
    result.left_draft,
    result.leftDraft,
    details.left_draft,
    details.leftDraft,
    shipReport.left_draft
  );
  const finalized = firstBoolean(riddleState.finalized, result.finalized, details.finalized);
  const prState = normalizePrLifecycleStateInput(
    recordValue(riddleState.pr_state) || recordValue(riddleState.prState) || recordValue(result.pr_state) || recordValue(result.prState) || recordValue(details.pr_state) || recordValue(details.prState) || recordValue(shipReport.pr_state) || recordValue(shipReport.prState)
  );
  const cleanupReport = recordValue(riddleState.cleanup_report) || recordValue(riddleState.cleanupReport) || recordValue(result.cleanup_report) || recordValue(result.cleanupReport) || recordValue(details.cleanup_report) || recordValue(details.cleanupReport) || recordValue(prState?.cleanup);
  return compactRecord({
    pr_url: firstNonEmptyString(riddleState.pr_url, result.pr_url, result.prUrl, details.pr_url, details.prUrl, shipReport.pr_url),
    pr_branch: firstNonEmptyString(
      riddleState.pr_branch,
      riddleState.target_branch,
      result.pr_branch,
      result.prBranch,
      details.pr_branch,
      details.prBranch,
      shipReport.pr_branch,
      shipReport.branch,
      prState?.head_branch
    ),
    pr_state: prState,
    marked_ready: markedReady,
    left_draft: leftDraft,
    ci_status: firstNonEmptyString(riddleState.ci_status, result.ci_status, result.ciStatus, details.ci_status, details.ciStatus, shipReport.ci_status),
    ship_commit: firstNonEmptyString(riddleState.ship_commit, result.ship_commit, result.shipCommit, details.ship_commit, details.shipCommit, shipReport.shipped_commit, shipReport.ship_commit),
    ship_remote_head: firstNonEmptyString(riddleState.ship_remote_head, result.ship_remote_head, result.shipRemoteHead, details.ship_remote_head, details.shipRemoteHead, shipReport.ship_remote_head),
    merge_commit: firstNonEmptyString(riddleState.merge_commit, riddleState.mergeCommit, result.merge_commit, result.mergeCommit, details.merge_commit, details.mergeCommit, prState?.merge_commit),
    merged_at: firstNonEmptyString(riddleState.merged_at, riddleState.mergedAt, result.merged_at, result.mergedAt, details.merged_at, details.mergedAt, prState?.merged_at),
    proof_comment_url: firstNonEmptyString(riddleState.proof_comment_url, result.proof_comment_url, result.proofCommentUrl, details.proof_comment_url, details.proofCommentUrl, shipReport.proof_comment_url),
    before_artifact_url: firstNonEmptyString(riddleState.before_artifact_url, riddleState.before_cdn, result.before_artifact_url, result.beforeArtifactUrl, details.before_artifact_url, details.beforeArtifactUrl, shipReport.before_artifact_url),
    prod_artifact_url: firstNonEmptyString(riddleState.prod_artifact_url, riddleState.prod_cdn, result.prod_artifact_url, result.prodArtifactUrl, details.prod_artifact_url, details.prodArtifactUrl, shipReport.prod_artifact_url),
    after_artifact_url: firstNonEmptyString(riddleState.after_artifact_url, riddleState.after_cdn, result.after_artifact_url, result.afterArtifactUrl, details.after_artifact_url, details.afterArtifactUrl, shipReport.after_artifact_url),
    ship_report: Object.keys(shipReport).length ? shipReport : void 0,
    cleanup_report: cleanupReport,
    notification: recordValue(riddleState.notification) || recordValue(riddleState.discord_notification) || recordValue(result.notification) || recordValue(result.discord_notification),
    proof_decision: nonEmptyString(riddleState.proof_decision) || nonEmptyString(result.proof_decision),
    merge_recommendation: nonEmptyString(riddleState.merge_recommendation) || nonEmptyString(result.merge_recommendation),
    finalized: typeof finalized === "boolean" ? finalized : void 0
  });
}
function applyTerminalMetadata(state, metadata) {
  if (metadata.pr_state) {
    state.pr_state = metadata.pr_state;
    if (metadata.pr_state.pr_url) state.pr_url = metadata.pr_state.pr_url;
    if (metadata.pr_state.head_branch) state.pr_branch = metadata.pr_state.head_branch;
    if (metadata.pr_state.merge_commit) state.merge_commit = metadata.pr_state.merge_commit;
    if (metadata.pr_state.merged_at) state.merged_at = metadata.pr_state.merged_at;
    if (metadata.pr_state.cleanup) state.cleanup_report = metadata.pr_state.cleanup;
    if (metadata.pr_state.status === "merged") state.finalized = true;
  }
  const prUrl = nonEmptyString(metadata.pr_url);
  if (prUrl) state.pr_url = prUrl;
  const prBranch = nonEmptyString(metadata.pr_branch);
  if (prBranch) state.pr_branch = prBranch;
  if (typeof metadata.marked_ready === "boolean") state.marked_ready = metadata.marked_ready;
  if (typeof metadata.left_draft === "boolean") state.left_draft = metadata.left_draft;
  const ciStatus = nonEmptyString(metadata.ci_status);
  if (ciStatus) state.ci_status = ciStatus;
  const shipCommit = nonEmptyString(metadata.ship_commit);
  if (shipCommit) state.ship_commit = shipCommit;
  const shipRemoteHead = nonEmptyString(metadata.ship_remote_head);
  if (shipRemoteHead) state.ship_remote_head = shipRemoteHead;
  const mergeCommit = nonEmptyString(metadata.merge_commit);
  if (mergeCommit) state.merge_commit = mergeCommit;
  const mergedAt = nonEmptyString(metadata.merged_at);
  if (mergedAt) state.merged_at = mergedAt;
  const proofCommentUrl = nonEmptyString(metadata.proof_comment_url);
  if (proofCommentUrl) state.proof_comment_url = proofCommentUrl;
  const beforeArtifactUrl = nonEmptyString(metadata.before_artifact_url);
  if (beforeArtifactUrl) state.before_artifact_url = beforeArtifactUrl;
  const prodArtifactUrl = nonEmptyString(metadata.prod_artifact_url);
  if (prodArtifactUrl) state.prod_artifact_url = prodArtifactUrl;
  const afterArtifactUrl = nonEmptyString(metadata.after_artifact_url);
  if (afterArtifactUrl) state.after_artifact_url = afterArtifactUrl;
  const shipReport = recordValue(metadata.ship_report);
  if (shipReport) state.ship_report = shipReport;
  const cleanupReport = recordValue(metadata.cleanup_report);
  if (cleanupReport) state.cleanup_report = cleanupReport;
  const notification = recordValue(metadata.notification);
  if (notification) state.notification = notification;
  const proofDecision = nonEmptyString(metadata.proof_decision);
  if (proofDecision) state.proof_decision = proofDecision;
  const mergeRecommendation = nonEmptyString(metadata.merge_recommendation);
  if (mergeRecommendation) state.merge_recommendation = mergeRecommendation;
  if (typeof metadata.finalized === "boolean") state.finalized = metadata.finalized;
  return state;
}
function createRunResult(input) {
  const status = input.status || input.state.status;
  const ok = isSuccessfulStatus(status);
  const state = input.metadata ? applyTerminalMetadata(input.state, input.metadata) : input.state;
  state.status = status;
  state.ok = ok;
  return compactRecord({
    ok,
    status,
    run_id: state.run_id,
    state_path: input.state_path ?? state.state_path ?? null,
    worktree_path: state.worktree_path ?? null,
    branch: state.branch ?? null,
    current_stage: state.current_stage ?? null,
    iterations: state.iterations,
    last_checkpoint: state.last_checkpoint ?? null,
    last_summary: input.last_summary ?? null,
    event_count: state.events.length,
    pr_url: state.pr_url,
    pr_branch: state.pr_branch,
    pr_state: state.pr_state,
    marked_ready: state.marked_ready,
    left_draft: state.left_draft,
    ci_status: state.ci_status,
    ship_commit: state.ship_commit,
    ship_remote_head: state.ship_remote_head,
    merge_commit: state.merge_commit,
    merged_at: state.merged_at,
    proof_comment_url: state.proof_comment_url,
    before_artifact_url: state.before_artifact_url,
    prod_artifact_url: state.prod_artifact_url,
    after_artifact_url: state.after_artifact_url,
    ship_report: state.ship_report,
    cleanup_report: state.cleanup_report,
    notification: state.notification,
    proof_decision: state.proof_decision,
    merge_recommendation: state.merge_recommendation,
    finalized: state.finalized,
    blocker: state.blocker,
    checkpoint_packet: state.checkpoint_packet,
    checkpoint_summary: state.checkpoint_summary,
    state_paths: state.state_paths,
    proof_contract: state.proof_contract,
    run_card: state.run_card,
    proof_session: state.proof_session,
    viewport_matrix_status: state.viewport_matrix_status,
    evidence_bundle: input.evidence_bundle,
    raw: input.raw
  });
}

// src/checkpoint.ts
var import_node_crypto = __toESM(require("crypto"), 1);
var RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION = "riddle-proof.checkpoint.v1";
var RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION = "riddle-proof.checkpoint_response.v1";
function timestamp() {
  return (/* @__PURE__ */ new Date()).toISOString();
}
function jsonCloneRecord(value) {
  const record = recordValue(value);
  if (!record) return void 0;
  try {
    return JSON.parse(JSON.stringify(record));
  } catch {
    return { ...record };
  }
}
function jsonCloneValue(value) {
  if (value === void 0 || value === null) return void 0;
  try {
    return JSON.parse(JSON.stringify(value));
  } catch {
    return value;
  }
}
function stableJson(value) {
  if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
  const record = recordValue(value);
  if (record) {
    return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
  }
  return JSON.stringify(value);
}
function compactText(value, limit = 1600) {
  const text = nonEmptyString(value);
  if (!text) return void 0;
  return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
}
function statePathsForRunState(state, engineStatePath) {
  return compactRecord({
    wrapper_state_path: state.state_path || state.request.harness_state_path || null,
    engine_state_path: engineStatePath || state.request.engine_state_path || null,
    resume_state_path: engineStatePath || state.request.engine_state_path || null
  });
}
function responseSchemaForAuthorPacket() {
  return {
    type: "object",
    required: ["version", "run_id", "checkpoint", "decision", "summary", "payload", "created_at"],
    additionalProperties: false,
    properties: {
      version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
      run_id: { type: "string" },
      checkpoint: { type: "string" },
      resume_token: { type: "string" },
      decision: {
        type: "string",
        enum: ["author_packet", "needs_recon", "blocked", "human_review"]
      },
      summary: { type: "string" },
      payload: {
        type: "object",
        description: "For decision=author_packet, provide the proof packet itself or {author_packet:{...}} with proof_plan, capture_script, refined_inputs.expected_terminal_path, and interaction_contract when the proof changes route, query, or hash."
      },
      reasons: { type: "array", items: { type: "string" } },
      continue_with_stage: { type: "string", enum: ["author", "recon"] },
      source: {
        type: "object",
        properties: {
          kind: { type: "string" },
          session_id: { type: "string" },
          user_id: { type: "string" }
        }
      },
      created_at: { type: "string" }
    }
  };
}
function responseSchemaForProofAssessmentPacket() {
  return {
    type: "object",
    required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
    additionalProperties: false,
    properties: {
      version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
      run_id: { type: "string" },
      checkpoint: { type: "string" },
      resume_token: { type: "string" },
      decision: {
        type: "string",
        enum: [
          "ready_to_ship",
          "needs_richer_proof",
          "revise_capture",
          "needs_recon",
          "needs_implementation",
          "blocked",
          "human_review"
        ]
      },
      summary: { type: "string" },
      payload: {
        type: "object",
        description: "Optional structured assessment details, including recommended_stage, continue_with_stage, visual_delta notes, or blocker diagnostics."
      },
      reasons: { type: "array", items: { type: "string" } },
      continue_with_stage: { type: "string", enum: ["ship", "author", "implement", "recon", "verify"] },
      source: {
        type: "object",
        properties: {
          kind: { type: "string" },
          session_id: { type: "string" },
          user_id: { type: "string" }
        }
      },
      created_at: { type: "string" }
    }
  };
}
function responseSchemaForReconPacket() {
  return {
    type: "object",
    required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
    additionalProperties: false,
    properties: {
      version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
      run_id: { type: "string" },
      checkpoint: { type: "string" },
      resume_token: { type: "string" },
      decision: {
        type: "string",
        enum: ["ready_for_author", "retry_recon", "recon_stuck", "needs_recon", "blocked", "human_review"]
      },
      summary: { type: "string" },
      payload: {
        type: "object",
        description: "Optional recon assessment details such as baseline_understanding, refined_inputs, reasons, or diagnostic blocker context."
      },
      reasons: { type: "array", items: { type: "string" } },
      continue_with_stage: { type: "string", enum: ["recon", "author"] },
      source: {
        type: "object",
        properties: {
          kind: { type: "string" },
          session_id: { type: "string" },
          user_id: { type: "string" }
        }
      },
      created_at: { type: "string" }
    }
  };
}
function responseSchemaForImplementationPacket() {
  return {
    type: "object",
    required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
    additionalProperties: false,
    properties: {
      version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
      run_id: { type: "string" },
      checkpoint: { type: "string" },
      resume_token: { type: "string" },
      decision: {
        type: "string",
        enum: ["implementation_complete", "needs_author", "needs_recon", "blocked", "human_review"]
      },
      summary: { type: "string" },
      payload: {
        type: "object",
        description: "Implementation details such as changed_files, tests_run, and implementation_notes. The changed worktree must contain a real git diff before verify can advance."
      },
      reasons: { type: "array", items: { type: "string" } },
      continue_with_stage: { type: "string", enum: ["implement", "verify", "author", "recon"] },
      source: {
        type: "object",
        properties: {
          kind: { type: "string" },
          session_id: { type: "string" },
          user_id: { type: "string" }
        }
      },
      created_at: { type: "string" }
    }
  };
}
function responseSchemaForAdvancePacket(stage) {
  return {
    type: "object",
    required: ["version", "run_id", "checkpoint", "decision", "summary", "created_at"],
    additionalProperties: false,
    properties: {
      version: { const: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION },
      run_id: { type: "string" },
      checkpoint: { type: "string" },
      resume_token: { type: "string" },
      decision: {
        type: "string",
        enum: ["continue_stage", "retry_stage", "needs_recon", "needs_implementation", "blocked", "human_review"]
      },
      summary: { type: "string" },
      payload: { type: "object" },
      reasons: { type: "array", items: { type: "string" } },
      continue_with_stage: { type: "string", enum: ["recon", "author", "implement", "verify", "ship", stage] },
      source: {
        type: "object",
        properties: {
          kind: { type: "string" },
          session_id: { type: "string" },
          user_id: { type: "string" }
        }
      },
      created_at: { type: "string" }
    }
  };
}
function resumeTokenFor(input) {
  const hash = import_node_crypto.default.createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 24);
  return `rpchk_${hash}`;
}
function artifactsFromState(state) {
  const artifacts = [];
  for (const role of ["before", "prod", "after"]) {
    const url = nonEmptyString(state?.[`${role}_cdn`]);
    if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
  }
  const authorRequest = recordValue(state?.author_request);
  const latestAttempt = recordValue(authorRequest?.latest_attempt);
  const observations = recordValue(latestAttempt?.observations);
  for (const [label, observation] of Object.entries(observations || {})) {
    const record = recordValue(observation);
    const url = nonEmptyString(record?.url);
    if (url && !artifacts.some((artifact) => artifact.url === url)) {
      artifacts.push({
        role: label === "before" || label === "prod" ? label : "json",
        url,
        name: `${label}-observation`,
        summary: compactText(record?.reason, 240)
      });
    }
  }
  return artifacts.slice(0, 16);
}
function stageFromCheckpoint(checkpoint) {
  if (checkpoint.startsWith("recon_")) return "recon";
  if (checkpoint.startsWith("author_")) return "author";
  if (checkpoint.startsWith("implement_")) return "implement";
  if (checkpoint.startsWith("verify_")) return "verify";
  if (checkpoint.startsWith("ship_")) return "ship";
  if (checkpoint.startsWith("pr_sync_")) return "notify";
  if (checkpoint.includes("capture")) return "prove";
  return "setup";
}
function allowedDecisionsForStage(stage, checkpoint) {
  if (stage === "recon") return ["ready_for_author", "retry_recon", "recon_stuck", "needs_recon", "blocked", "human_review"];
  if (stage === "implement") return ["implementation_complete", "needs_author", "needs_recon", "blocked", "human_review"];
  if (stage === "ship") return ["continue_stage", "retry_stage", "needs_implementation", "needs_recon", "blocked", "human_review"];
  if (checkpoint === "awaiting_stage_advance") return ["continue_stage", "retry_stage", "needs_recon", "needs_implementation", "blocked", "human_review"];
  return ["continue_stage", "retry_stage", "needs_recon", "needs_implementation", "blocked", "human_review"];
}
function packetKindForStage(stage, checkpoint) {
  if (stage === "recon") return "assess_recon";
  if (stage === "implement") return "implement_change";
  if (checkpoint.includes("human")) return "human_review";
  return "advance_decision";
}
function responseSchemaForStage(stage, checkpoint) {
  if (stage === "recon") return responseSchemaForReconPacket();
  if (stage === "implement") return responseSchemaForImplementationPacket();
  return responseSchemaForAdvancePacket(stage);
}
function questionForStage(stage, checkpoint) {
  if (stage === "recon") {
    return "Assess the baseline/recon evidence. Return ready_for_author only when the baseline is trustworthy; otherwise choose retry_recon, recon_stuck, blocked, or human_review.";
  }
  if (stage === "implement") {
    return "Implement the requested change in the after worktree, leave a real git diff, then return implementation_complete with changed_files/tests_run/implementation_notes. Choose blocked or human_review if implementation cannot honestly advance.";
  }
  if (stage === "ship") {
    return "Assess whether the ship gate can continue. Return continue_stage only if proof, PR, and policy gates are satisfied; otherwise route to the appropriate earlier stage or block with a concrete reason.";
  }
  return "Choose the next Riddle Proof stage for this durable run, or block with a concrete reason if the run cannot honestly advance.";
}
function buildStageCheckpointPacket(input) {
  const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "stage_checkpoint";
  const stage = nonEmptyString(input.engineResult.stage) || stageFromCheckpoint(checkpoint);
  const runId = input.runState.run_id || "unknown";
  const fullState = input.fullRiddleState || {};
  const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
  const checkpointContract = recordValue(input.engineResult.checkpointContract);
  const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.stage_summary) || `${stage} checkpoint needs a supervising decision.`;
  const kind = packetKindForStage(stage, checkpoint);
  return {
    version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
    run_id: runId,
    state_path: input.runState.state_path,
    stage,
    checkpoint,
    kind,
    summary,
    question: questionForStage(stage, checkpoint),
    change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
    context: input.request.context,
    artifacts: artifactsFromState(fullState),
    state_excerpt: compactRecord({
      repo: input.request.repo || fullState.repo,
      branch: input.request.branch || fullState.branch,
      after_worktree: fullState.after_worktree || input.runState.worktree_path,
      verification_mode: input.request.verification_mode || fullState.verification_mode,
      reference: input.request.reference || fullState.reference,
      server_path: fullState.server_path,
      wait_for_selector: fullState.wait_for_selector,
      recon_status: fullState.recon_status,
      author_status: fullState.author_status,
      implementation_status: fullState.implementation_status,
      verify_status: fullState.verify_status,
      stage_decision_request: jsonCloneRecord(fullState.stage_decision_request)
    }),
    evidence_excerpt: compactRecord({
      before_cdn: fullState.before_cdn || null,
      prod_cdn: fullState.prod_cdn || null,
      after_cdn: fullState.after_cdn || null,
      recon_results: jsonCloneRecord(fullState.recon_results),
      checkpoint_contract: jsonCloneRecord(checkpointContract),
      decision_details: jsonCloneRecord(decisionDetails)
    }),
    allowed_decisions: allowedDecisionsForStage(stage, checkpoint),
    response_schema: responseSchemaForStage(stage, checkpoint),
    routing_hint: {
      suggested_role: stage === "implement" ? "builder_agent" : checkpoint.includes("human") ? "human" : "main_agent",
      visibility: input.visibility || "quiet",
      urgency: stage === "ship" ? "high" : "normal",
      can_auto_answer: input.visibility !== "manual"
    },
    resume_token: resumeTokenFor({
      runId,
      statePath: input.engineResult.state_path || input.request.engine_state_path || null,
      checkpoint,
      stage
    }),
    created_at: input.created_at || timestamp()
  };
}
function buildAuthorCheckpointPacket(input) {
  const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "author_supervisor_judgment";
  const stage = "author";
  const runId = input.runState.run_id || "unknown";
  const fullState = input.fullRiddleState || {};
  const decisionDetails = recordValue(input.engineResult.decisionRequest?.details);
  const authorRequest = recordValue(fullState.author_request) || recordValue(fullState.proof_plan_request) || recordValue(decisionDetails?.authorRequest) || {};
  const fallbackDefaults = recordValue(authorRequest.fallback_defaults) || {};
  const reconResults = recordValue(fullState.recon_results);
  const checkpointContract = recordValue(input.engineResult.checkpointContract);
  const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.author_summary) || "Author checkpoint needs a supervising proof packet.";
  return {
    version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
    run_id: runId,
    state_path: input.runState.state_path,
    stage,
    checkpoint,
    kind: "author_proof",
    summary,
    question: "Author the proof packet for this Riddle Proof run. Return a CheckpointResponse with decision=author_packet and payload containing proof_plan and capture_script.",
    change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
    context: input.request.context,
    artifacts: artifactsFromState(fullState),
    state_excerpt: compactRecord({
      repo: input.request.repo || fullState.repo,
      branch: input.request.branch || fullState.branch,
      verification_mode: input.request.verification_mode || fullState.verification_mode,
      success_criteria: fullState.success_criteria,
      reference: input.request.reference || fullState.reference,
      server_path: fullState.server_path,
      wait_for_selector: fullState.wait_for_selector,
      expected_start_path: fullState.expected_start_path,
      expected_terminal_path: fullState.expected_terminal_path,
      requested_expected_terminal_path: fullState.requested_expected_terminal_path,
      interaction_contract: jsonCloneRecord(fullState.interaction_contract),
      route_expectation: jsonCloneRecord(fullState.route_expectation),
      author_summary: fullState.author_summary,
      author_request: jsonCloneRecord(authorRequest),
      recon_baseline_understanding: jsonCloneRecord(fullState.recon_baseline_understanding),
      fallback_defaults: jsonCloneRecord(fallbackDefaults)
    }),
    evidence_excerpt: compactRecord({
      recon_results: jsonCloneRecord(reconResults),
      checkpoint_contract: jsonCloneRecord(checkpointContract)
    }),
    allowed_decisions: ["author_packet", "needs_recon", "blocked", "human_review"],
    response_schema: responseSchemaForAuthorPacket(),
    routing_hint: {
      suggested_role: "proof_author",
      visibility: input.visibility || "quiet",
      urgency: "normal",
      can_auto_answer: input.visibility !== "manual"
    },
    resume_token: resumeTokenFor({
      runId,
      statePath: input.engineResult.state_path || input.request.engine_state_path || null,
      checkpoint,
      stage
    }),
    created_at: input.created_at || timestamp()
  };
}
function visualDeltaFromState(fullState) {
  const bundle = recordValue(fullState.evidence_bundle);
  const after = recordValue(bundle?.after);
  const afterDelta = recordValue(after?.visual_delta);
  if (afterDelta && Object.keys(afterDelta).length) return afterDelta;
  const proofAssessmentRequest = recordValue(fullState.proof_assessment_request);
  return recordValue(proofAssessmentRequest?.visual_delta) || null;
}
function normalizedText(value) {
  return typeof value === "string" ? value.trim().toLowerCase() : "";
}
function noImplementationModeForCheckpoint(request, fullState) {
  const requestRecord = recordValue(request) || {};
  const mode = normalizedText(
    requestRecord.mode || requestRecord.workflow_mode || fullState.mode || fullState.workflow_mode
  );
  const implementationMode = normalizedText(requestRecord.implementation_mode || fullState.implementation_mode);
  const requireDiff = requestRecord.require_diff ?? fullState.require_diff;
  const allowCodeChanges = requestRecord.allow_code_changes ?? fullState.allow_code_changes;
  return mode === "audit" || mode === "profile" || implementationMode === "none" || requireDiff === false || allowCodeChanges === false;
}
function visualDeltaNotApplicableForNoImplementation(visualDelta) {
  if (String(visualDelta?.status || "").trim() !== "not_applicable") return false;
  const reason = String(visualDelta?.reason || "").toLowerCase();
  return reason.includes("audit/no-diff") || reason.includes("does not require a before/after implementation delta");
}
function verificationModeRequiresVisualDelta(value) {
  const mode = String(value || "proof").trim().toLowerCase();
  return [
    "visual",
    "render",
    "interaction",
    "ui",
    "layout",
    "screenshot",
    "canvas",
    "animation"
  ].includes(mode);
}
function visualDeltaIssueCode(visualDelta, required) {
  const status = String(visualDelta?.status || "").trim();
  const reason = String(visualDelta?.reason || "").toLowerCase();
  if (status === "unmeasured") {
    if (reason.includes("fetch") || reason.includes("allowlist") || reason.includes("registered domain") || reason.includes("high risk") || reason.includes("comparator")) {
      return "comparator_fetch_blocked";
    }
    return "visual_delta_unmeasured";
  }
  if (status === "measured" && visualDelta?.passed === false) return "semantic_proof_failed";
  if (required && status !== "measured") return "visual_delta_unmeasured";
  return null;
}
function buildProofAssessmentCheckpointPacket(input) {
  const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "verify_supervisor_judgment";
  const stage = "verify";
  const runId = input.runState.run_id || "unknown";
  const fullState = input.fullRiddleState || {};
  const proofAssessmentRequest = recordValue(fullState.proof_assessment_request) || recordValue(recordValue(fullState.verify_decision_request)?.assessment_request) || recordValue(input.engineResult.decisionRequest?.details) || {};
  const bundle = recordValue(fullState.evidence_bundle);
  const artifactContract = recordValue(proofAssessmentRequest.artifact_contract) || recordValue(bundle?.artifact_contract);
  const requiredSignals = recordValue(recordValue(artifactContract)?.required);
  const visualDelta = visualDeltaFromState(fullState);
  const verificationMode = nonEmptyString(bundle?.verification_mode) || nonEmptyString(fullState.verification_mode) || nonEmptyString(input.request.verification_mode) || "proof";
  const noImplementationMode = noImplementationModeForCheckpoint(input.request, fullState);
  const noImplementationVisualDelta = visualDeltaNotApplicableForNoImplementation(visualDelta);
  const visualDeltaRequired = !noImplementationMode && !noImplementationVisualDelta && requiredSignals?.visual_delta !== false && (requiredSignals?.visual_delta === true || verificationModeRequiresVisualDelta(verificationMode));
  const evidenceIssueCode2 = visualDeltaIssueCode(visualDelta, visualDeltaRequired);
  const summary = nonEmptyString(input.engineResult.summary) || nonEmptyString(fullState.verify_summary) || "Verify captured evidence and needs a supervising proof assessment.";
  const recoveryHint = evidenceIssueCode2 ? "Required visual_delta evidence is incomplete. Keep this same run in verify/evidence recovery with decision=revise_capture and continue_with_stage=verify unless the evidence proves an implementation or recon problem." : "Assess whether the current artifacts prove the requested change, then choose the next stage.";
  return {
    version: RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
    run_id: runId,
    state_path: input.runState.state_path,
    stage,
    checkpoint,
    kind: evidenceIssueCode2 ? "recover_evidence" : "assess_proof",
    summary,
    question: `Assess the current Riddle Proof evidence. ${recoveryHint} Return a CheckpointResponse using one allowed decision.`,
    change_request: input.request.change_request || nonEmptyString(fullState.change_request) || "",
    context: input.request.context,
    artifacts: artifactsFromState(fullState),
    state_excerpt: compactRecord({
      repo: input.request.repo || fullState.repo,
      branch: input.request.branch || fullState.branch,
      verification_mode: verificationMode,
      reference: input.request.reference || fullState.reference,
      server_path: fullState.server_path,
      wait_for_selector: fullState.wait_for_selector,
      implementation_status: fullState.implementation_status,
      implementation_summary: fullState.implementation_summary,
      changed_files: jsonCloneValue(fullState.changed_files),
      proof_plan: compactText(fullState.proof_plan, 1200)
    }),
    evidence_excerpt: compactRecord({
      before_cdn: fullState.before_cdn || null,
      prod_cdn: fullState.prod_cdn || null,
      after_cdn: fullState.after_cdn || null,
      visual_delta_required: visualDeltaRequired,
      visual_delta_ready: !visualDeltaRequired || visualDelta?.status === "measured" && visualDelta?.passed === true,
      visual_delta: jsonCloneRecord(visualDelta),
      evidence_issue_code: evidenceIssueCode2,
      proof_assessment_request: jsonCloneRecord(proofAssessmentRequest),
      verify_decision_request: jsonCloneRecord(fullState.verify_decision_request),
      checkpoint_contract: jsonCloneRecord(input.engineResult.checkpointContract)
    }),
    artifact_contract: jsonCloneRecord(artifactContract),
    allowed_decisions: [
      "ready_to_ship",
      "needs_richer_proof",
      "revise_capture",
      "needs_recon",
      "needs_implementation",
      "blocked",
      "human_review"
    ],
    response_schema: responseSchemaForProofAssessmentPacket(),
    routing_hint: {
      suggested_role: evidenceIssueCode2 ? "proof_judge" : "proof_judge",
      visibility: input.visibility || "quiet",
      urgency: evidenceIssueCode2 ? "high" : "normal",
      can_auto_answer: input.visibility !== "manual"
    },
    resume_token: resumeTokenFor({
      runId,
      statePath: input.engineResult.state_path || input.request.engine_state_path || null,
      checkpoint,
      stage
    }),
    created_at: input.created_at || timestamp()
  };
}
function buildCheckpointPacketForEngineResult(input) {
  const checkpoint = nonEmptyString(input.engineResult.checkpoint) || "";
  if (checkpoint === "verify_supervisor_judgment" || checkpoint === "verify_supervisor_judgment_required" || checkpoint === "verify_human_escalation") {
    return buildProofAssessmentCheckpointPacket(input);
  }
  const resume = recordValue(input.engineResult.checkpointContract?.resume);
  const continueStage = nonEmptyString(resume?.continue_with_stage);
  if (checkpoint === "author_supervisor_judgment" || checkpoint === "verify_capture_retry" || checkpoint === "verify_agent_retry" && continueStage === "author") {
    return buildAuthorCheckpointPacket(input);
  }
  return buildStageCheckpointPacket(input);
}
function normalizeCheckpointResponse(value) {
  const record = recordValue(value);
  if (!record) return null;
  const version = nonEmptyString(record.version);
  const runId = nonEmptyString(record.run_id);
  const checkpoint = nonEmptyString(record.checkpoint);
  const decision = nonEmptyString(record.decision);
  const summary = nonEmptyString(record.summary);
  if (version !== RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION || !runId || !checkpoint || !decision || !summary) {
    return null;
  }
  return compactRecord({
    version: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
    run_id: runId,
    checkpoint,
    resume_token: nonEmptyString(record.resume_token),
    decision,
    summary,
    payload: jsonCloneRecord(record.payload),
    reasons: Array.isArray(record.reasons) ? record.reasons.filter((item) => typeof item === "string") : void 0,
    continue_with_stage: nonEmptyString(record.continue_with_stage),
    source: jsonCloneRecord(record.source),
    created_at: nonEmptyString(record.created_at) || timestamp()
  });
}
function defaultContinueStage(packet, decision) {
  if (decision === "ready_for_author" || decision === "author_packet" || decision === "needs_author") return "author";
  if (decision === "implementation_complete") return "verify";
  if (decision === "ready_to_ship") return "ship";
  if (decision === "revise_capture") return "verify";
  if (decision === "retry_recon" || decision === "recon_stuck" || decision === "needs_recon") return "recon";
  if (decision === "needs_implementation") return "implement";
  if (decision === "continue_stage" || decision === "retry_stage") return packet.stage;
  return void 0;
}
function templatePayloadFor(packet, decision) {
  if (decision === "author_packet") {
    const expectedTerminalPath = packet.state_excerpt?.expected_terminal_path || packet.state_excerpt?.requested_expected_terminal_path || null;
    const expectedStartPath = packet.state_excerpt?.expected_start_path || packet.state_excerpt?.server_path || null;
    return {
      proof_plan: "TODO: describe the exact proof plan and stop condition.",
      capture_script: "TODO: provide the capture script that collects required artifacts/evidence.",
      refined_inputs: {
        server_path: packet.state_excerpt?.server_path || null,
        wait_for_selector: packet.state_excerpt?.wait_for_selector || null,
        reference: packet.state_excerpt?.reference || null,
        expected_start_path: expectedStartPath,
        expected_terminal_path: expectedTerminalPath
      },
      interaction_contract: {
        start_path: expectedStartPath,
        expected_terminal_path: expectedTerminalPath,
        action: "TODO: describe the browser interaction, for example click the visible Proof nav link.",
        assertions: []
      },
      summary: "TODO: summarize why this proof packet targets the requested change."
    };
  }
  if (decision === "implementation_complete") {
    return {
      changed_files: [],
      tests_run: [],
      implementation_notes: "TODO: summarize the direct edits made in the after worktree."
    };
  }
  if (decision === "ready_for_author") {
    return {
      baseline_understanding: {
        reference: "TODO",
        target_route: "TODO",
        before_evidence_url: "TODO",
        visible_before_state: "TODO",
        relevant_elements: [],
        requested_change: packet.change_request,
        proof_focus: "TODO",
        stop_condition: "TODO",
        quality_risks: []
      },
      refined_inputs: {
        server_path: null,
        wait_for_selector: null,
        reference: null
      }
    };
  }
  if (packet.kind === "assess_proof" || packet.kind === "recover_evidence" || packet.stage === "verify") {
    return {
      recommended_stage: defaultContinueStage(packet, decision) || packet.stage,
      evidence_issue_code: packet.evidence_excerpt?.evidence_issue_code || null,
      visual_delta: packet.evidence_excerpt?.visual_delta || null
    };
  }
  return void 0;
}
function createCheckpointResponseTemplate(packet, input = {}) {
  const allowed = Array.isArray(packet.allowed_decisions) ? packet.allowed_decisions : [];
  const decision = input.decision && allowed.includes(input.decision) ? input.decision : allowed[0] || "blocked";
  const continueStage = input.continue_with_stage || defaultContinueStage(packet, decision);
  return compactRecord({
    version: RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
    run_id: packet.run_id,
    checkpoint: packet.checkpoint,
    resume_token: packet.resume_token,
    decision,
    summary: input.summary || `TODO: explain checkpoint decision ${decision}.`,
    payload: input.payload || templatePayloadFor(packet, decision),
    reasons: input.reasons || ["TODO: replace with concrete reason(s)."],
    continue_with_stage: continueStage,
    source: {
      kind: input.source_kind || "codex"
    },
    created_at: input.created_at || timestamp()
  });
}
function checkpointSummaryFromState(state, engineStatePath) {
  const history = state.checkpoint_history || [];
  const packets = history.filter((entry) => entry.packet);
  const responses = history.filter((entry) => entry.response);
  const duplicateResponses = (state.events || []).filter((event) => event.kind === "checkpoint.response.duplicate");
  const latestPacketEntry = [...history].reverse().find((entry) => entry.packet);
  const latestResponseEntry = [...history].reverse().find((entry) => entry.response);
  const latestPacket = state.checkpoint_packet || latestPacketEntry?.packet;
  const latestResponse = latestResponseEntry?.response;
  const latestResumeToken = latestPacket?.resume_token || null;
  const latestResponseToken = latestResponse?.resume_token || null;
  const tokenMatches = !latestResponse ? null : latestResumeToken && latestResponseToken ? latestResumeToken === latestResponseToken : latestResumeToken || latestResponseToken ? false : null;
  return compactRecord({
    pending: Boolean(state.checkpoint_packet),
    packet_count: packets.length,
    response_count: responses.length,
    duplicate_response_count: duplicateResponses.length,
    latest_checkpoint: state.checkpoint_packet?.checkpoint || latestResponse?.checkpoint || state.last_checkpoint || null,
    latest_stage: state.checkpoint_packet?.stage || latestResponse?.continue_with_stage || state.current_stage || null,
    latest_kind: state.checkpoint_packet?.kind || latestPacket?.kind || null,
    latest_decision: latestResponse?.decision || null,
    latest_packet_summary: latestPacket?.summary || null,
    latest_response_summary: latestResponse?.summary || null,
    latest_resume_token: latestResumeToken,
    latest_response_token: latestResponseToken,
    token_matches: tokenMatches,
    last_packet_at: latestPacketEntry?.ts || null,
    last_response_at: latestResponseEntry?.ts || null,
    state_paths: statePathsForRunState(state, engineStatePath)
  });
}
function isDuplicateCheckpointResponse(state, response) {
  const identity = checkpointResponseIdentity(response);
  return (state.checkpoint_history || []).some((entry) => entry.response ? checkpointResponseIdentity(entry.response) === identity : false);
}
function checkpointResponseIdentity(response) {
  const logicalResponse = compactRecord({
    run_id: response.run_id,
    checkpoint: response.checkpoint,
    resume_token: response.resume_token,
    decision: response.decision,
    summary: response.summary,
    payload: response.payload,
    reasons: response.reasons,
    continue_with_stage: response.continue_with_stage,
    source: response.source
  });
  return import_node_crypto.default.createHash("sha256").update(stableJson(logicalResponse)).digest("hex").slice(0, 24);
}
function authorPacketPayloadFromCheckpointResponse(response) {
  if (response.decision !== "author_packet") return null;
  const payload = recordValue(response.payload);
  if (!payload) return null;
  const nested = recordValue(payload.author_packet);
  const candidate = nested || payload;
  if (!nonEmptyString(candidate.proof_plan) || !nonEmptyString(candidate.capture_script)) return null;
  return candidate;
}
function proofContractFromAuthorCheckpointResponse(response, packet, payload) {
  const refinedInputs = recordValue(payload.refined_inputs) || {};
  return compactRecord({
    version: "riddle-proof.proof-contract.v1",
    checkpoint: packet.checkpoint,
    source_response: compactRecord({
      run_id: response.run_id,
      checkpoint: response.checkpoint,
      resume_token: response.resume_token,
      decision: response.decision,
      summary: response.summary,
      created_at: response.created_at
    }),
    proof_plan: nonEmptyString(payload.proof_plan),
    capture_script: nonEmptyString(payload.capture_script),
    artifact_contract: jsonCloneRecord(payload.artifact_contract),
    assertions: jsonCloneValue(payload.assertions),
    interaction_contract: jsonCloneRecord(payload.interaction_contract) || jsonCloneRecord(payload.interactionContract),
    baseline_understanding: jsonCloneRecord(payload.baseline_understanding) || jsonCloneRecord(payload.recon_baseline_understanding) || jsonCloneRecord(packet.state_excerpt?.recon_baseline_understanding),
    route_assumptions: compactRecord({
      server_path: nonEmptyString(refinedInputs.server_path) || nonEmptyString(payload.server_path) || nonEmptyString(packet.state_excerpt?.server_path),
      wait_for_selector: nonEmptyString(refinedInputs.wait_for_selector) || nonEmptyString(payload.wait_for_selector) || nonEmptyString(packet.state_excerpt?.wait_for_selector),
      reference: nonEmptyString(refinedInputs.reference) || nonEmptyString(payload.reference),
      expected_path: nonEmptyString(payload.expected_path) || nonEmptyString(refinedInputs.expected_path),
      expected_terminal_path: nonEmptyString(refinedInputs.expected_terminal_path) || nonEmptyString(payload.expected_terminal_path) || nonEmptyString(refinedInputs.expected_after_path) || nonEmptyString(payload.expected_after_path)
    }),
    stop_condition: nonEmptyString(payload.stop_condition),
    rationale: jsonCloneValue(payload.rationale),
    verdict_dimensions: jsonCloneRecord(payload.verdict_dimensions),
    payload: jsonCloneRecord(payload),
    created_at: timestamp()
  });
}

// src/run-card.ts
var RIDDLE_PROOF_RUN_CARD_VERSION = "riddle-proof.run-card.v1";
function elapsedMs(start, end) {
  const startMs = start ? Date.parse(start) : NaN;
  const endMs = end ? Date.parse(end) : NaN;
  if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
  return Math.max(0, endMs - startMs);
}
function jsonCloneRecord2(value) {
  const record = recordValue(value);
  if (!record) return void 0;
  try {
    return JSON.parse(JSON.stringify(record));
  } catch {
    return { ...record };
  }
}
function compactText2(value, limit = 600) {
  const text = nonEmptyString(value);
  if (!text) return void 0;
  return text.length <= limit ? text : `${text.slice(0, limit - 20).trimEnd()}...`;
}
function numericValue(value) {
  const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
  return Number.isFinite(number) ? number : void 0;
}
function eventDetails(event) {
  return recordValue(recordValue(event)?.details) || {};
}
function collectRunnerMetrics(details) {
  const metrics = [];
  const adapterDetails = recordValue(details.adapter_details);
  const direct = recordValue(adapterDetails?.runner_metrics);
  if (direct) metrics.push(direct);
  const attempts = Array.isArray(adapterDetails?.attempt_summaries) ? adapterDetails.attempt_summaries : [];
  for (const attempt of attempts) {
    const attemptMetrics = recordValue(recordValue(attempt)?.runner_metrics);
    if (attemptMetrics) metrics.push(attemptMetrics);
  }
  return metrics;
}
function observabilityFrom(state) {
  const engineEvents = state.events.filter((event) => event.kind === "engine.result").map((event) => ({ event, details: eventDetails(event) }));
  const agentEvents = state.events.filter((event) => event.kind.startsWith("agent.")).map((event) => ({ event, details: eventDetails(event) })).filter(({ details }) => numericValue(details.duration_ms) !== void 0);
  const retryEvents = state.events.filter((event) => /retry|recovery/i.test(event.kind) || /retry|recovery/i.test(event.summary || "")).slice(-8);
  const runnerMetrics = agentEvents.flatMap(({ details }) => collectRunnerMetrics(details));
  const promptChars = runnerMetrics.map((metrics) => numericValue(metrics.prompt_chars)).filter((value) => value !== void 0);
  const sum = (values) => values.reduce((total, value) => total + (value ?? 0), 0);
  const recentEngineTimings = engineEvents.slice(-8).map(({ event, details }) => compactRecord({
    checkpoint: event.checkpoint || null,
    stage: event.stage || null,
    duration_ms: numericValue(details.duration_ms),
    ok: details.ok ?? null
  }));
  const recentAgentTimings = agentEvents.slice(-8).map(({ event, details }) => {
    const metrics = collectRunnerMetrics(details);
    const localPromptChars = metrics.map((item) => numericValue(item.prompt_chars)).filter((value) => value !== void 0);
    return compactRecord({
      kind: event.kind,
      checkpoint: event.checkpoint || null,
      stage: event.stage || null,
      duration_ms: numericValue(details.duration_ms),
      prompt_chars: localPromptChars.length ? Math.max(...localPromptChars) : void 0,
      attempt_count: numericValue(recordValue(details.adapter_details)?.attempt_count)
    });
  });
  return compactRecord({
    engine_call_count: engineEvents.length,
    agent_call_count: agentEvents.length,
    engine_total_ms: sum(engineEvents.map(({ details }) => numericValue(details.duration_ms))),
    agent_total_ms: sum(agentEvents.map(({ details }) => numericValue(details.duration_ms))),
    max_agent_prompt_chars: promptChars.length ? Math.max(...promptChars) : void 0,
    total_agent_prompt_chars: promptChars.length ? sum(promptChars) : void 0,
    recent_engine_timings: recentEngineTimings.length ? recentEngineTimings : void 0,
    recent_agent_timings: recentAgentTimings.length ? recentAgentTimings : void 0,
    retry_event_count: retryEvents.length,
    recent_retry_reasons: retryEvents.length ? retryEvents.map((event) => compactRecord({
      kind: event.kind,
      checkpoint: event.checkpoint || null,
      stage: event.stage || null,
      summary: compactText2(event.summary, 240)
    })) : void 0
  });
}
function visualDeltaFrom(input) {
  const fullState = input.fullRiddleState || {};
  const bundle = recordValue(fullState.evidence_bundle);
  const after = recordValue(bundle?.after);
  const afterDelta = recordValue(after?.visual_delta);
  if (afterDelta && Object.keys(afterDelta).length) return afterDelta;
  const requestDelta = recordValue(recordValue(fullState.proof_assessment_request)?.visual_delta);
  if (requestDelta && Object.keys(requestDelta).length) return requestDelta;
  const packetDelta = recordValue(input.runState.checkpoint_packet?.evidence_excerpt?.visual_delta);
  return packetDelta && Object.keys(packetDelta).length ? packetDelta : void 0;
}
function artifactsFrom(input) {
  const packetArtifacts = input.runState.checkpoint_packet?.artifacts;
  if (packetArtifacts?.length) return packetArtifacts.slice(0, 12);
  const fullState = input.fullRiddleState || {};
  const artifacts = [];
  for (const role of ["before", "prod", "after"]) {
    const url = nonEmptyString(fullState[`${role}_cdn`]) || nonEmptyString(input.runState[`${role}_artifact_url`]);
    if (url) artifacts.push({ role, url, name: `${role}.png`, mime_type: "image/png" });
  }
  return artifacts.length ? artifacts : void 0;
}
function viewportMatrixFrom(input) {
  const fullState = input.fullRiddleState || {};
  const bundle = recordValue(fullState.evidence_bundle);
  const fromBundle = recordValue(bundle?.viewport_matrix);
  if (fromBundle && Object.keys(fromBundle).length) return jsonCloneRecord2(fromBundle);
  const fromRequest = recordValue(recordValue(fullState.proof_assessment_request)?.viewport_matrix);
  if (fromRequest && Object.keys(fromRequest).length) return jsonCloneRecord2(fromRequest);
  const fromState = recordValue(fullState.viewport_matrix_status) || recordValue(input.runState.viewport_matrix_status);
  return fromState && Object.keys(fromState).length ? jsonCloneRecord2(fromState) : void 0;
}
function ownerFor(state) {
  if (state.status === "awaiting_checkpoint") {
    const role = nonEmptyString(state.checkpoint_packet?.routing_hint?.suggested_role);
    return role || "supervising_agent";
  }
  if (state.status === "running") return "engine";
  if (state.status === "blocked" || state.status === "failed") return "human_or_operator";
  return "none";
}
function actionFor(state) {
  if (state.status === "awaiting_checkpoint") return state.checkpoint_packet?.question || "Answer the pending checkpoint.";
  if (state.status === "running") return "Continue the current Riddle Proof stage.";
  if (state.status === "blocked" || state.status === "failed") return state.blocker?.message || "Inspect the blocker and decide whether a new run or infrastructure repair is needed.";
  if (state.status === "ready_to_ship") return "Ship is held by policy; review PR/ship policy before advancing.";
  return "No next action; run is terminal.";
}
function evidenceIssueCode(input) {
  const packetIssue = nonEmptyString(input.runState.checkpoint_packet?.evidence_excerpt?.evidence_issue_code);
  if (packetIssue) return packetIssue;
  const assessmentIssue = nonEmptyString(recordValue(input.fullRiddleState?.proof_assessment)?.evidence_issue_code);
  if (assessmentIssue) return assessmentIssue;
  const delta = visualDeltaFrom(input);
  const status = nonEmptyString(delta?.status);
  if (status === "unmeasured") {
    const reason = `${nonEmptyString(delta?.reason) || ""}
${input.runState.blocker?.message || ""}`.toLowerCase();
    return reason.includes("fetch") || reason.includes("allowlist") || reason.includes("registered domain") || reason.includes("high risk") || reason.includes("comparator") ? "comparator_fetch_blocked" : "visual_delta_unmeasured";
  }
  if (status === "measured" && delta?.passed === false) return "semantic_proof_failed";
  return void 0;
}
function createRiddleProofRunCard(state, input = {}) {
  const at = input.at || (/* @__PURE__ */ new Date()).toISOString();
  const fullState = input.fullRiddleState || {};
  const packet = state.checkpoint_packet;
  const latestEvent = state.events[state.events.length - 1];
  const bundle = recordValue(fullState.evidence_bundle);
  const artifactContract = jsonCloneRecord2(packet?.artifact_contract) || jsonCloneRecord2(recordValue(fullState.proof_assessment_request)?.artifact_contract) || jsonCloneRecord2(recordValue(bundle?.artifact_contract)) || jsonCloneRecord2(state.proof_contract?.artifact_contract);
  const required = jsonCloneRecord2(recordValue(artifactContract)?.required);
  const statePaths = input.state_paths || state.state_paths || statePathsForRunState(state);
  const visualDelta = visualDeltaFrom({ fullRiddleState: fullState, runState: state });
  const artifacts = artifactsFrom({ fullRiddleState: fullState, runState: state });
  const viewportMatrix = viewportMatrixFrom({ fullRiddleState: fullState, runState: state });
  return {
    version: RIDDLE_PROOF_RUN_CARD_VERSION,
    run_id: state.run_id || "unknown",
    status: state.status,
    goal: compactRecord({
      repo: state.request.repo || nonEmptyString(fullState.repo),
      branch: state.request.branch || nonEmptyString(fullState.branch),
      change_request: state.request.change_request || nonEmptyString(fullState.change_request),
      verification_mode: state.request.verification_mode || nonEmptyString(fullState.verification_mode),
      success_criteria: state.request.success_criteria
    }),
    durable_state: compactRecord({
      ...statePaths,
      worktree_path: state.worktree_path || nonEmptyString(fullState.after_worktree) || null,
      branch: state.branch || nonEmptyString(fullState.branch) || null
    }),
    current_phase: compactRecord({
      stage: state.current_stage ?? null,
      checkpoint: state.last_checkpoint ?? packet?.checkpoint ?? null,
      latest_event: latestEvent?.kind ?? null,
      elapsed_ms: elapsedMs(state.created_at, at),
      stage_elapsed_ms: elapsedMs(state.stage_started_at, at),
      iterations: state.iterations
    }),
    owner_next_action: compactRecord({
      owner: ownerFor(state),
      action: actionFor(state),
      checkpoint_kind: packet?.kind || null,
      allowed_decisions: packet?.allowed_decisions,
      retryable: state.status === "running" || state.status === "awaiting_checkpoint",
      reason: state.blocker?.code || packet?.summary || latestEvent?.summary || null
    }),
    evidence_contract: compactRecord({
      verification_mode: state.request.verification_mode || nonEmptyString(fullState.verification_mode),
      required,
      artifact_contract: artifactContract,
      proof_plan: compactText2(state.proof_contract?.proof_plan || fullState.proof_plan, 600),
      stop_condition: compactText2(state.proof_contract?.stop_condition, 400)
    }),
    latest_evidence: compactRecord({
      before_url: nonEmptyString(fullState.before_cdn) || state.before_artifact_url || null,
      prod_url: nonEmptyString(fullState.prod_cdn) || state.prod_artifact_url || null,
      after_url: nonEmptyString(fullState.after_cdn) || state.after_artifact_url || null,
      visual_delta: visualDelta || null,
      evidence_issue_code: evidenceIssueCode({ fullRiddleState: fullState, runState: state }) || null,
      proof_evidence_present: fullState.proof_evidence_present === true || Boolean(bundle?.proof_evidence || bundle?.proof_evidence_sample),
      viewport_matrix: viewportMatrix,
      artifacts
    }),
    observability: observabilityFrom(state),
    stop_condition: compactRecord({
      status: state.status,
      terminal: isTerminalStatus(state.status),
      blocker_code: state.blocker?.code || null,
      blocker_message: state.blocker?.message || null,
      proof_decision: state.proof_decision,
      merge_recommendation: state.merge_recommendation,
      monitor_should_continue: !isTerminalStatus(state.status)
    }),
    updated_at: state.updated_at
  };
}

// src/state.ts
var RIDDLE_PROOF_RUN_STATE_VERSION = "riddle-proof.run-state.v1";
function timestamp2() {
  return (/* @__PURE__ */ new Date()).toISOString();
}
function createRunId(createdAt) {
  const stamp = createdAt.replace(/\D/g, "").slice(0, 14) || "unknown";
  const entropy = Math.random().toString(36).slice(2, 8) || "run";
  return `rp_${stamp}_${entropy}`;
}
function elapsedMs2(start, end) {
  const startMs = start ? Date.parse(start) : NaN;
  const endMs = end ? Date.parse(end) : NaN;
  if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return void 0;
  return Math.max(0, endMs - startMs);
}
function normalizePrStatus2(value) {
  const status = nonEmptyString(value)?.toLowerCase();
  if (status === "merged") return "merged";
  if (status === "open") return "open";
  if (status === "closed") return "closed";
  if (status === "not_found" || status === "not-found") return "not_found";
  if (status === "unavailable") return "unavailable";
  return status || "unknown";
}
function normalizePrLifecycleState(input, checkedAt = timestamp2()) {
  const value = recordValue(input);
  if (!value) return void 0;
  const cleanup = recordValue(value.cleanup);
  const mergeCommit = nonEmptyString(value.merge_commit) || nonEmptyString(value.mergeCommit) || nonEmptyString(recordValue(value.mergeCommit)?.oid);
  return compactRecord({
    status: normalizePrStatus2(value.status || value.state),
    pr_url: nonEmptyString(value.pr_url) || nonEmptyString(value.prUrl) || nonEmptyString(value.url),
    pr_number: nonEmptyString(value.pr_number) || nonEmptyString(value.prNumber) || (typeof value.number === "number" ? String(value.number) : void 0),
    repo: nonEmptyString(value.repo) || nonEmptyString(value.repository),
    head_branch: nonEmptyString(value.head_branch) || nonEmptyString(value.headBranch) || nonEmptyString(value.headRefName),
    base_branch: nonEmptyString(value.base_branch) || nonEmptyString(value.baseBranch) || nonEmptyString(value.baseRefName),
    merge_commit: mergeCommit,
    merged_at: nonEmptyString(value.merged_at) || nonEmptyString(value.mergedAt),
    closed_at: nonEmptyString(value.closed_at) || nonEmptyString(value.closedAt),
    checked_at: nonEmptyString(value.checked_at) || nonEmptyString(value.checkedAt) || checkedAt,
    source: nonEmptyString(value.source),
    next_action: nonEmptyString(value.next_action) || nonEmptyString(value.nextAction),
    cleanup: cleanup && Object.keys(cleanup).length ? cleanup : void 0
  });
}
function normalizeIntegrationContext(input, fallbackSource) {
  const value = recordValue(input);
  if (!value) {
    return fallbackSource ? { source: fallbackSource } : void 0;
  }
  const metadata = recordValue(value.metadata);
  return compactRecord({
    source: nonEmptyString(value.source) || fallbackSource,
    channel_id: nonEmptyString(value.channel_id),
    thread_id: nonEmptyString(value.thread_id),
    message_id: nonEmptyString(value.message_id),
    source_url: nonEmptyString(value.source_url),
    metadata: metadata && Object.keys(metadata).length ? metadata : void 0
  });
}
function normalizeRunParams(input) {
  return compactRecord({
    repo: input.repo,
    branch: input.branch,
    change_request: input.change_request,
    commit_message: input.commit_message,
    prod_url: input.prod_url,
    capture_script: input.capture_script,
    success_criteria: input.success_criteria,
    assertions: input.assertions,
    verification_mode: input.verification_mode,
    resume_session: input.resume_session,
    target_image_url: input.target_image_url,
    target_image_hash: input.target_image_hash,
    viewport_matrix: input.viewport_matrix,
    deterministic_setup: input.deterministic_setup,
    reference: input.reference,
    base_branch: input.base_branch,
    before_ref: input.before_ref,
    allow_static_preview_fallback: input.allow_static_preview_fallback,
    context: input.context,
    reviewer: input.reviewer,
    mode: input.mode,
    implementation_mode: input.implementation_mode,
    require_diff: input.require_diff,
    allow_code_changes: input.allow_code_changes,
    build_command: input.build_command,
    build_output: input.build_output,
    server_image: input.server_image,
    server_command: input.server_command,
    server_port: input.server_port,
    server_path: input.server_path,
    use_auth: input.use_auth,
    auth_localStorage_json: input.auth_localStorage_json,
    auth_cookies_json: input.auth_cookies_json,
    auth_headers_json: input.auth_headers_json,
    color_scheme: input.color_scheme,
    wait_for_selector: input.wait_for_selector,
    ship_mode: input.ship_mode,
    leave_draft: input.leave_draft,
    engine_state_path: input.engine_state_path,
    harness_state_path: input.harness_state_path,
    riddle_engine_module_url: input.riddle_engine_module_url,
    max_iterations: input.max_iterations,
    auto_approve: input.auto_approve,
    dry_run: input.dry_run,
    integration_context: normalizeIntegrationContext(input.integration_context)
  });
}
function createRunState(input) {
  const createdAt = input.created_at || timestamp2();
  return compactRecord({
    version: RIDDLE_PROOF_RUN_STATE_VERSION,
    run_id: input.run_id || createRunId(createdAt),
    state_path: input.state_path,
    worktree_path: input.worktree_path,
    branch: input.branch || input.request.branch,
    current_stage: input.current_stage ?? null,
    stage_started_at: input.stage_started_at ?? null,
    status: input.status || "running",
    created_at: createdAt,
    updated_at: input.updated_at || createdAt,
    request: normalizeRunParams(input.request),
    iterations: input.iterations ?? 0,
    last_checkpoint: input.last_checkpoint ?? null,
    checkpoint_packet: input.checkpoint_packet,
    checkpoint_summary: input.checkpoint_summary,
    state_paths: input.state_paths,
    proof_contract: input.proof_contract,
    run_card: input.run_card,
    checkpoint_history: input.checkpoint_history,
    events: input.events ? [...input.events] : []
  });
}
function appendRunEvent(state, input) {
  const event = {
    ts: input.ts || timestamp2(),
    kind: input.kind,
    checkpoint: input.checkpoint,
    stage: input.stage,
    summary: input.summary,
    details: input.details
  };
  state.events.push(compactRecord({
    ts: event.ts,
    kind: event.kind,
    checkpoint: event.checkpoint,
    stage: event.stage,
    summary: event.summary,
    details: event.details
  }));
  if (input.checkpoint !== void 0) state.last_checkpoint = input.checkpoint;
  if (input.stage !== void 0) {
    if (state.current_stage !== input.stage) state.stage_started_at = event.ts;
    state.current_stage = input.stage;
  }
  state.updated_at = event.ts;
  return state;
}
function appendStageHeartbeat(state, input) {
  const at = input.ts || timestamp2();
  return appendRunEvent(state, {
    ts: at,
    kind: "stage.heartbeat",
    checkpoint: input.checkpoint || `${input.stage}_heartbeat`,
    stage: input.stage,
    summary: input.summary || `${input.stage} stage is active.`,
    details: compactRecord({
      elapsed_ms: elapsedMs2(state.created_at, at),
      stage_elapsed_ms: elapsedMs2(state.stage_started_at, at),
      wait_reason: input.wait_reason,
      blocker: input.blocker,
      ...input.details
    })
  });
}
function createRunStatusSnapshot(state, at = timestamp2()) {
  const latestEvent = state.events[state.events.length - 1];
  const runId = state.run_id || "unknown";
  const existingRunCardCurrent = state.run_card?.status === state.status && state.run_card.stop_condition?.status === state.status && state.run_card.stop_condition?.terminal === isTerminalStatus(state.status) && state.run_card.stop_condition?.monitor_should_continue === !isTerminalStatus(state.status);
  const runCard = existingRunCardCurrent ? state.run_card : createRiddleProofRunCard(state, { at });
  return compactRecord({
    run_id: runId,
    status: state.status,
    is_terminal: isTerminalStatus(state.status),
    monitor_should_continue: !isTerminalStatus(state.status),
    current_stage: state.current_stage ?? null,
    state_path: state.state_path ?? null,
    worktree_path: state.worktree_path ?? null,
    branch: state.branch ?? null,
    pr_url: state.pr_url ?? null,
    pr_branch: state.pr_branch ?? null,
    pr_state: state.pr_state,
    ci_status: state.ci_status,
    ship_commit: state.ship_commit,
    ship_remote_head: state.ship_remote_head,
    merge_commit: state.merge_commit,
    merged_at: state.merged_at,
    proof_comment_url: state.proof_comment_url,
    cleanup_report: state.cleanup_report,
    iterations: state.iterations,
    last_checkpoint: state.last_checkpoint ?? null,
    updated_at: state.updated_at,
    elapsed_ms: elapsedMs2(state.created_at, at),
    stage_elapsed_ms: elapsedMs2(state.stage_started_at, at),
    blocker: state.blocker,
    checkpoint_packet: state.checkpoint_packet,
    checkpoint_summary: state.checkpoint_summary,
    state_paths: state.state_paths,
    proof_contract: state.proof_contract,
    run_card: runCard,
    viewport_matrix_status: state.viewport_matrix_status,
    latest_event: latestEvent
  });
}
function setRunStatus(state, status, at = timestamp2()) {
  state.status = status;
  state.ok = status !== "blocked" && status !== "failed";
  state.updated_at = at;
  return state;
}
function applyPrLifecycleState(state, input, at = timestamp2()) {
  const prState = normalizePrLifecycleState(input, at);
  if (!prState) return state;
  state.pr_state = prState;
  if (prState.pr_url) state.pr_url = prState.pr_url;
  if (prState.head_branch) state.pr_branch = prState.head_branch;
  if (prState.merge_commit) state.merge_commit = prState.merge_commit;
  if (prState.merged_at) state.merged_at = prState.merged_at;
  if (prState.cleanup) state.cleanup_report = prState.cleanup;
  if (prState.status === "merged") {
    state.finalized = true;
    state.status = "completed";
    state.ok = true;
  }
  state.updated_at = at;
  return state;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  RIDDLE_PROOF_CHECKPOINT_PACKET_VERSION,
  RIDDLE_PROOF_CHECKPOINT_RESPONSE_VERSION,
  RIDDLE_PROOF_RUN_CARD_VERSION,
  RIDDLE_PROOF_RUN_STATE_VERSION,
  appendRunEvent,
  appendStageHeartbeat,
  applyPrLifecycleState,
  applyTerminalMetadata,
  authorPacketPayloadFromCheckpointResponse,
  buildAuthorCheckpointPacket,
  buildCheckpointPacketForEngineResult,
  buildProofAssessmentCheckpointPacket,
  buildStageCheckpointPacket,
  checkpointResponseIdentity,
  checkpointSummaryFromState,
  compactRecord,
  createCheckpointResponseTemplate,
  createRiddleProofRunCard,
  createRunResult,
  createRunState,
  createRunStatusSnapshot,
  isDuplicateCheckpointResponse,
  isSuccessfulStatus,
  isTerminalStatus,
  nonEmptyString,
  normalizeCheckpointResponse,
  normalizeIntegrationContext,
  normalizePrLifecycleState,
  normalizeRunParams,
  normalizeTerminalMetadata,
  proofContractFromAuthorCheckpointResponse,
  recordValue,
  setRunStatus,
  statePathsForRunState
});
