"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/codex-exec-agent.ts
var codex_exec_agent_exports = {};
__export(codex_exec_agent_exports, {
  createCodexExecAgentAdapter: () => createCodexExecAgentAdapter,
  createCodexExecJsonRunner: () => createCodexExecJsonRunner,
  runCodexExecAgentDoctor: () => runCodexExecAgentDoctor
});
module.exports = __toCommonJS(codex_exec_agent_exports);
var import_node_child_process = require("child_process");
var import_node_fs = require("fs");
var import_node_os = __toESM(require("os"), 1);
var import_node_path = __toESM(require("path"), 1);

// src/result.ts
function compactRecord(input) {
  return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0 && value !== null && value !== ""));
}

// src/codex-exec-agent.ts
var DEFAULT_CODEX_TIMEOUT_MS = 6e5;
var DEFAULT_PROOF_PACKET_AUTHOR_TIMEOUT_MS = 18e4;
var REFINED_INPUTS_SCHEMA = {
  type: "object",
  additionalProperties: false,
  required: ["server_path", "wait_for_selector", "reference"],
  properties: {
    server_path: { type: ["string", "null"] },
    wait_for_selector: { type: ["string", "null"] },
    reference: { enum: ["before", "prod", "both", null] }
  }
};
var BASELINE_UNDERSTANDING_SCHEMA = {
  type: "object",
  additionalProperties: false,
  required: [
    "reference",
    "target_route",
    "before_evidence_url",
    "visible_before_state",
    "relevant_elements",
    "requested_change",
    "proof_focus",
    "stop_condition",
    "quality_risks"
  ],
  properties: {
    reference: { type: "string", enum: ["before", "prod", "both", "unknown"] },
    target_route: { type: "string" },
    before_evidence_url: { type: "string" },
    visible_before_state: { type: "string" },
    relevant_elements: { type: "array", items: { type: "string" } },
    requested_change: { type: "string" },
    proof_focus: { type: "string" },
    stop_condition: { type: "string" },
    quality_risks: { type: "array", items: { type: "string" } }
  }
};
var RECON_SCHEMA = {
  type: "object",
  additionalProperties: false,
  required: [
    "decision",
    "summary",
    "baseline_understanding",
    "continue_with_stage",
    "escalation_target",
    "refined_inputs",
    "reasons",
    "source"
  ],
  properties: {
    decision: { type: "string", enum: ["retry_recon", "ready_for_author", "recon_stuck"] },
    summary: { type: "string" },
    baseline_understanding: BASELINE_UNDERSTANDING_SCHEMA,
    continue_with_stage: { type: "string", enum: ["recon", "author"] },
    escalation_target: { type: "string", enum: ["agent", "human"] },
    refined_inputs: REFINED_INPUTS_SCHEMA,
    reasons: { type: "array", items: { type: "string" } },
    source: { type: "string", enum: ["supervising_agent"] }
  }
};
var AUTHOR_SCHEMA = {
  type: "object",
  additionalProperties: false,
  required: [
    "proof_plan",
    "capture_script",
    "baseline_understanding_used",
    "refined_inputs",
    "rationale",
    "confidence",
    "summary"
  ],
  properties: {
    proof_plan: { type: "string" },
    capture_script: { type: "string" },
    baseline_understanding_used: BASELINE_UNDERSTANDING_SCHEMA,
    refined_inputs: REFINED_INPUTS_SCHEMA,
    rationale: { type: "array", items: { type: "string" } },
    confidence: { type: "string", enum: ["low", "medium", "high"] },
    summary: { type: "string" }
  }
};
var IMPLEMENT_SCHEMA = {
  type: "object",
  additionalProperties: false,
  required: ["summary", "implementation_notes", "changed_files", "tests_run", "blockers"],
  properties: {
    summary: { type: "string" },
    implementation_notes: { type: "string" },
    changed_files: { type: "array", items: { type: "string" } },
    tests_run: { type: "array", items: { type: "string" } },
    blockers: { type: "array", items: { type: "string" } }
  }
};
var PROOF_SCHEMA = {
  type: "object",
  additionalProperties: false,
  required: [
    "decision",
    "summary",
    "recommended_stage",
    "continue_with_stage",
    "escalation_target",
    "reasons",
    "source"
  ],
  properties: {
    decision: {
      type: "string",
      enum: [
        "ready_to_ship",
        "needs_richer_proof",
        "revise_capture",
        "needs_recon",
        "needs_implementation"
      ]
    },
    summary: { type: "string" },
    recommended_stage: { type: "string", enum: ["ship", "author", "implement", "recon", "verify"] },
    continue_with_stage: { type: "string", enum: ["ship", "author", "implement", "recon", "verify"] },
    escalation_target: { type: "string", enum: ["agent", "human"] },
    reasons: { type: "array", items: { type: "string" } },
    source: { type: "string", enum: ["supervising_agent"] }
  }
};
var PROMPT_STRING_LIMIT = 1e3;
var PROMPT_ARRAY_LIMIT = 8;
var PROMPT_OBJECT_KEY_LIMIT = 50;
var PROMPT_BLOCK_LIMIT = 16e3;
var PROMPT_TOTAL_LIMIT = 58e3;
var PROMPT_KEY_PRIORITY = [
  "ok",
  "status",
  "stage",
  "checkpoint",
  "summary",
  "state_path",
  "repo",
  "branch",
  "change_request",
  "context",
  "success_criteria",
  "verification_mode",
  "reference",
  "server_path",
  "wait_for_selector",
  "before_cdn",
  "prod_cdn",
  "after_cdn",
  "before_baseline",
  "prod_baseline",
  "route_hints",
  "route_candidates",
  "keyword_hits",
  "observations",
  "latest_attempt",
  "attempt_history",
  "current_plan",
  "plan_history",
  "decision_history",
  "refined_inputs",
  "recon_assessment",
  "baseline_understanding",
  "supervisor_author_packet",
  "proof_plan",
  "capture_script",
  "implementation_status",
  "implementation_summary",
  "implementation_notes",
  "changed_files",
  "verify_status",
  "verify_summary",
  "proof_assessment",
  "proof_assessment_request",
  "semantic_context",
  "visual_delta",
  "proof_evidence_present",
  "proof_evidence_sample",
  "artifacts",
  "assertions",
  "checkpointContract",
  "shipGate",
  "last_error",
  "errors",
  "runtime_events",
  "events"
];
var PROMPT_PRIORITY_INDEX = new Map(PROMPT_KEY_PRIORITY.map((key, index) => [key, index]));
function truncatePromptString(value, limit = PROMPT_STRING_LIMIT) {
  if (value.length <= limit) return value;
  return `${value.slice(0, limit)}
...[truncated ${value.length - limit} chars]`;
}
function compactPromptValue(value, depth = 0, key = "") {
  if (value === null || typeof value === "boolean" || typeof value === "number") return value;
  if (typeof value === "string") {
    const lowerKey = key.toLowerCase();
    const looksLikeUrl = /^https?:\/\//.test(value);
    if (!looksLikeUrl && (lowerKey.includes("base64") || lowerKey.includes("data_url") || lowerKey.includes("screenshot_blob"))) {
      return `[omitted ${value.length} chars from ${key || "large artifact"}]`;
    }
    const limit = looksLikeUrl ? 1e3 : depth <= 1 ? PROMPT_STRING_LIMIT : 900;
    return truncatePromptString(value, limit);
  }
  if (Array.isArray(value)) {
    const lowerKey = key.toLowerCase();
    const items = lowerKey.includes("event") || lowerKey.includes("histor") || lowerKey.includes("retry") ? value.slice(-PROMPT_ARRAY_LIMIT) : value.slice(0, PROMPT_ARRAY_LIMIT);
    const compacted = items.map((item) => compactPromptValue(item, depth + 1, key));
    if (value.length > items.length) {
      const omitted = value.length - items.length;
      return lowerKey.includes("event") || lowerKey.includes("histor") || lowerKey.includes("retry") ? [{ omittedEarlierItems: omitted }, ...compacted] : [...compacted, { omittedItems: omitted }];
    }
    return compacted;
  }
  if (!value || typeof value !== "object") return String(value);
  const entries = Object.entries(value).sort(([left], [right]) => {
    const leftPriority = PROMPT_PRIORITY_INDEX.get(left) ?? 1e3;
    const rightPriority = PROMPT_PRIORITY_INDEX.get(right) ?? 1e3;
    if (leftPriority !== rightPriority) return leftPriority - rightPriority;
    return left.localeCompare(right);
  });
  const result = {};
  for (const [entryKey, entryValue] of entries.slice(0, PROMPT_OBJECT_KEY_LIMIT)) {
    result[entryKey] = compactPromptValue(entryValue, depth + 1, entryKey);
  }
  if (entries.length > PROMPT_OBJECT_KEY_LIMIT) {
    result.__omitted_keys = entries.length - PROMPT_OBJECT_KEY_LIMIT;
  }
  return result;
}
function jsonBlock(label, value) {
  let json = JSON.stringify(compactPromptValue(value), null, 2);
  if (json.length > PROMPT_BLOCK_LIMIT) {
    json = `${json.slice(0, PROMPT_BLOCK_LIMIT)}
...[truncated ${json.length - PROMPT_BLOCK_LIMIT} chars from compacted ${label}]`;
  }
  return `${label}:
${json}`;
}
function resolveWorkdir(context, fallback = "/tmp") {
  const after = typeof context.fullRiddleState?.after_worktree === "string" ? context.fullRiddleState.after_worktree.trim() : "";
  return after || fallback;
}
function basePrompt(context, role) {
  const prompt = [
    role,
    "",
    "You are the supervising Codex worker inside the Riddle Proof harness.",
    "Return only JSON matching the provided output schema.",
    "Do not ask the human to manually continue. If blocked, encode the blocker in the JSON fields allowed by the schema.",
    "Large raw artifacts are summarized before this prompt. Use preserved state summaries, URLs, file paths, and proof evidence samples instead of expecting full raw logs or binary artifacts inline.",
    "",
    jsonBlock("Original request", context.request),
    jsonBlock("Riddle checkpoint result", context.engineResult),
    jsonBlock("Full riddle state", context.fullRiddleState || {})
  ].join("\n");
  if (prompt.length <= PROMPT_TOTAL_LIMIT) return prompt;
  return `${prompt.slice(0, PROMPT_TOTAL_LIMIT).trimEnd()}
...[truncated ${prompt.length - PROMPT_TOTAL_LIMIT} chars from total prompt]`;
}
function schemaRequiredKeys(schema) {
  const required = schema?.required;
  return Array.isArray(required) ? required.filter((key) => typeof key === "string" && key.length > 0) : [];
}
function isSchemaShapedObject(value, schema) {
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
  const required = schemaRequiredKeys(schema);
  return required.every((key) => Object.prototype.hasOwnProperty.call(value, key));
}
function parseJsonCandidate(raw, schema) {
  try {
    const parsed = JSON.parse(raw);
    return isSchemaShapedObject(parsed, schema) ? parsed : null;
  } catch {
    return null;
  }
}
function extractJsonObjectCandidates(raw) {
  const candidates = [];
  let depth = 0;
  let start = -1;
  let inString = false;
  let escaped = false;
  for (let index = 0; index < raw.length; index += 1) {
    const char = raw[index];
    if (inString) {
      if (escaped) {
        escaped = false;
      } else if (char === "\\") {
        escaped = true;
      } else if (char === '"') {
        inString = false;
      }
      continue;
    }
    if (char === '"') {
      inString = true;
      continue;
    }
    if (char === "{") {
      if (depth === 0) start = index;
      depth += 1;
      continue;
    }
    if (char === "}" && depth > 0) {
      depth -= 1;
      if (depth === 0 && start >= 0) {
        candidates.push(raw.slice(start, index + 1));
        start = -1;
      }
    }
  }
  return candidates;
}
function parseJsonObject(raw, schema) {
  const trimmed = raw.trim();
  if (!trimmed) return null;
  const whole = parseJsonCandidate(trimmed, schema);
  if (whole) return whole;
  const lines = trimmed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
  for (let index = lines.length - 1; index >= 0; index -= 1) {
    const parsed = parseJsonCandidate(lines[index], schema);
    if (parsed) return parsed;
  }
  const candidates = extractJsonObjectCandidates(trimmed);
  for (let index = candidates.length - 1; index >= 0; index -= 1) {
    const parsed = parseJsonCandidate(candidates[index], schema);
    if (parsed) return parsed;
  }
  return null;
}
function parseJsonFromRunnerOutputs(outputs, schema) {
  const seen = /* @__PURE__ */ new Set();
  for (const output of outputs) {
    if (!output.text.trim() || seen.has(output.text)) continue;
    seen.add(output.text);
    const parsed = parseJsonObject(output.text, schema);
    if (parsed) return { parsed, source: output.source };
  }
  const combined = outputs.map((output) => output.text).filter((text) => text.trim()).join("\n");
  if (!combined.trim() || seen.has(combined)) return { parsed: null, source: "" };
  return { parsed: parseJsonObject(combined, schema), source: "combined_output" };
}
function resolveCodexTimeoutMs(config, request) {
  if (typeof config.codexTimeoutMs === "number" && Number.isFinite(config.codexTimeoutMs) && config.codexTimeoutMs > 0) {
    return Number(config.codexTimeoutMs);
  }
  return request.purpose === "proof packet authoring" ? DEFAULT_PROOF_PACKET_AUTHOR_TIMEOUT_MS : DEFAULT_CODEX_TIMEOUT_MS;
}
function isCodexLifecycleEvent(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
  const type = value.type;
  return typeof type === "string" && (type.startsWith("thread.") || type.startsWith("turn.") || type.startsWith("exec.") || type.startsWith("agent.") || type.startsWith("token.") || type.startsWith("reasoning.") || type.startsWith("error."));
}
function analyzeCodexRunnerOutput(outputs) {
  const eventTypes = /* @__PURE__ */ new Set();
  let eventLineCount = 0;
  let nonEventLineCount = 0;
  const nonEventSamples = [];
  for (const output of outputs) {
    const lines = output.text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
    for (const line of lines) {
      try {
        const parsed = JSON.parse(line);
        if (isCodexLifecycleEvent(parsed)) {
          eventLineCount += 1;
          eventTypes.add(parsed.type);
          continue;
        }
      } catch {
      }
      nonEventLineCount += 1;
      if (nonEventSamples.length < 3) nonEventSamples.push(line.slice(0, 240));
    }
  }
  return {
    eventLineCount,
    eventTypes: Array.from(eventTypes),
    nonEventLineCount,
    nonEventSamples,
    onlyLifecycleEvents: eventLineCount > 0 && nonEventLineCount === 0
  };
}
function isHarnessVerificationOnlyBlocker(blocker) {
  const text = blocker.toLowerCase();
  return (text.includes("erofs") || text.includes("read-only file system")) && text.includes("node_modules") && (text.includes(".vite-temp") || text.includes("vite.config"));
}
function runnerMetrics(input) {
  const schemaText = JSON.stringify(input.request.schema);
  const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
  return compactRecord({
    purpose: input.request.purpose,
    workdir: input.request.workdir,
    started_at: input.startedAt,
    finished_at: finishedAt,
    duration_ms: Date.now() - input.startedMs,
    prompt_chars: input.request.prompt.length,
    prompt_lines: input.request.prompt.split(/\r?\n/).length,
    schema_chars: schemaText.length,
    stdout_chars: (input.stdout || "").length,
    stderr_chars: (input.stderr || "").length,
    final_message_chars: (input.finalText || "").length,
    parsed_json_source: input.parsedJsonSource,
    exit_status: input.status ?? null,
    timed_out: input.timedOut || false,
    error_code: input.errorCode,
    codex_event_types: input.codexEventTypes && input.codexEventTypes.length ? input.codexEventTypes : void 0,
    codex_event_line_count: input.codexEventLineCount,
    codex_non_event_line_count: input.codexNonEventLineCount,
    codex_command: input.config.codexCommand || "codex",
    codex_model: input.config.codexModel,
    codex_sandbox: input.config.codexSandbox || "workspace-write",
    codex_full_auto: input.config.codexFullAuto !== false,
    timeout_ms: input.timeoutMs ?? DEFAULT_CODEX_TIMEOUT_MS
  });
}
function createCodexExecJsonRunner(config = {}) {
  return (request) => {
    const startedAt = (/* @__PURE__ */ new Date()).toISOString();
    const startedMs = Date.now();
    const timeoutMs = resolveCodexTimeoutMs(config, request);
    if (!request.workdir || !(0, import_node_fs.existsSync)(request.workdir)) {
      return {
        ok: false,
        metrics: runnerMetrics({ request, config, startedAt, startedMs, timeoutMs, errorCode: "workdir_missing" }),
        blocker: {
          code: "codex_workdir_missing",
          message: `Codex workdir does not exist for ${request.purpose}.`,
          details: { workdir: request.workdir }
        }
      };
    }
    const tmpDir = (0, import_node_fs.mkdtempSync)(import_node_path.default.join(import_node_os.default.tmpdir(), "riddle-proof-codex-"));
    const schemaPath = import_node_path.default.join(tmpDir, "schema.json");
    const lastMessagePath = import_node_path.default.join(tmpDir, "last-message.json");
    (0, import_node_fs.writeFileSync)(schemaPath, JSON.stringify(request.schema, null, 2));
    const args = [
      "exec",
      "--json",
      "--output-schema",
      schemaPath,
      "--output-last-message",
      lastMessagePath,
      "--cd",
      request.workdir,
      "--sandbox",
      config.codexSandbox || "workspace-write",
      "--skip-git-repo-check"
    ];
    if (config.codexFullAuto !== false) args.push("--full-auto");
    if (config.codexModel) args.push("-m", config.codexModel);
    args.push("-");
    const env = { ...process.env };
    if (config.codexHome) env.CODEX_HOME = config.codexHome;
    delete env.OPENAI_API_KEY;
    try {
      const proc = (0, import_node_child_process.spawnSync)(config.codexCommand || "codex", args, {
        input: request.prompt,
        encoding: "utf-8",
        timeout: timeoutMs,
        maxBuffer: 10 * 1024 * 1024,
        env
      });
      if (proc.error) {
        const timedOut = proc.error.code === "ETIMEDOUT";
        return {
          ok: false,
          stdout: proc.stdout || "",
          stderr: proc.stderr || "",
          metrics: runnerMetrics({
            request,
            config,
            startedAt,
            startedMs,
            stdout: proc.stdout || "",
            stderr: proc.stderr || "",
            status: proc.status,
            timedOut,
            timeoutMs,
            errorCode: proc.error.code || "spawn_error"
          }),
          blocker: {
            code: timedOut ? "codex_timeout" : "codex_exec_error",
            message: timedOut ? `Codex timed out during ${request.purpose}.` : `Codex failed to start or complete ${request.purpose}.`,
            details: { error: proc.error.message }
          }
        };
      }
      if (proc.status !== 0) {
        return {
          ok: false,
          stdout: proc.stdout || "",
          stderr: proc.stderr || "",
          metrics: runnerMetrics({
            request,
            config,
            startedAt,
            startedMs,
            stdout: proc.stdout || "",
            stderr: proc.stderr || "",
            status: proc.status,
            timeoutMs,
            errorCode: "nonzero_exit"
          }),
          blocker: {
            code: "codex_nonzero_exit",
            message: `Codex exited with status ${proc.status} during ${request.purpose}.`,
            details: { stdout: proc.stdout || "", stderr: proc.stderr || "" }
          }
        };
      }
      const finalText = (0, import_node_fs.existsSync)(lastMessagePath) ? (0, import_node_fs.readFileSync)(lastMessagePath, "utf-8") : String(proc.stdout || "");
      const stdoutText = String(proc.stdout || "");
      const stderrText = String(proc.stderr || "");
      const runnerOutputs = [
        { source: (0, import_node_fs.existsSync)(lastMessagePath) ? "last_message" : "stdout", text: finalText },
        { source: "stdout", text: stdoutText },
        { source: "stderr", text: stderrText }
      ];
      const { parsed, source: parsedJsonSource } = parseJsonFromRunnerOutputs(runnerOutputs, request.schema);
      if (!parsed) {
        const outputAnalysis = analyzeCodexRunnerOutput(runnerOutputs);
        const errorCode = outputAnalysis.onlyLifecycleEvents ? "no_final_response" : "invalid_json";
        return {
          ok: false,
          stdout: stdoutText,
          stderr: stderrText,
          metrics: runnerMetrics({
            request,
            config,
            startedAt,
            startedMs,
            stdout: stdoutText,
            stderr: stderrText,
            finalText,
            status: proc.status,
            timeoutMs,
            errorCode,
            codexEventTypes: outputAnalysis.eventTypes,
            codexEventLineCount: outputAnalysis.eventLineCount,
            codexNonEventLineCount: outputAnalysis.nonEventLineCount
          }),
          blocker: {
            code: outputAnalysis.onlyLifecycleEvents ? "codex_no_final_response" : "codex_invalid_json",
            message: outputAnalysis.onlyLifecycleEvents ? `Codex emitted lifecycle events during ${request.purpose}, but did not produce a final JSON response.` : `Codex completed ${request.purpose}, but did not return valid JSON.`,
            details: {
              finalText,
              stdout: stdoutText,
              stderr: stderrText,
              event_types: outputAnalysis.eventTypes,
              event_line_count: outputAnalysis.eventLineCount,
              non_event_line_count: outputAnalysis.nonEventLineCount,
              non_event_samples: outputAnalysis.nonEventSamples
            }
          }
        };
      }
      return {
        ok: true,
        json: parsed,
        stdout: stdoutText,
        stderr: stderrText,
        metrics: runnerMetrics({
          request,
          config,
          startedAt,
          startedMs,
          stdout: stdoutText,
          stderr: stderrText,
          finalText,
          parsedJsonSource,
          status: proc.status,
          timeoutMs
        })
      };
    } finally {
      (0, import_node_fs.rmSync)(tmpDir, { recursive: true, force: true });
    }
  };
}
async function callRunner(runner, request) {
  return runner(request);
}
function payloadOrBlocker(raw, checkpoint) {
  if (!raw.ok || !raw.json) {
    const blocker = raw.blocker || {
      code: "codex_runner_failed",
      message: "Codex runner failed without a detailed blocker.",
      details: { stdout: raw.stdout || "", stderr: raw.stderr || "" }
    };
    return {
      ok: false,
      blocker: {
        ...blocker,
        checkpoint,
        details: {
          ...blocker.details || {},
          runner_metrics: raw.metrics || null
        }
      }
    };
  }
  return {
    ok: true,
    payload: raw.json,
    summary: typeof raw.json.summary === "string" ? raw.json.summary : void 0,
    details: compactRecord({
      runner_metrics: raw.metrics || null
    })
  };
}
function stringArray(value) {
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
}
function parseGitStatusPaths(status) {
  return status.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean).map((line) => {
    let item = line.length > 3 ? line.slice(3) : line;
    if (item.includes(" -> ")) item = item.split(" -> ").pop() || item;
    return item.trim();
  }).filter(Boolean);
}
function isToolNoisePath(filePath) {
  return filePath === ".codex" || filePath.startsWith(".codex/") || filePath === ".oc-smoke" || filePath.startsWith(".oc-smoke/");
}
function hasGitDiff(workdir) {
  try {
    const status = git(["status", "--porcelain"], workdir);
    return parseGitStatusPaths(status).some((filePath) => !isToolNoisePath(filePath));
  } catch {
    return false;
  }
}
function buildImplementationPrompt(context, extraLines = []) {
  return [
    basePrompt(context, "Implement the requested code change in the after worktree."),
    "Make the code changes directly in this repository.",
    "Use the recon-approved baseline understanding in the state to decide exactly what prior UI/state is being changed.",
    "Run focused checks when practical.",
    "If a focused check is blocked only by the harness sandbox writing Vite temp config into a shared/symlinked node_modules path (for example EROFS on node_modules/.vite-temp/vite.config...), do not treat that as an implementation blocker when the requested git diff exists. Record it in tests_run or implementation_notes instead so the harness can advance to its own verify stage.",
    "Leave a real git diff in the after worktree. Do not commit or push.",
    "Before you return success, run git status --short and git diff --name-only in this repository and verify they show the intended change.",
    "Do not return success with empty changed_files or a clean git status. If you cannot create the requested diff, explain why in blockers instead.",
    "changed_files should match the real git diff as closely as practical.",
    "Return changed_files, implementation_notes, tests_run, and blockers if any.",
    "Use empty arrays for tests_run or blockers when none apply.",
    ...extraLines
  ].join("\n");
}
function createCodexExecAgentAdapter(config = {}, runner = createCodexExecJsonRunner(config)) {
  return {
    async assessRecon(context) {
      const raw = await callRunner(runner, {
        purpose: "recon assessment",
        workdir: resolveWorkdir(context),
        schema: RECON_SCHEMA,
        prompt: [
          basePrompt(context, "Judge the latest recon packet."),
          "Decide whether recon should retry, continue to author, or escalate to the human.",
          "This is the first intelligent before-evidence gate. It runs before proof authoring and before any code edits.",
          "Prefer ready_for_author only when the baseline evidence is trustworthy for the requested change.",
          "Do not approve recon just because telemetry_ready is true or a screenshot URL exists.",
          "Inspect the baseline evidence in the state: screenshot URLs, structured pageState details, visible_text_sample, headings, buttons, links, canvas_count, large_visible_elements, observed_path, and route candidates.",
          "Fill baseline_understanding with concrete observations about what the before/prod evidence shows, what exact user request it anchors, what proof should focus on, and what stop condition would satisfy the request.",
          "If you cannot write a specific baseline_understanding from the current evidence, choose retry_recon or recon_stuck; do not choose ready_for_author.",
          "Reject blank, banner-only, app-shell-only, loading-only, generic landing, source-import path, or wrong-feature baselines; retry recon with a better server_path or selector instead.",
          "Your summary must say what is visibly present in the approved baseline or why the current baseline is not good enough.",
          "Always include refined_inputs; use null values for server_path, wait_for_selector, or reference when no refinement is needed."
        ].join("\n")
      });
      return payloadOrBlocker(raw, context.checkpoint);
    },
    async authorProofPacket(context) {
      const raw = await callRunner(runner, {
        purpose: "proof packet authoring",
        workdir: resolveWorkdir(context),
        schema: AUTHOR_SCHEMA,
        prompt: [
          basePrompt(context, "Author the proof packet."),
          "Write a proof_plan and capture_script that will verify the exact user-facing change.",
          "Use recon_assessment.baseline_understanding as the source of truth. Do not author a proof plan unless it names the observed before state and the requested delta from that state.",
          "Use the recon-approved route and baseline context; make the plan name the concrete target, expected before state, expected after state, and stop condition.",
          "Do not leave this authoring stage pending for external investigation. Keep any repo inspection brief, do not modify files, and return the JSON proof packet from the available state.",
          "Choose the evidence modality from verification_mode and success_criteria: screenshots for visual/UI proof, interactions plus screenshots for interaction proof, structured metrics/logs/JSON/audio analysis for non-visual proof.",
          "For playable/gameplay proof, treat screenshots as supporting artifacts only: start the game, send keyboard or pointer input, measure state before/after, measure non-HUD canvas/playfield pixel deltas across time, and return playability evidence with version riddle-proof.playability.v1.",
          "For interaction proof, return a structured evidence object with start route/state, terminal route/state, action, assertions, and matched UI text. Catch waitForURL or selector timeouts and record them as failed assertions instead of throwing before evidence is emitted.",
          "For structured proof, collect meaningful measurements inside page.evaluate, assign them to an evidence variable, and return that object from capture_script. Screenshots are optional supporting context for data/audio/log/metric/custom modes.",
          "Do not assign globalThis.__riddleProofEvidence, window.__riddleProofEvidence, or self.__riddleProofEvidence in the worker context. Avoid global evidence assignment unless it is inside page.evaluate for compatibility with older packets.",
          "Do not call Playwright page.* APIs inside page.evaluate; page.evaluate runs in the browser page, while page.waitForFunction, page.waitForSelector, page.click, and saveScreenshot belong in the outer capture script.",
          "When page.evaluate needs data from the outer Playwright script, pass exactly one serializable argument object; do not pass multiple positional arguments.",
          "When setting Playwright wait timeouts, use the correct signature: await page.waitForFunction(fn, undefined, { timeout: 60000 }). Do not write page.waitForFunction(fn, { timeout: 60000 }); that passes the object as the page argument and leaves the default timeout in place.",
          "For audio/data/metric proof, return the same evidence object: const evidence = await page.evaluate(async () => ({ /* browser measurements */ })); Then assert evidence fields before saving screenshots and return evidence from capture_script.",
          "If a capture attempt errors or proof_evidence is absent, revise the capture_script to make structured evidence easier to collect; do not only add more screenshots for non-visual proof.",
          "When checking visible copy, normalize text before exact matching: const normalizedText = (document.body?.innerText || '').replace(/\\s+/g, ' ').trim(); Avoid raw innerText.includes(exact sentence) because browser line wrapping can split copy.",
          "Prefer success-oriented evidence booleans such as newCopyVisible: true and oldCopyAbsent: true. If a positive assertion is false while screenshots/text samples look right, fix the capture script instead of leaving contradictory proof evidence.",
          "Include a short matchedSnippet or normalizedTextSample when proofing copy so assertion mismatches are diagnosable.",
          "For visual/UI proof, include saveScreenshot('after-proof') exactly once.",
          "Avoid generic proof language. The packet should be specific enough that verify can tell whether the requested change actually happened.",
          "Echo the baseline understanding you used in baseline_understanding_used so later stages can detect drift.",
          "Use refined_inputs for server_path, wait_for_selector, or reference when useful; use null values when no refinement is needed."
        ].join("\n")
      });
      return payloadOrBlocker(raw, context.checkpoint);
    },
    async implementChange(context) {
      if (!context.workdir || !(0, import_node_fs.existsSync)(context.workdir)) {
        return {
          ok: false,
          blocker: {
            code: "implementation_workdir_missing",
            checkpoint: context.checkpoint,
            message: "The Riddle Proof state does not include an after worktree that exists on disk.",
            details: { workdir: context.workdir || null }
          }
        };
      }
      const workdir = context.workdir;
      const attemptSummaries = [];
      const runImplementationAttempt = async (purpose, extraLines = []) => {
        const raw = await callRunner(runner, {
          purpose,
          workdir,
          schema: IMPLEMENT_SCHEMA,
          prompt: buildImplementationPrompt(context, extraLines)
        });
        if (!raw.ok || !raw.json) {
          return {
            ok: false,
            payload: payloadOrBlocker(raw, context.checkpoint)
          };
        }
        const changedFiles = stringArray(raw.json.changed_files);
        const blockers = stringArray(raw.json.blockers);
        const testsRun = stringArray(raw.json.tests_run);
        const softVerificationBlockers = changedFiles.length ? blockers.filter(isHarnessVerificationOnlyBlocker) : [];
        const hardBlockers = blockers.filter((item) => !softVerificationBlockers.includes(item));
        const implementationNotesRaw = typeof raw.json.implementation_notes === "string" ? raw.json.implementation_notes : "";
        const summary = typeof raw.json.summary === "string" ? raw.json.summary : "";
        const implementationNotes = [
          implementationNotesRaw,
          ...softVerificationBlockers.map((item) => `Harness verification note: ${item}`)
        ].filter(Boolean).join("\n");
        const agentDetails = {
          agent_purpose: purpose,
          agent_summary: summary,
          agent_changed_files: changedFiles,
          agent_tests_run: testsRun,
          agent_blockers: blockers,
          runner_metrics: raw.metrics || null
        };
        attemptSummaries.push({
          purpose,
          summary,
          changed_files: changedFiles,
          tests_run: testsRun,
          blockers,
          runner_metrics: raw.metrics || null
        });
        if (hardBlockers.length) {
          return {
            ok: false,
            payload: {
              ok: false,
              blocker: {
                code: "codex_implementation_blocked",
                checkpoint: context.checkpoint,
                message: summary || "Codex reported implementation blockers.",
                details: {
                  blockers: hardBlockers,
                  changedFiles,
                  testsRun,
                  implementationNotes: implementationNotesRaw,
                  ...agentDetails
                }
              }
            }
          };
        }
        return {
          ok: true,
          summary,
          changedFiles,
          testsRun,
          implementationNotes,
          implementationNotesRaw,
          softVerificationBlockers,
          hardBlockers,
          agentDetails
        };
      };
      let attempt = await runImplementationAttempt("implementation");
      if (!attempt.ok) return attempt.payload;
      let diffDetected = hasGitDiff(workdir);
      if (!diffDetected) {
        attempt = await runImplementationAttempt("implementation retry", [
          "The previous implementation attempt returned without a detectable git diff in this repository.",
          `Previous summary: ${attempt.summary || "(none)"}`,
          `Previous changed_files: ${JSON.stringify(attempt.changedFiles)}`,
          "Before you return success this time, run git status --short and git diff --name-only. If they are still empty, do not return success; either keep editing or explain the blocker."
        ]);
        if (!attempt.ok) return attempt.payload;
        diffDetected = hasGitDiff(workdir);
      }
      return {
        ok: true,
        summary: attempt.summary || void 0,
        implementationNotes: attempt.implementationNotes || void 0,
        changedFiles: attempt.changedFiles,
        testsRun: attempt.testsRun,
        details: {
          ...attempt.agentDetails,
          implementation_notes: attempt.implementationNotes || attempt.implementationNotesRaw || "",
          soft_verification_blockers: attempt.softVerificationBlockers,
          hard_blocker_count: attempt.hardBlockers.length,
          retry_attempted: attemptSummaries.length > 1,
          attempt_count: attemptSummaries.length,
          attempt_summaries: attemptSummaries,
          post_agent_diff_detected: diffDetected
        }
      };
    },
    async assessProof(context) {
      const raw = await callRunner(runner, {
        purpose: "proof assessment",
        workdir: resolveWorkdir(context),
        schema: PROOF_SCHEMA,
        prompt: [
          basePrompt(context, "Judge the proof bundle."),
          "Decide whether the evidence is ready_to_ship or which internal stage should run next.",
          "Only use ready_to_ship when the before/prod and after evidence actually prove the requested change.",
          "Do not assume screenshots are required for every verification_mode. For data/audio/log/metric/custom proof, inspect the structured evidence bundle, proof_evidence_sample, artifacts, assertions, and success criteria directly.",
          "Use semantic_context.route, headings, buttons, and text anchors to ground route/content judgment before calling screenshot evidence wrong-route or unrelated.",
          "If structured proof evidence contains failed positive assertions, such as newCopyVisible: false or hasExpectedText: false, do not choose ready_to_ship until the evidence is reconciled or a richer proof is produced.",
          "For visual/UI proof, screenshots and route/page-state quality still matter, but capture success alone is not proof.",
          "For playable/gameplay proof, do not choose ready_to_ship unless playability evidence shows accepted input, state/time progression, and playfield/canvas pixel motion; a static generated scene is not playable proof.",
          "For visual/UI polish, reject changes that are technically different but not legible to a reviewer. If visual_delta.status is measured and visual_delta.passed is false, choose needs_implementation when the visible result is wrong, or needs_richer_proof only when non-visual proof artifacts are insufficient.",
          "If required visual_delta is unmeasured, missing, or not_applicable, choose revise_capture with recommended_stage=verify and continue_with_stage=verify so the same run stays in evidence/comparison recovery; do not choose ready_to_ship or generic needs_richer_proof for that missing metric.",
          "Do not ship if the baseline is blank, shell-only, generic, or unrelated to the requested feature.",
          "Your summary must name the concrete change, the target that was tested, what changed between baseline and after evidence, and why the stop condition is satisfied."
        ].join("\n")
      });
      return payloadOrBlocker(raw, context.checkpoint);
    }
  };
}
function git(args, workdir) {
  return (0, import_node_child_process.execFileSync)("git", args, {
    cwd: workdir,
    encoding: "utf-8",
    timeout: 1e4
  });
}
async function runCodexExecAgentDoctor(config = {}, runner = createCodexExecJsonRunner(config)) {
  const workdir = (0, import_node_fs.mkdtempSync)(import_node_path.default.join(import_node_os.default.tmpdir(), "riddle-proof-codex-doctor-"));
  const targetPath = import_node_path.default.join(workdir, "target.txt");
  (0, import_node_fs.writeFileSync)(targetPath, "color=red\n");
  try {
    git(["init", "-b", "main"], workdir);
    git(["config", "user.email", "doctor@example.com"], workdir);
    git(["config", "user.name", "Riddle Proof Doctor"], workdir);
    git(["add", "target.txt"], workdir);
    git(["commit", "-m", "initial doctor fixture"], workdir);
  } catch (error) {
    return {
      ok: false,
      status: "blocked",
      blocker: {
        code: "doctor_git_setup_failed",
        message: "Could not create the temporary doctor git fixture.",
        details: { error: error instanceof Error ? error.message : String(error), workdir }
      }
    };
  }
  const raw = await callRunner(runner, {
    purpose: "codex exec doctor implementation",
    workdir,
    schema: IMPLEMENT_SCHEMA,
    prompt: [
      "You are running a Riddle Proof Codex exec doctor check.",
      "In this temporary git repository, edit target.txt so it says exactly: color=blue",
      "Do not commit. Leave a git diff.",
      "Return JSON matching the schema with changed_files containing target.txt.",
      "Use empty arrays for tests_run and blockers."
    ].join("\n")
  });
  if (!raw.ok || !raw.json) {
    return {
      ok: false,
      status: "blocked",
      blocker: {
        ...raw.blocker || {
          code: "doctor_codex_failed",
          message: "Codex doctor runner failed.",
          details: { stdout: raw.stdout || "", stderr: raw.stderr || "" }
        },
        details: {
          ...raw.blocker?.details || {},
          workdir
        }
      }
    };
  }
  const content = (0, import_node_fs.readFileSync)(targetPath, "utf-8");
  const status = git(["status", "--porcelain"], workdir);
  const changedFiles = stringArray(raw.json.changed_files);
  const ok = content.trim() === "color=blue" && status.includes("target.txt");
  return {
    ok,
    status: ok ? "passed" : "blocked",
    workdir,
    changedFiles,
    implementationSummary: raw.json.summary || null,
    implementationNotes: raw.json.implementation_notes || null,
    gitStatus: status,
    targetContent: content,
    blocker: ok ? null : {
      code: "doctor_diff_missing_or_wrong",
      message: "Codex doctor completed, but target.txt was not changed to color=blue with a git diff.",
      details: { workdir, changedFiles, gitStatus: status, targetContent: content }
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createCodexExecAgentAdapter,
  createCodexExecJsonRunner,
  runCodexExecAgentDoctor
});
