import {
  runLocalHarness
} from "./chunk-7LO5GMAO.js";

// src/improvement/agentic-generator.ts
import { spawnSync } from "child_process";
function agenticGenerator(opts = {}) {
  const harness = opts.harness ?? "claude";
  const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt;
  const run = opts.runHarness ?? runLocalHarness;
  const dirty = opts.isDirty ?? worktreeDirty;
  const verify = opts.verify;
  return {
    kind: `agentic:${harness}`,
    async generate({ worktreePath, report, findings, maxShots, signal }) {
      const basePrompt = buildPrompt({ report, findings });
      const shots = Math.max(1, maxShots);
      let attemptNote = "";
      for (let shot = 0; shot < shots; shot++) {
        if (signal.aborted) break;
        await run({
          harness,
          cwd: worktreePath,
          taskPrompt: attemptNote ? `${basePrompt}

${attemptNote}` : basePrompt,
          timeoutMs: opts.timeoutMs,
          signal
        });
        if (!dirty(worktreePath)) {
          attemptNote = EMPTY_TREE_NOTE;
          continue;
        }
        if (!verify) {
          return { applied: true, summary: summarize(findings) };
        }
        const result = await verify(worktreePath);
        if (result.ok) {
          return { applied: true, summary: summarize(findings) };
        }
        attemptNote = failureNote(result.feedback);
      }
      return { applied: false, summary: "" };
    }
  };
}
function defaultBuildPrompt(args) {
  const lines = [
    "You are improving this codebase based on an evaluation analysis.",
    "Make the smallest set of edits that addresses the findings below, then stop.",
    "Do not change unrelated code. Do not commit \u2014 leave changes in the working tree.",
    "",
    "Findings:"
  ];
  for (const f of args.findings) {
    const where = f.subject ? ` [${f.subject}]` : "";
    lines.push(`- (${f.severity})${where} ${f.claim}`);
    if (f.recommended_action) lines.push(`    \u2192 ${f.recommended_action}`);
  }
  return lines.join("\n");
}
var EMPTY_TREE_NOTE = "NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.";
function failureNote(feedback) {
  const detail = feedback?.trim();
  return [
    "NOTE: your edits are in the working tree but verification FAILED.",
    "Fix the problem in place \u2014 build on your existing edits, do not revert them.",
    detail ? `Verifier output:
${truncate(detail, 4e3)}` : "No verifier detail was captured."
  ].join("\n");
}
function commandVerifier(command, args = [], timeoutMs = 3e5) {
  return (worktreePath) => {
    const result = spawnSync(command, args, {
      cwd: worktreePath,
      encoding: "utf-8",
      timeout: timeoutMs
    });
    if (result.signal) {
      return {
        ok: false,
        feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`
      };
    }
    if (result.error) {
      const code = result.error.code;
      if (code === "ENOENT") {
        throw new Error(
          `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`
        );
      }
      throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`);
    }
    if (result.status === 0) return { ok: true };
    const out = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
    return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` };
  };
}
function summarize(findings) {
  if (findings.length === 0) return "agentic improvement";
  if (findings.length === 1) return `agentic: ${truncate(findings[0].claim, 64)}`;
  return `agentic: ${findings.length} findings addressed`;
}
function truncate(s, n) {
  return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
}
function worktreeDirty(worktreePath) {
  const result = spawnSync("git", ["status", "--porcelain"], {
    cwd: worktreePath,
    encoding: "utf-8"
  });
  if (result.error) {
    throw new Error(
      `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`
    );
  }
  if (result.status !== 0) {
    throw new Error(
      `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`
    );
  }
  return result.stdout.trim().length > 0;
}

// src/improvement/build-prompts.ts
function findingLines(findings) {
  return findings.map((f) => {
    const where = f.subject ? ` [${f.subject}]` : "";
    const action = f.recommended_action ? ` \u2192 ${f.recommended_action}` : "";
    return `- (${f.severity})${where} ${f.claim}${action}`;
  });
}
function toolBuildPrompt(args) {
  return [
    "You are building a new TOOL for this codebase to address the gaps below.",
    "Write the tool as a small, self-contained module PLUS tests that exercise it.",
    "The tool must compile and its tests must pass \u2014 they will be run automatically;",
    "if verification fails you will get the error and another attempt. Do not commit;",
    "leave the changes in the working tree.",
    "",
    "Gaps the tool should close:",
    ...findingLines(args.findings)
  ].join("\n");
}
function mcpBuildPrompt(args) {
  return [
    "You are building a new MCP SERVER (Model Context Protocol) that exposes",
    "tool(s) addressing the gaps below, so any harness can mount it.",
    "Requirements that WILL be checked by booting the server:",
    "- it starts over stdio and answers the MCP `initialize` handshake,",
    "- `tools/list` returns at least one tool with a valid input schema.",
    "Newline-delimited JSON-RPC 2.0, protocol version 2024-11-05. Include a start",
    "command (e.g. a package.json `start` script or a clear entrypoint). If the",
    "boot-and-probe fails you will get the error and another attempt. Do not",
    "commit; leave the changes in the working tree.",
    "",
    "Capabilities the server should provide:",
    ...findingLines(args.findings)
  ].join("\n");
}

// src/improvement/mcp-serve-verifier.ts
import { spawn } from "child_process";
import { createInterface } from "readline";
var PROTOCOL_VERSION = "2024-11-05";
function mcpServeVerifier(spec) {
  const timeoutMs = spec.timeoutMs ?? 3e4;
  const minTools = spec.minTools ?? 1;
  return (worktreePath) => new Promise((resolve, reject) => {
    const child = spawn(spec.command, spec.args ?? [], {
      cwd: worktreePath,
      stdio: ["pipe", "pipe", "pipe"],
      env: { ...process.env, ...spec.env }
    });
    const stderr = [];
    let settled = false;
    let nextId = 1;
    const initId = nextId++;
    let listId = -1;
    const settle = (fn) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      rl.close();
      child.kill("SIGKILL");
      fn();
    };
    const withStderr = (msg) => stderr.length > 0 ? `${msg}
stderr:
${stderr.join("").slice(-2e3)}` : msg;
    const pass = () => settle(() => resolve({ ok: true }));
    const failCandidate = (msg) => settle(() => resolve({ ok: false, feedback: withStderr(msg) }));
    const setupFault = (err) => settle(() => reject(err));
    const send = (msg) => {
      try {
        child.stdin.write(`${JSON.stringify(msg)}
`);
        return true;
      } catch (err) {
        failCandidate(`writing to MCP server stdin failed: ${err.message}`);
        return false;
      }
    };
    child.on("error", (err) => {
      const code = err.code;
      setupFault(
        code === "ENOENT" ? new Error(
          `mcpServeVerifier: '${spec.command}' not found in PATH (setup bug, not a failed candidate)`
        ) : new Error(`mcpServeVerifier: '${spec.command}' failed to spawn: ${err.message}`)
      );
    });
    child.on("exit", (code, signal) => {
      failCandidate(`MCP server exited (code ${code}, signal ${signal}) before serving`);
    });
    child.stderr.on("data", (d) => stderr.push(String(d)));
    const rl = createInterface({ input: child.stdout });
    rl.on("line", (line) => {
      let msg;
      try {
        msg = JSON.parse(line);
      } catch {
        return;
      }
      if (!msg || typeof msg !== "object") return;
      if (msg.id === initId) {
        if (msg.error) return failCandidate(`initialize errored: ${JSON.stringify(msg.error)}`);
        if (!send({ jsonrpc: "2.0", method: "notifications/initialized" })) return;
        listId = nextId++;
        send({ jsonrpc: "2.0", id: listId, method: "tools/list" });
        return;
      }
      if (msg.id === listId) {
        if (msg.error) return failCandidate(`tools/list errored: ${JSON.stringify(msg.error)}`);
        const tools = msg.result?.tools;
        if (!Array.isArray(tools)) return failCandidate("tools/list result has no tools array");
        if (tools.length < minTools) {
          return failCandidate(`tools/list returned ${tools.length} tool(s), need >= ${minTools}`);
        }
        return pass();
      }
    });
    const timer = setTimeout(
      () => failCandidate(`MCP server did not complete the handshake within ${timeoutMs}ms`),
      timeoutMs
    );
    send({
      jsonrpc: "2.0",
      id: initId,
      method: "initialize",
      params: {
        protocolVersion: PROTOCOL_VERSION,
        capabilities: {},
        clientInfo: { name: "agent-runtime-mcp-verify", version: "0" }
      }
    });
  });
}

export {
  agenticGenerator,
  commandVerifier,
  toolBuildPrompt,
  mcpBuildPrompt,
  mcpServeVerifier
};
//# sourceMappingURL=chunk-VNOOH22O.js.map