"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/advanced/runner.ts
var runner_exports = {};
__export(runner_exports, {
  runRiddleProof: () => runRiddleProof
});
module.exports = __toCommonJS(runner_exports);

// src/public-state.ts
function riddleProofPublicStateAllowsClaim(summary, claim) {
  return !summary?.prohibited_claims.includes(claim);
}
function riddleProofPublicStateAllowsMergeRecommendation(summary) {
  return riddleProofPublicStateAllowsClaim(summary, "merge_ready") && riddleProofPublicStateAllowsClaim(summary, "sync_allowed");
}
function riddleProofPublicStateMergeRecommendation(summary, recommendation) {
  return recommendation && riddleProofPublicStateAllowsMergeRecommendation(summary) ? recommendation : void 0;
}
function asRecord(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}
function stringValue(value) {
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
}
function booleanValue(value) {
  return typeof value === "boolean" ? value : void 0;
}
function numberValue(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function firstStringValue(...values) {
  for (const value of values) {
    const text = stringValue(value);
    if (text) return text;
  }
  return void 0;
}
function firstBooleanValue(...values) {
  for (const value of values) {
    const bool = booleanValue(value);
    if (typeof bool === "boolean") return bool;
  }
  return void 0;
}
function firstRecordValue(...values) {
  for (const value of values) {
    const record = asRecord(value);
    if (Object.keys(record).length) return record;
  }
  return void 0;
}
function countValue(value) {
  const number = numberValue(value);
  return typeof number === "number" && number > 0 ? Math.trunc(number) : 0;
}
function checkpointSummaryFrom(...values) {
  const record = firstRecordValue(...values);
  if (!record) return void 0;
  const accepted = countValue(record.response_count);
  const rejected = countValue(record.rejected_response_count);
  const ignored = countValue(record.ignored_response_count);
  const duplicate = countValue(record.duplicate_response_count);
  const summary = {
    pending: booleanValue(record.pending),
    accepted_response_count: accepted,
    rejected_response_count: rejected,
    ignored_response_count: ignored,
    duplicate_response_count: duplicate,
    latest_decision: stringValue(record.latest_decision),
    audit_disclosure_required: rejected > 0 || ignored > 0 || duplicate > 0
  };
  return Object.values(summary).some((value) => typeof value !== "undefined") ? summary : void 0;
}
function uniqueStrings(values) {
  return [...new Set(values.filter(Boolean))];
}
function statusIsProofFailed(status) {
  return status === "failed" || status === "product_regression";
}
function statusIsProofBlocked(status) {
  return status === "blocked" || status === "proof_insufficient" || status === "environment_blocked" || status === "configuration_error" || status === "needs_human_review";
}
function statusRequiresDisclosure(status) {
  if (status === "proof_insufficient") return "proof_insufficient";
  if (status === "environment_blocked") return "environment_blocked";
  if (status === "configuration_error") return "configuration_error";
  if (status === "needs_human_review") return "human_review_required";
  return void 0;
}
function summarizeRiddleProofPublicState(input) {
  const record = asRecord(input);
  const runCard = asRecord(record.run_card);
  const stopCondition = asRecord(runCard.stop_condition);
  const raw = asRecord(record.raw);
  const request = asRecord(record.request);
  const requestMetadata = asRecord(record.request_metadata);
  const prState = asRecord(record.pr_state);
  const handoff = asRecord(record.pr_handoff_policy);
  const handoffState = stringValue(handoff.state);
  const status = firstStringValue(record.status, stopCondition.status);
  const ok = booleanValue(record.ok) ?? null;
  const shipMode = firstStringValue(request.ship_mode, requestMetadata.ship_mode, record.ship_mode, handoff.ship_mode);
  const explicitShippingDisabled = firstBooleanValue(
    record.shipping_disabled,
    stopCondition.shipping_disabled,
    raw.shipping_disabled,
    handoff.shipping_disabled
  );
  const shippingDisabled = explicitShippingDisabled === true || shipMode === "none" || handoffState === "proof_complete_ship_disabled";
  const explicitShipAuthorized = firstBooleanValue(
    record.ship_authorized,
    stopCondition.ship_authorized,
    raw.ship_authorized
  );
  const authorizationEvidence = Boolean(
    status === "shipped" || record.marked_ready === true || stringValue(prState.status) === "merged" || record.merge_commit || record.merged_at
  );
  const shipAuthorizedBeforeHold = explicitShipAuthorized ?? authorizationEvidence;
  const explicitShipHeld = firstBooleanValue(record.ship_held, stopCondition.ship_held, raw.ship_held);
  const inferredHeld = status === "ready_to_ship" && shippingDisabled && !shipAuthorizedBeforeHold;
  const shipHeld = explicitShipHeld === true || inferredHeld;
  const shipAuthorized = shipHeld ? false : shipAuthorizedBeforeHold === true;
  const proofComplete = Boolean(
    status === "ready_to_ship" || status === "shipped" || status === "completed" || status === "passed" || ok === true || handoff.proof_complete === true
  );
  const checkpointSummary = checkpointSummaryFrom(
    record.checkpoint_summary,
    stopCondition.checkpoint_summary,
    asRecord(record.details).checkpoint_summary,
    asRecord(raw.details).checkpoint_summary
  );
  const blockedOrWaiting = statusIsProofBlocked(status) || statusIsProofFailed(status) || status === "awaiting_checkpoint" || handoffState === "proof_blocked" || handoffState === "proof_review_required" || handoffState === "proof_failed" || handoffState === "proof_checkpoint_required";
  const proofPassed = Boolean(proofComplete && !blockedOrWaiting);
  const explicitMergeReady = firstBooleanValue(record.merge_ready, stopCondition.merge_ready, raw.merge_ready, handoff.merge_ready);
  const normalPrAllowed = firstBooleanValue(record.normal_pr_allowed, raw.normal_pr_allowed, handoff.normal_pr_allowed);
  const baseHandoffAllowed = !blockedOrWaiting && !shipHeld && !shippingDisabled;
  const mergeReady = baseHandoffAllowed && normalPrAllowed !== false && (explicitMergeReady ?? shipAuthorized);
  const syncAllowed = mergeReady;
  let policyState = "unknown";
  if (status === "awaiting_checkpoint" || handoffState === "proof_checkpoint_required") policyState = "awaiting_checkpoint";
  else if (statusIsProofFailed(status) || handoffState === "proof_failed") policyState = "proof_failed";
  else if (statusIsProofBlocked(status) || handoffState === "proof_blocked" || handoffState === "proof_review_required") policyState = "proof_blocked";
  else if (handoffState === "proof_complete_ship_disabled") policyState = "proof_complete_ship_disabled";
  else if (proofComplete && shipHeld && !shipAuthorized) policyState = "proof_passed_ship_held";
  else if (proofComplete && shippingDisabled && !shipAuthorized) policyState = "proof_complete_ship_disabled";
  else if (shipAuthorized) policyState = "ship_authorized";
  else if (proofPassed) policyState = "proof_passed";
  else if (status === "running") policyState = "proof_in_progress";
  const requiredDisclosures = [];
  if (shipHeld) requiredDisclosures.push("ship_held");
  if (shippingDisabled) requiredDisclosures.push("shipping_disabled");
  if (checkpointSummary?.audit_disclosure_required) requiredDisclosures.push("checkpoint_audit_counters");
  if (status === "awaiting_checkpoint" || handoffState === "proof_checkpoint_required") requiredDisclosures.push("checkpoint_required");
  const statusDisclosure = statusRequiresDisclosure(status);
  if (statusDisclosure) requiredDisclosures.push(statusDisclosure);
  const prohibitedClaims = [];
  if (!shipAuthorized || shipHeld || shippingDisabled) prohibitedClaims.push("ship_authorized", "shipped");
  if (!mergeReady) prohibitedClaims.push("merge_ready");
  if (!syncAllowed) prohibitedClaims.push("sync_allowed");
  if (blockedOrWaiting) {
    prohibitedClaims.push("proof_passed", "ready_to_ship");
  }
  if (checkpointSummary?.audit_disclosure_required) {
    prohibitedClaims.push("all_checkpoint_responses_accepted");
  }
  const resultLabel = status === "product_regression" ? "product_regression" : status === "proof_insufficient" ? "proof_insufficient" : status === "environment_blocked" ? "environment_blocked" : status === "configuration_error" ? "configuration_error" : status === "needs_human_review" ? "needs_human_review" : policyState === "awaiting_checkpoint" ? "checkpoint required" : policyState === "proof_blocked" ? "blocked" : policyState === "proof_failed" ? "failed" : policyState === "proof_complete_ship_disabled" ? "proof complete; shipping disabled" : policyState === "proof_passed_ship_held" ? "proof passed; ship held" : policyState === "ship_authorized" ? status === "shipped" ? "shipped" : "ship authorized" : policyState === "proof_passed" ? "passed" : policyState === "proof_in_progress" ? "running" : status || "recorded";
  return {
    status,
    ok,
    policy_state: policyState,
    result_label: resultLabel,
    proof_complete: proofComplete,
    proof_passed: proofPassed,
    ship_held: shipHeld,
    shipping_disabled: shippingDisabled,
    ship_authorized: shipAuthorized,
    merge_ready: mergeReady,
    sync_allowed: syncAllowed,
    checkpoint_summary: checkpointSummary,
    required_disclosures: uniqueStrings(requiredDisclosures),
    prohibited_claims: uniqueStrings(prohibitedClaims)
  };
}

// src/result.ts
function isTerminalStatus(status) {
  return status === "blocked" || status === "failed" || status === "ready_to_ship" || status === "shipped" || status === "completed";
}
function isProtectedFinalStatus(status) {
  return 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 firstBoolean(...values) {
  for (const value of values) {
    if (typeof value === "boolean") return value;
  }
  return 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;
  if (typeof metadata.ship_held === "boolean") state.ship_held = metadata.ship_held;
  if (typeof metadata.shipping_disabled === "boolean") state.shipping_disabled = metadata.shipping_disabled;
  if (typeof metadata.ship_authorized === "boolean") state.ship_authorized = metadata.ship_authorized;
  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 publicStateForRunState(input) {
  const state = input.state;
  const status = input.status || state.status;
  const raw = recordValue(input.raw) || {};
  const extendedState = state;
  const terminalOk = isTerminalStatus(status) ? state.ok : void 0;
  return summarizeRiddleProofPublicState(compactRecord({
    status,
    ok: terminalOk,
    request: state.request,
    pr_state: state.pr_state,
    marked_ready: state.marked_ready,
    ship_held: state.ship_held,
    shipping_disabled: state.shipping_disabled,
    ship_authorized: state.ship_authorized,
    ship_mode: state.request?.ship_mode,
    merge_commit: state.merge_commit,
    merged_at: state.merged_at,
    checkpoint_summary: state.checkpoint_summary,
    pr_handoff_policy: recordValue(extendedState.pr_handoff_policy),
    merge_ready: extendedState.merge_ready,
    normal_pr_allowed: extendedState.normal_pr_allowed,
    raw: Object.keys(raw).length ? raw : void 0
  }));
}
function shipControlStateFor(input) {
  const state = input.state;
  const status = input.status || state.status;
  const raw = recordValue(input.raw) || {};
  const shipReport = recordValue(state.ship_report) || {};
  const prState = recordValue(state.pr_state) || {};
  const shippingDisabled = firstBoolean(
    raw.shipping_disabled,
    raw.shippingDisabled,
    state.shipping_disabled,
    shipReport.shipping_disabled,
    shipReport.shippingDisabled
  ) ?? state.request?.ship_mode === "none";
  const explicitAuthorized = firstBoolean(
    raw.ship_authorized,
    raw.shipAuthorized,
    state.ship_authorized,
    shipReport.ship_authorized,
    shipReport.shipAuthorized
  );
  const authorizationEvidence = Boolean(
    status === "shipped" || state.marked_ready === true || shipReport.marked_ready === true || prState.status === "merged" || state.merge_commit || state.merged_at
  );
  const inferredAuthorized = explicitAuthorized ?? authorizationEvidence;
  const rawHeld = firstBoolean(raw.ship_held, raw.shipHeld);
  const inferredHeld = status === "ready_to_ship" && shippingDisabled && !inferredAuthorized;
  const shipHeld = rawHeld ?? (state.ship_held === true || inferredHeld);
  return {
    ship_held: shipHeld,
    shipping_disabled: shippingDisabled,
    ship_authorized: shipHeld ? false : inferredAuthorized
  };
}
function applyShipControlState(state, input = {}) {
  const control = shipControlStateFor({ state, status: input.status, raw: input.raw });
  state.ship_held = control.ship_held;
  state.shipping_disabled = control.shipping_disabled;
  state.ship_authorized = control.ship_authorized;
  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;
  if (isProtectedFinalStatus(status)) state.finalized = true;
  applyShipControlState(state, { status, raw: input.raw });
  const publicState = publicStateForRunState({ state, status, raw: input.raw });
  const publicMergeRecommendation = riddleProofPublicStateMergeRecommendation(
    publicState,
    state.merge_recommendation
  );
  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,
    result_label: publicState.result_label,
    ship_held: publicState.ship_held,
    shipping_disabled: publicState.shipping_disabled,
    ship_authorized: publicState.ship_authorized,
    merge_ready: publicState.merge_ready,
    sync_allowed: publicState.sync_allowed,
    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: publicMergeRecommendation,
    public_state: publicState,
    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/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 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 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: elapsedMs(state.created_at, at),
      stage_elapsed_ms: elapsedMs(state.stage_started_at, at),
      wait_reason: input.wait_reason,
      blocker: input.blocker,
      ...input.details
    })
  });
}
function setRunStatus(state, status, at = timestamp()) {
  state.status = status;
  state.ok = status !== "blocked" && status !== "failed";
  if (isProtectedFinalStatus(status)) state.finalized = true;
  state.updated_at = at;
  return state;
}

// src/proof-run-core.ts
var import_node_fs = require("fs");
var import_node_crypto = require("crypto");
var import_node_path = __toESM(require("path"), 1);
var import_node_url = require("url");
var import_meta = {};
function normalizedMode(value) {
  return typeof value === "string" ? value.trim().toLowerCase() : "";
}
function noImplementationModeInput(value) {
  return value && typeof value === "object" ? value : {};
}
function noImplementationModeFor(params, state) {
  const input = noImplementationModeInput(params);
  const stateInput = noImplementationModeInput(state);
  const mode = normalizedMode(input.mode ?? input.workflow_mode ?? stateInput.mode ?? stateInput.workflow_mode);
  const implementationMode = normalizedMode(input.implementation_mode ?? stateInput.implementation_mode);
  const requireDiff = input.require_diff ?? stateInput.require_diff;
  const allowCodeChanges = input.allow_code_changes ?? stateInput.allow_code_changes;
  return mode === "audit" || mode === "profile" || implementationMode === "none" || requireDiff === false || allowCodeChanges === false;
}
function currentDistDir() {
  const meta = typeof import_meta === "object" ? import_meta : {};
  if (typeof meta.url === "string" && meta.url) {
    return import_node_path.default.dirname((0, import_node_url.fileURLToPath)(meta.url));
  }
  if (typeof __dirname === "string") return __dirname;
  return process.cwd();
}
var BUNDLED_RIDDLE_PROOF_DIR = import_node_path.default.resolve(
  currentDistDir(),
  "..",
  "runtime"
);

// src/runner.ts
function errorDetails(error) {
  if (error instanceof Error) {
    return {
      name: error.name,
      message: error.message
    };
  }
  return { message: String(error) };
}
function adapterBlocker(code, message, checkpoint, details) {
  return {
    code,
    message,
    checkpoint,
    details
  };
}
function blockRun(input) {
  input.state.blocker = input.blocker;
  appendRunEvent(input.state, {
    kind: "run.blocked",
    checkpoint: input.blocker.checkpoint,
    stage: input.stage,
    summary: input.blocker.message,
    details: {
      code: input.blocker.code,
      ...input.blocker.details
    }
  });
  setRunStatus(input.state, "blocked");
  return createRunResult({
    state: input.state,
    status: "blocked",
    last_summary: input.blocker.message,
    evidence_bundle: input.evidence_bundle,
    raw: input.raw
  });
}
function shouldIterate(assessment) {
  const nextStage = assessment.continue_with_stage || assessment.recommended_stage;
  return nextStage === "implement" || nextStage === "author";
}
function hasTrustedReadySource(assessment) {
  return assessment.source === "supervising_agent" || assessment.source === "supervisor";
}
async function notifyIfConfigured(input) {
  if (!input.notification) return input.result;
  try {
    const notification = await input.notification.notify({
      state: input.state,
      result: input.result
    });
    input.state.notification = notification;
    appendRunEvent(input.state, {
      kind: "notification.completed",
      checkpoint: "notification_completed",
      stage: "notify",
      summary: "Integration notification completed."
    });
  } catch (error) {
    appendRunEvent(input.state, {
      kind: "notification.failed",
      checkpoint: "notification_failed",
      stage: "notify",
      summary: "Integration notification failed.",
      details: errorDetails(error)
    });
  }
  return createRunResult({
    state: input.state,
    status: input.state.status,
    last_summary: input.result.last_summary,
    evidence_bundle: input.result.evidence_bundle,
    raw: input.result.raw
  });
}
async function runRiddleProof(input) {
  const state = input.state || createRunState({
    request: input.request,
    state_path: input.state_path,
    worktree_path: input.workdir
  });
  const adapters = input.adapters || {};
  const maxIterations = Math.max(1, Math.trunc(input.max_iterations ?? 1));
  appendRunEvent(state, {
    kind: "run.started",
    checkpoint: "run_started",
    stage: "setup",
    summary: "Riddle Proof run started.",
    details: {
      run_id: state.run_id,
      state_path: state.state_path,
      worktree_path: state.worktree_path,
      branch: state.branch,
      max_iterations: maxIterations,
      ship_mode: state.request.ship_mode || "none"
    }
  });
  appendStageHeartbeat(state, {
    stage: "setup",
    summary: "Setup stage is active.",
    details: {
      run_id: state.run_id,
      state_path: state.state_path,
      worktree_path: state.worktree_path,
      branch: state.branch
    }
  });
  let workdir = input.workdir;
  let evidenceContext;
  if (adapters.preflight) {
    appendRunEvent(state, {
      kind: "preflight.started",
      checkpoint: "preflight_started",
      stage: "preflight",
      summary: "Riddle Proof preflight adapter started."
    });
    try {
      const preflight = await adapters.preflight.preflight({ request: state.request, state });
      if (!preflight.ok) {
        return blockRun({
          state,
          stage: "preflight",
          blocker: adapterBlocker(
            "preflight_failed",
            "The preflight adapter found blocking tool or model configuration issues.",
            "preflight_failed",
            {
              blockers: preflight.blockers,
              warnings: preflight.warnings,
              degraded_capabilities: preflight.degraded_capabilities
            }
          ),
          raw: { preflight }
        });
      }
      appendRunEvent(state, {
        kind: "preflight.completed",
        checkpoint: "preflight_completed",
        stage: "preflight",
        summary: "Riddle Proof preflight adapter completed.",
        details: {
          warnings: preflight.warnings,
          degraded_capabilities: preflight.degraded_capabilities
        }
      });
    } catch (error) {
      return blockRun({
        state,
        stage: "preflight",
        blocker: adapterBlocker("preflight_exception", "The preflight adapter threw an exception.", "preflight_failed", errorDetails(error))
      });
    }
  }
  if (adapters.setup) {
    appendRunEvent(state, {
      kind: "setup.started",
      checkpoint: "setup_started",
      stage: "setup",
      summary: "Riddle Proof setup adapter started."
    });
    try {
      const setup = await adapters.setup.setup({ request: state.request, state });
      if (!setup.ok) {
        return blockRun({
          state,
          stage: "setup",
          blocker: adapterBlocker(
            "setup_failed",
            "The setup adapter did not complete successfully.",
            "setup_failed",
            { blockers: setup.blockers }
          ),
          raw: { setup }
        });
      }
      workdir = setup.worktree_path || setup.workdir || workdir;
      state.worktree_path = setup.worktree_path || setup.workdir || state.worktree_path;
      state.branch = setup.branch || state.branch;
      evidenceContext = setup.evidence_context;
      appendRunEvent(state, {
        kind: "setup.completed",
        checkpoint: "setup_completed",
        stage: "setup",
        summary: "Riddle Proof setup adapter completed.",
        details: {
          has_workdir: Boolean(workdir),
          worktree_path: state.worktree_path,
          branch: state.branch,
          cleanup_policy: setup.cleanup_policy,
          has_evidence_context: Boolean(evidenceContext)
        }
      });
    } catch (error) {
      return blockRun({
        state,
        stage: "setup",
        blocker: adapterBlocker("setup_exception", "The setup adapter threw an exception.", "setup_failed", errorDetails(error))
      });
    }
  }
  const changeRequest = state.request.change_request?.trim();
  const noImplementationMode = noImplementationModeFor(state.request);
  if (!changeRequest) {
    return blockRun({
      state,
      stage: "setup",
      blocker: adapterBlocker("change_request_required", "A change request is required before implementation.", "request_invalid")
    });
  }
  if (!noImplementationMode && !workdir) {
    return blockRun({
      state,
      stage: "setup",
      blocker: adapterBlocker("workdir_not_configured", "A workdir or setup adapter result is required before implementation.", "setup_required")
    });
  }
  if (!noImplementationMode && !adapters.implementation) {
    return blockRun({
      state,
      stage: "implement",
      blocker: adapterBlocker("implementation_adapter_not_configured", "An implementation adapter is required to change code.", "implementation_required")
    });
  }
  if (!adapters.proof) {
    return blockRun({
      state,
      stage: "prove",
      blocker: adapterBlocker("proof_adapter_not_configured", "A proof adapter is required to capture evidence.", "proof_required")
    });
  }
  if (!adapters.judge) {
    return blockRun({
      state,
      stage: "verify",
      blocker: adapterBlocker("judge_adapter_not_configured", "A judge adapter is required to assess proof.", "judge_required")
    });
  }
  let implementation;
  let evidenceBundle;
  let assessment;
  for (let attempt = 0; attempt < maxIterations; attempt += 1) {
    state.iterations += 1;
    if (noImplementationMode) {
      state.implementation_status = "not_required";
      appendRunEvent(state, {
        kind: "implementation.skipped",
        checkpoint: "implementation_not_required",
        stage: "implement",
        summary: "Implementation stage skipped because audit/no-diff mode disables code changes.",
        details: { iteration: state.iterations }
      });
    } else {
      appendStageHeartbeat(state, {
        stage: "implement",
        summary: "Implementation stage is active.",
        details: { iteration: state.iterations }
      });
      appendRunEvent(state, {
        kind: "implementation.started",
        checkpoint: "implementation_started",
        stage: "implement",
        summary: "Implementation adapter started.",
        details: { iteration: state.iterations }
      });
      try {
        implementation = await adapters.implementation.implement({
          workdir,
          change_request: changeRequest,
          evidence_context: evidenceContext,
          state
        });
      } catch (error) {
        return blockRun({
          state,
          stage: "implement",
          blocker: adapterBlocker("implementation_exception", "The implementation adapter threw an exception.", "implementation_failed", errorDetails(error)),
          evidence_bundle: evidenceBundle
        });
      }
      if (!implementation.ok) {
        return blockRun({
          state,
          stage: "implement",
          blocker: adapterBlocker(
            "implementation_failed",
            "The implementation adapter did not complete successfully.",
            "implementation_failed",
            { blockers: implementation.blockers }
          ),
          evidence_bundle: evidenceBundle,
          raw: { implementation }
        });
      }
      appendRunEvent(state, {
        kind: "implementation.completed",
        checkpoint: "implementation_completed",
        stage: "implement",
        summary: "Implementation adapter completed.",
        details: {
          changed_files: implementation.changed_files,
          tests_run: implementation.tests_run
        }
      });
    }
    appendStageHeartbeat(state, {
      stage: "prove",
      summary: "Proof capture stage is active.",
      details: {
        verification_mode: state.request.verification_mode
      }
    });
    appendRunEvent(state, {
      kind: "proof.started",
      checkpoint: "proof_started",
      stage: "prove",
      summary: "Proof adapter started."
    });
    try {
      const proof = await adapters.proof.prove({
        state,
        implementation,
        evidence_context: evidenceContext
      });
      if (!proof.ok || !proof.evidence_bundle) {
        return blockRun({
          state,
          stage: "prove",
          blocker: adapterBlocker(
            "proof_failed",
            "The proof adapter did not produce a usable evidence bundle.",
            "proof_failed",
            { blockers: proof.blockers }
          ),
          raw: { proof }
        });
      }
      evidenceBundle = proof.evidence_bundle;
      appendRunEvent(state, {
        kind: "proof.completed",
        checkpoint: "proof_completed",
        stage: "prove",
        summary: "Proof adapter completed.",
        details: {
          verification_mode: evidenceBundle.verification_mode,
          artifact_count: evidenceBundle.artifacts?.length ?? 0
        }
      });
    } catch (error) {
      return blockRun({
        state,
        stage: "prove",
        blocker: adapterBlocker("proof_exception", "The proof adapter threw an exception.", "proof_failed", errorDetails(error))
      });
    }
    appendRunEvent(state, {
      kind: "judge.started",
      checkpoint: "judge_started",
      stage: "verify",
      summary: "Judge adapter started."
    });
    appendStageHeartbeat(state, {
      stage: "verify",
      summary: "Verification stage is active.",
      details: {
        verification_mode: evidenceBundle.verification_mode
      }
    });
    try {
      assessment = await adapters.judge.assessProof({ state, evidence_bundle: evidenceBundle });
      state.proof_decision = assessment.decision;
      appendRunEvent(state, {
        kind: "judge.completed",
        checkpoint: "judge_completed",
        stage: "verify",
        summary: assessment.summary,
        details: {
          decision: assessment.decision,
          recommended_stage: assessment.recommended_stage,
          continue_with_stage: assessment.continue_with_stage,
          source: assessment.source,
          reasons: assessment.reasons
        }
      });
    } catch (error) {
      return blockRun({
        state,
        stage: "verify",
        blocker: adapterBlocker("judge_exception", "The judge adapter threw an exception.", "judge_failed", errorDetails(error)),
        evidence_bundle: evidenceBundle
      });
    }
    if (assessment.decision === "ready_to_ship") {
      if (!hasTrustedReadySource(assessment)) {
        return blockRun({
          state,
          stage: "verify",
          blocker: adapterBlocker(
            "proof_assessment_untrusted_source",
            "A ready_to_ship proof assessment must come from a supervising source.",
            "judge_completed",
            {
              decision: assessment.decision,
              source: assessment.source || null,
              trusted_sources: ["supervising_agent", "supervisor"]
            }
          ),
          evidence_bundle: evidenceBundle,
          raw: { assessment }
        });
      }
      break;
    }
    if (attempt + 1 < maxIterations && shouldIterate(assessment)) {
      evidenceContext = evidenceBundle;
      appendRunEvent(state, {
        kind: "run.iterating",
        checkpoint: "iteration_requested",
        stage: "implement",
        summary: "Judge requested another implementation iteration.",
        details: {
          decision: assessment.decision,
          next_iteration: state.iterations + 1
        }
      });
      continue;
    }
    return blockRun({
      state,
      stage: "verify",
      blocker: adapterBlocker(
        "proof_not_ready",
        assessment.summary || "Proof is not ready to ship.",
        "judge_completed",
        {
          decision: assessment.decision,
          recommended_stage: assessment.recommended_stage,
          continue_with_stage: assessment.continue_with_stage,
          reasons: assessment.reasons
        }
      ),
      evidence_bundle: evidenceBundle,
      raw: { assessment }
    });
  }
  if (!assessment || !evidenceBundle) {
    return blockRun({
      state,
      stage: "verify",
      blocker: adapterBlocker("runner_incomplete", "The runner ended without proof assessment.", "runner_incomplete")
    });
  }
  if (state.request.ship_mode !== "ship") {
    setRunStatus(state, "ready_to_ship");
    const result2 = createRunResult({
      state,
      status: "ready_to_ship",
      last_summary: assessment.summary,
      evidence_bundle: evidenceBundle,
      raw: { implementation, assessment, ship_held: true, shipping_disabled: true, ship_authorized: false }
    });
    return notifyIfConfigured({ state, result: result2, notification: adapters.notification });
  }
  if (!adapters.ship) {
    return blockRun({
      state,
      stage: "ship",
      blocker: adapterBlocker("ship_adapter_not_configured", "A ship adapter is required when ship_mode is ship.", "ship_required"),
      evidence_bundle: evidenceBundle,
      raw: { implementation, assessment }
    });
  }
  appendRunEvent(state, {
    kind: "ship.started",
    checkpoint: "ship_started",
    stage: "ship",
    summary: "Ship adapter started."
  });
  appendStageHeartbeat(state, {
    stage: "ship",
    summary: "Ship stage is active."
  });
  let metadata;
  try {
    metadata = await adapters.ship.ship({ state, assessment });
  } catch (error) {
    return blockRun({
      state,
      stage: "ship",
      blocker: adapterBlocker("ship_exception", "The ship adapter threw an exception.", "ship_failed", errorDetails(error)),
      evidence_bundle: evidenceBundle,
      raw: { implementation, assessment }
    });
  }
  appendRunEvent(state, {
    kind: "ship.completed",
    checkpoint: "ship_completed",
    stage: "ship",
    summary: "Ship adapter completed.",
    details: {
      pr_url: metadata.pr_url,
      marked_ready: metadata.marked_ready,
      finalized: metadata.finalized
    }
  });
  setRunStatus(state, "shipped");
  const result = createRunResult({
    state,
    status: "shipped",
    last_summary: "Riddle Proof shipped.",
    metadata,
    evidence_bundle: evidenceBundle,
    raw: { implementation, assessment }
  });
  return notifyIfConfigured({ state, result, notification: adapters.notification });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  runRiddleProof
});
