"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/state.ts
var state_exports = {};
__export(state_exports, {
  RIDDLE_PROOF_RUN_STATE_VERSION: () => RIDDLE_PROOF_RUN_STATE_VERSION,
  appendRunEvent: () => appendRunEvent,
  appendStageHeartbeat: () => appendStageHeartbeat,
  applyPrLifecycleState: () => applyPrLifecycleState,
  createRunState: () => createRunState,
  createRunStatusSnapshot: () => createRunStatusSnapshot,
  normalizeIntegrationContext: () => normalizeIntegrationContext,
  normalizePrLifecycleState: () => normalizePrLifecycleState,
  normalizeRunParams: () => normalizeRunParams,
  setRunStatus: () => setRunStatus
});
module.exports = __toCommonJS(state_exports);

// src/result.ts
function isTerminalStatus(status) {
  return status === "blocked" || status === "failed" || status === "ready_to_ship" || status === "shipped" || status === "completed";
}
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;
}

// src/checkpoint.ts
var import_node_crypto = __toESM(require("crypto"), 1);
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
  });
}

// 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 jsonCloneRecord(value) {
  const record = recordValue(value);
  if (!record) return void 0;
  try {
    return JSON.parse(JSON.stringify(record));
  } catch {
    return { ...record };
  }
}
function compactText(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: compactText(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 jsonCloneRecord(fromBundle);
  const fromRequest = recordValue(recordValue(fullState.proof_assessment_request)?.viewport_matrix);
  if (fromRequest && Object.keys(fromRequest).length) return jsonCloneRecord(fromRequest);
  const fromState = recordValue(fullState.viewport_matrix_status) || recordValue(input.runState.viewport_matrix_status);
  return fromState && Object.keys(fromState).length ? jsonCloneRecord(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 = jsonCloneRecord(packet?.artifact_contract) || jsonCloneRecord(recordValue(fullState.proof_assessment_request)?.artifact_contract) || jsonCloneRecord(recordValue(bundle?.artifact_contract)) || jsonCloneRecord(state.proof_contract?.artifact_contract);
  const required = jsonCloneRecord(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: compactText(state.proof_contract?.proof_plan || fullState.proof_plan, 600),
      stop_condition: compactText(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 timestamp() {
  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 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 normalizePrLifecycleState(input, checkedAt = timestamp()) {
  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: normalizePrStatus(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 || timestamp();
  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 || timestamp(),
    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 || timestamp();
  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 = timestamp()) {
  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 = timestamp()) {
  state.status = status;
  state.ok = status !== "blocked" && status !== "failed";
  state.updated_at = at;
  return state;
}
function applyPrLifecycleState(state, input, at = timestamp()) {
  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_RUN_STATE_VERSION,
  appendRunEvent,
  appendStageHeartbeat,
  applyPrLifecycleState,
  createRunState,
  createRunStatusSnapshot,
  normalizeIntegrationContext,
  normalizePrLifecycleState,
  normalizeRunParams,
  setRunStatus
});
