// 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 failStdin = (err) => failCandidate(`writing to MCP server stdin failed: ${err.message}`);
    const send = (msg) => {
      try {
        child.stdin.write(`${JSON.stringify(msg)}
`);
        return true;
      } catch (err) {
        failStdin(err);
        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.stdin.on("error", failStdin);
    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 {
  toolBuildPrompt,
  mcpBuildPrompt,
  mcpServeVerifier
};
//# sourceMappingURL=chunk-6O73TRHW.js.map