import "./chunk-QDVLTRCP.js";
import {
  createSandboxForSpec
} from "./chunk-SSA6OERV.js";
import "./chunk-UD4BHQMI.js";
import "./chunk-BZF3KQ6G.js";
import {
  mapSandboxEvent
} from "./chunk-4J6RBI3K.js";
import "./chunk-7LO5GMAO.js";
import "./chunk-YEJR7IXO.js";
import "./chunk-DPEUKJRO.js";
import {
  __require
} from "./chunk-DGUM43GV.js";

// src/agent/surfaces.ts
import { existsSync } from "fs";
import { isAbsolute, join } from "path";
function resolveSubjectPath(subject, surfaces, repoRoot) {
  const candidates = candidatePathsForSubject(subject, surfaces);
  if (candidates.length === 0) return null;
  for (const rel of candidates) {
    const abs = isAbsolute(rel) ? rel : join(repoRoot, rel);
    if (existsSync(abs)) {
      return { absolutePath: abs, repoRelativePath: rel, exists: true, intent: "edit-existing" };
    }
  }
  const fallback = candidates[0];
  const fallbackAbs = isAbsolute(fallback) ? fallback : join(repoRoot, fallback);
  return {
    absolutePath: fallbackAbs,
    repoRelativePath: fallback,
    exists: false,
    intent: "create-new"
  };
}
function candidatePathsForSubject(subject, surfaces) {
  switch (subject.kind) {
    case "knowledge.wiki":
    case "knowledge.stale":
      return [join(surfaces.knowledge, `${subject.slug}.md`)];
    case "knowledge.claim":
      return [join(surfaces.knowledge, "claims", `${slugify(subject.topic)}.md`)];
    case "knowledge.raw":
      return [join(surfaces.knowledge, "raw", `${subject.sourceId}.md`)];
    case "system-prompt": {
      const slug = slugify(subject.section);
      return [
        join(surfaces.systemPrompt, `${slug}.md`),
        join(surfaces.systemPrompt, slug, "SKILL.md"),
        join(surfaces.systemPrompt, slug, "index.md")
      ];
    }
    case "tool-doc":
      if (subject.aspect) {
        return [join(surfaces.tools, subject.tool, `${slugify(subject.aspect)}.md`)];
      }
      return [
        join(surfaces.tools, subject.tool, "README.md"),
        join(surfaces.tools, `${subject.tool}.md`)
      ];
    case "new-tool":
      return [join(surfaces.tools, subject.name, "README.md")];
    case "rag":
      if (!surfaces.rag) return [];
      return [join(surfaces.rag, subject.corpus, `${subject.docId}.md`)];
    case "memory":
      if (!surfaces.memory) return [];
      return [join(surfaces.memory, `${slugify(subject.key)}.json`)];
    case "scaffolding":
      if (!surfaces.scaffolding) return [];
      return [join(surfaces.scaffolding, `${slugify(subject.concern)}.md`)];
    case "output-schema":
      if (!surfaces.outputSchema) return [];
      return [surfaces.outputSchema];
    case "websearch.outdated":
    case "prior-run-summary":
      return [];
    case "cluster":
      return [];
  }
}
function slugify(s) {
  return s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200) || "untitled";
}
function validateSurfaces(surfaces, repoRoot) {
  const issues = [];
  const dirSurfaces = [
    "systemPrompt",
    "tools",
    "personas",
    "knowledge"
  ];
  const fileSurfaces = ["rubric"];
  const optionalDirSurfaces = ["scaffolding", "memory", "rag"];
  const optionalFileSurfaces = ["outputSchema"];
  for (const key of dirSurfaces) {
    const p = surfaces[key];
    if (!p) {
      issues.push({ surface: key, path: "", reason: "missing" });
      continue;
    }
    const abs = isAbsolute(p) ? p : join(repoRoot, p);
    if (!existsSync(abs)) {
      issues.push({ surface: key, path: p, reason: "missing" });
    }
  }
  for (const key of fileSurfaces) {
    const p = surfaces[key];
    if (!p) {
      issues.push({ surface: key, path: "", reason: "missing" });
      continue;
    }
    const abs = isAbsolute(p) ? p : join(repoRoot, p);
    if (!existsSync(abs)) {
      issues.push({ surface: key, path: p, reason: "missing" });
    }
  }
  for (const key of [...optionalDirSurfaces, ...optionalFileSurfaces]) {
    const p = surfaces[key];
    if (p === void 0) continue;
    const abs = isAbsolute(p) ? p : join(repoRoot, p);
    if (!existsSync(abs)) {
      issues.push({ surface: key, path: p, reason: "missing" });
    }
  }
  return issues;
}
function renderSurfaceIssues(issues, repoRoot) {
  if (issues.length === 0) return "";
  const lines = issues.map(
    (i) => `  - ${i.surface}: ${i.path ? `"${i.path}"` : "<not set>"} (${i.reason})`
  );
  return [
    `Agent surface validation failed against repoRoot=${repoRoot}:`,
    ...lines,
    "",
    "Fix the manifest: every required surface must point at an existing",
    "directory (systemPrompt / tools / personas / knowledge) or file",
    "(rubric). Optional surfaces (scaffolding / memory / rag / outputSchema)",
    "may be omitted; the loop will reject findings targeting omitted",
    "surfaces rather than fabricating a path."
  ].join("\n");
}

// src/agent/define-agent.ts
function unimplementedAgentRun(reason = "AgentRuntime.act is not yet wired for this manifest") {
  return {
    events: (async function* empty() {
    })(),
    output: Promise.reject(new Error(reason))
  };
}
async function collectAgentRun(invocation) {
  const events = [];
  for await (const ev of invocation.events) events.push(ev);
  const output = await invocation.output;
  return { events, output };
}
var AgentManifestError = class extends Error {
  constructor(message, agentId, issues = []) {
    super(message);
    this.agentId = agentId;
    this.issues = issues;
    this.name = "AgentManifestError";
  }
  agentId;
  issues;
};
function defineAgent(manifest) {
  if (!manifest.id || manifest.id.trim().length === 0) {
    throw new AgentManifestError("defineAgent: `id` is required", manifest.id ?? "");
  }
  if (!manifest.repoRoot || manifest.repoRoot.trim().length === 0) {
    throw new AgentManifestError("defineAgent: `repoRoot` is required", manifest.id);
  }
  const issues = validateSurfaces(manifest.surfaces, manifest.repoRoot);
  if (issues.length > 0) {
    throw new AgentManifestError(
      renderSurfaceIssues(issues, manifest.repoRoot),
      manifest.id,
      issues
    );
  }
  const total = manifest.rubric.dimensions.reduce((acc, d) => acc + d.weight, 0);
  if (manifest.rubric.dimensions.length > 0 && (total < 0.5 || total > 1.5)) {
    throw new AgentManifestError(
      `defineAgent(${manifest.id}): rubric dimension weights sum to ${total.toFixed(3)} \u2014 should be ~1.0`,
      manifest.id
    );
  }
  return manifest;
}

// src/agent/improvement-adapter.ts
import { spawnSync } from "child_process";
import { readFileSync } from "fs";
import { parseFindingSubject } from "@tangle-network/agent-eval/analyst";
var DEFAULT_CREATE_KINDS = [
  "knowledge.wiki",
  "knowledge.claim",
  "knowledge.raw",
  "new-tool"
];
function createSurfaceImprovementAdapter(opts) {
  const mode = opts.mode ?? "none";
  const allowCreate = opts.allowCreateForKinds ?? DEFAULT_CREATE_KINDS;
  return {
    async proposeFromFindings(findings) {
      const edits = [];
      const errors = [];
      let skipped = 0;
      for (const f of findings) {
        const subject = parseFindingSubject(f.subject);
        if (subject === null) {
          if (f.subject !== void 0) {
            errors.push({
              findingId: f.finding_id,
              subject: f.subject,
              message: "subject does not parse against the finding-subject grammar"
            });
          } else {
            skipped += 1;
          }
          continue;
        }
        if (subject.kind === "cluster") {
          skipped += 1;
          continue;
        }
        if (subject.kind.startsWith("knowledge.")) {
          skipped += 1;
          continue;
        }
        const target = resolveSubjectPath(subject, opts.surfaces, opts.repoRoot);
        if (target === null) {
          errors.push({
            findingId: f.finding_id,
            subject: f.subject ?? "",
            message: `subject kind "${subject.kind}" targets an undeclared surface; declare it in AgentSurfaces or stop emitting this subject`
          });
          continue;
        }
        if (target.intent === "create-new" && !allowCreate.includes(subject.kind)) {
          errors.push({
            findingId: f.finding_id,
            subject: f.subject ?? "",
            message: `target ${target.repoRelativePath} does not exist; the kind "${subject.kind}" requires an existing target (analyst named a section that isn't in the codebase)`
          });
          continue;
        }
        const currentContent = target.exists ? readFileSync(target.absolutePath, "utf-8") : "";
        let draft;
        try {
          draft = await opts.draftPatch({ finding: f, subject, target, currentContent });
        } catch (err) {
          errors.push({
            findingId: f.finding_id,
            subject: f.subject ?? "",
            message: `draftPatch threw: ${err instanceof Error ? err.message : String(err)}`
          });
          continue;
        }
        if (draft.patch.trim().length === 0) {
          skipped += 1;
          continue;
        }
        edits.push({
          id: `imp-${f.finding_id}`,
          sourceFindingId: f.finding_id,
          subject,
          target,
          baseSha256: sha256(currentContent),
          patch: draft.patch,
          summary: draft.summary,
          rationale: draft.rationale,
          confidence: f.confidence,
          severity: f.severity
        });
      }
      return { edits, skipped, errors };
    },
    async apply(edits) {
      const applied = [];
      const warnings = [];
      if (mode === "none") {
        warnings.push(
          "createSurfaceImprovementAdapter: mode=none; no edits applied \u2014 adjust manifest.autoApply.improvement.mode"
        );
        return { applied, warnings };
      }
      if (mode === "open-pr" && !opts.ghRepo) {
        warnings.push(
          "createSurfaceImprovementAdapter: mode=open-pr requires `ghRepo`; falling back to no-op"
        );
        return { applied, warnings };
      }
      for (const edit of edits) {
        const current = edit.target.exists ? readFileSync(edit.target.absolutePath, "utf-8") : "";
        if (sha256(current) !== edit.baseSha256) {
          warnings.push(
            `${edit.target.repoRelativePath}: base SHA mismatch; file changed after draft. Skipping.`
          );
          continue;
        }
        const ok = applyPatchInPlace(edit, opts.repoRoot);
        if (!ok) {
          warnings.push(`${edit.target.repoRelativePath}: git apply failed`);
          continue;
        }
        applied.push(edit.target.repoRelativePath);
      }
      if (mode === "open-pr" && applied.length > 0 && opts.ghRepo) {
        const prUrl = openPullRequest(
          applied,
          edits.filter((e) => applied.includes(e.target.repoRelativePath)),
          opts.repoRoot,
          opts.ghRepo,
          opts.baseBranch ?? "main"
        );
        if (prUrl) warnings.push(`opened PR: ${prUrl}`);
        else warnings.push("PR creation failed; edits are committed to a local branch only");
      }
      return { applied, warnings };
    }
  };
}
function applyPatchInPlace(edit, repoRoot) {
  const result = spawnSync("git", ["apply", "--whitespace=fix", "-p0", "-"], {
    cwd: repoRoot,
    input: edit.patch,
    encoding: "utf-8"
  });
  return result.status === 0;
}
function openPullRequest(paths, edits, repoRoot, ghRepo, baseBranch) {
  const branch = `analyst-loop/${Date.now()}-${edits[0]?.sourceFindingId.slice(0, 12) ?? "edits"}`;
  const checkout = spawnSync("git", ["checkout", "-b", branch], { cwd: repoRoot });
  if (checkout.status !== 0) return null;
  const add = spawnSync("git", ["add", ...paths], { cwd: repoRoot });
  if (add.status !== 0) return null;
  const title = `analyst-loop: ${edits[0]?.summary ?? `${edits.length} improvement edits`}`;
  const body = [
    `Automated analyst-loop edits \u2014 review carefully before merge.`,
    "",
    `Source findings:`,
    ...edits.map(
      (e) => `  - ${e.sourceFindingId} (confidence ${e.confidence.toFixed(2)}, severity ${e.severity})`
    ),
    "",
    "Rationales:",
    ...edits.map((e) => `
## ${e.target.repoRelativePath}

${e.rationale}`)
  ].join("\n");
  const commit = spawnSync("git", ["commit", "-m", title, "-m", body], { cwd: repoRoot });
  if (commit.status !== 0) return null;
  const push = spawnSync("git", ["push", "-u", "origin", branch], { cwd: repoRoot });
  if (push.status !== 0) return null;
  const pr = spawnSync(
    "gh",
    [
      "pr",
      "create",
      "--repo",
      ghRepo,
      "--title",
      title,
      "--body",
      body,
      "--base",
      baseBranch,
      "--head",
      branch
    ],
    { cwd: repoRoot, encoding: "utf-8" }
  );
  if (pr.status !== 0) return null;
  return pr.stdout.trim();
}
function sha256(s) {
  const crypto = __require("crypto");
  return crypto.createHash("sha256").update(s, "utf-8").digest("hex");
}

// src/agent/knowledge-adapter.ts
function createSurfaceKnowledgeAdapter(opts, deps) {
  return {
    proposeFromFindings(findings) {
      const batch = deps.proposeFromFindings(findings);
      return {
        proposals: batch.proposals,
        skipped: batch.skipped,
        errors: batch.errors
      };
    },
    async apply(proposals) {
      const written = [];
      const warnings = [];
      for (const p of proposals) {
        const proposalText = renderProposalAsWriteBlock(p);
        if (proposalText === null) {
          warnings.push(
            `proposal has no writeBlocks/content; skipping (sourceFindingId=${getSourceFindingId(p)})`
          );
          continue;
        }
        try {
          const r = await deps.applyKnowledgeWriteBlocks(opts.knowledgeRoot, proposalText);
          written.push(...r.written);
          warnings.push(...r.warnings);
        } catch (err) {
          warnings.push(
            `applyKnowledgeWriteBlocks failed: ${err instanceof Error ? err.message : String(err)}`
          );
        }
      }
      if (deps.lintAfterApply && written.length > 0) {
        try {
          const lintIssues = await deps.lintAfterApply(opts.knowledgeRoot);
          for (const issue of lintIssues) warnings.push(`lint: ${issue}`);
        } catch (err) {
          warnings.push(
            `lintAfterApply failed: ${err instanceof Error ? err.message : String(err)}`
          );
        }
      }
      return { written, warnings };
    }
  };
}
function renderProposalAsWriteBlock(p) {
  if (!p || typeof p !== "object") return null;
  const obj = p;
  if (Array.isArray(obj.writeBlocks)) {
    const blocks = obj.writeBlocks;
    if (blocks.length === 0) return null;
    return blocks.map((b) => typeof b.content === "string" ? b.content : "").filter((s) => s.length > 0).join("\n\n");
  }
  if (typeof obj.proposalText === "string") return obj.proposalText;
  if (typeof obj.content === "string") return obj.content;
  return null;
}
function getSourceFindingId(p) {
  if (!p || typeof p !== "object") return "<unknown>";
  const obj = p;
  if (typeof obj.sourceFindingId === "string") return obj.sourceFindingId;
  if (typeof obj.id === "string") return obj.id;
  return "<unknown>";
}

// src/agent/outcome.ts
async function measureOutcome(result, opts) {
  const applied = result.knowledge?.applied ?? [];
  const improvementsApplied = result.improvement?.applied ?? [];
  const allApplied = [...applied, ...improvementsApplied];
  if (allApplied.length === 0) {
    return {
      ...result,
      outcome: {
        baselineComposite: meanComposite(opts.baseline),
        afterComposite: meanComposite(opts.baseline),
        delta: 0,
        perPersona: opts.baseline.map((b) => ({
          personaId: b.personaId,
          before: b.composite,
          after: b.composite,
          delta: 0
        })),
        rolledBackPaths: []
      }
    };
  }
  const personaIds = opts.baseline.map((b) => b.personaId);
  const after = await opts.reRunCohort(personaIds);
  const afterByPersona = new Map(after.map((r) => [r.personaId, r.composite]));
  const perPersona = opts.baseline.map((b) => {
    const a = afterByPersona.get(b.personaId) ?? b.composite;
    return { personaId: b.personaId, before: b.composite, after: a, delta: a - b.composite };
  });
  const baselineComposite = meanComposite(opts.baseline);
  const afterComposite = meanComposite(after);
  const delta = afterComposite - baselineComposite;
  let rolledBackPaths = [];
  if (delta < 0 && opts.rollbackOnRegression && opts.revert) {
    await opts.revert(allApplied);
    rolledBackPaths = [...allApplied];
  }
  return {
    ...result,
    outcome: {
      baselineComposite,
      afterComposite,
      delta,
      perPersona,
      rolledBackPaths
    }
  };
}
function meanComposite(rows) {
  if (rows.length === 0) return 0;
  return rows.reduce((acc, r) => acc + r.composite, 0) / rows.length;
}

// src/agent/sandbox-act.ts
function createSandboxAct(options) {
  const mapEvent = options.mapEvent ?? mapSandboxEvent;
  return (persona, ctx) => {
    const profile = applyComposeOverrides(options.baseProfile, options.compose?.(persona));
    const agentRunName = options.name ?? profile.name ?? "agent";
    const message = options.buildPrompt(persona);
    const signal = ctx.signal ?? new AbortController().signal;
    const raw = [];
    let settle;
    let fail;
    const output = new Promise((resolve, reject) => {
      settle = resolve;
      fail = reject;
    });
    output.catch(() => {
    });
    const spec = {
      profile,
      taskToPrompt: () => message,
      name: agentRunName,
      ...options.sandboxOverrides ? { sandboxOverrides: options.sandboxOverrides } : {}
    };
    async function* events() {
      try {
        const box = await createSandboxForSpec(options.sandboxClient, spec, signal);
        for await (const event of box.streamPrompt(message, { signal })) {
          raw.push(event);
          const mapped = mapEvent(event, { agentRunName });
          if (mapped) yield mapped;
        }
        settle(options.output.parse(raw));
      } catch (err) {
        fail(err);
        throw err;
      }
    }
    return { events: events(), output };
  };
}
function applyComposeOverrides(base, overrides) {
  if (!overrides) return base;
  const prompt = overrides.systemPrompt ? { ...base.prompt, systemPrompt: overrides.systemPrompt } : base.prompt;
  const mergedTools = overrides.tools ? { ...base.tools ?? {}, ...overrides.tools } : base.tools;
  const mergedMcp = overrides.mcpConnections ? { ...base.mcp ?? {}, ...overrides.mcpConnections } : base.mcp;
  const baseFiles = base.resources?.files ?? [];
  const mergedFiles = overrides.extraFiles?.length ? [...baseFiles, ...overrides.extraFiles] : [...baseFiles];
  return {
    ...base,
    name: overrides.name ?? base.name,
    prompt,
    ...mergedTools ? { tools: mergedTools } : {},
    ...mergedMcp ? { mcp: mergedMcp } : {},
    resources: { ...base.resources, files: mergedFiles }
  };
}
export {
  AgentManifestError,
  collectAgentRun,
  createSandboxAct,
  createSurfaceImprovementAdapter,
  createSurfaceKnowledgeAdapter,
  defineAgent,
  measureOutcome,
  renderSurfaceIssues,
  resolveSubjectPath,
  unimplementedAgentRun,
  validateSurfaces
};
//# sourceMappingURL=agent.js.map