import {
  callLlm
} from "./chunk-CWNP4DV4.js";
import {
  makeFinding
} from "./chunk-45EEMHTC.js";
import {
  TraceFileMissingError,
  buildTraceAnalystTools
} from "./chunk-YBIGNSCZ.js";

// src/analyst/finding-subject.ts
import { z } from "zod";
var FINDING_SUBJECT_KINDS = [
  "knowledge.wiki",
  "knowledge.claim",
  "knowledge.raw",
  "knowledge.stale",
  "system-prompt",
  "tool-doc",
  "new-tool",
  "rag",
  "memory",
  "scaffolding",
  "output-schema",
  "websearch.outdated",
  "prior-run-summary",
  "cluster"
];
function parseFindingSubject(raw) {
  if (raw === null || raw === void 0) return null;
  const trimmed = raw.trim();
  if (trimmed.length === 0) return null;
  const wiki = trimmed.match(
    /^agent-knowledge:wiki:([a-z0-9][a-z0-9-]*)(?:#([a-z0-9][a-z0-9-]*))?$/
  );
  if (wiki)
    return { kind: "knowledge.wiki", slug: wiki[1], ...wiki[2] ? { heading: wiki[2] } : {} };
  const claim = trimmed.match(/^agent-knowledge:claim:(.+)$/);
  if (claim && claim[1].trim().length > 0)
    return { kind: "knowledge.claim", topic: claim[1].trim() };
  const raw_ = trimmed.match(/^agent-knowledge:raw:(.+)$/);
  if (raw_ && raw_[1].trim().length > 0)
    return { kind: "knowledge.raw", sourceId: raw_[1].trim() };
  const stale = trimmed.match(/^agent-knowledge:stale:([a-z0-9][a-z0-9-]*)$/);
  if (stale) return { kind: "knowledge.stale", slug: stale[1] };
  const sp = trimmed.match(/^system-prompt:(.+)$/);
  if (sp && sp[1].trim().length > 0) return { kind: "system-prompt", section: sp[1].trim() };
  const tdAspect = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*):(.+)$/);
  if (tdAspect && tdAspect[2].trim().length > 0) {
    return { kind: "tool-doc", tool: tdAspect[1], aspect: tdAspect[2].trim() };
  }
  const td = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*)$/);
  if (td) return { kind: "tool-doc", tool: td[1] };
  const nt = trimmed.match(/^new-tool:([a-z0-9][a-z0-9_-]*)$/);
  if (nt) return { kind: "new-tool", name: nt[1] };
  const rag = trimmed.match(/^rag:([a-z0-9][a-z0-9_-]*):(.+)$/);
  if (rag && rag[2].trim().length > 0) {
    return { kind: "rag", corpus: rag[1], docId: rag[2].trim() };
  }
  const mem = trimmed.match(/^memory:(.+)$/);
  if (mem && mem[1].trim().length > 0) return { kind: "memory", key: mem[1].trim() };
  const sc = trimmed.match(/^scaffolding:(.+)$/);
  if (sc && sc[1].trim().length > 0) return { kind: "scaffolding", concern: sc[1].trim() };
  const os = trimmed.match(/^output-schema:(.+)$/);
  if (os && os[1].trim().length > 0) return { kind: "output-schema", field: os[1].trim() };
  const ws = trimmed.match(/^websearch:outdated:(.+)$/);
  if (ws && ws[1].trim().length > 0) return { kind: "websearch.outdated", topic: ws[1].trim() };
  const prs = trimmed.match(/^prior-run-summary:(.+)$/);
  if (prs && prs[1].trim().length > 0) return { kind: "prior-run-summary", topic: prs[1].trim() };
  if (/^[a-z0-9][a-z0-9._-]*$/.test(trimmed) && trimmed.length <= 80) {
    return { kind: "cluster", label: trimmed };
  }
  return null;
}
function renderFindingSubject(s) {
  switch (s.kind) {
    case "knowledge.wiki":
      return s.heading ? `agent-knowledge:wiki:${s.slug}#${s.heading}` : `agent-knowledge:wiki:${s.slug}`;
    case "knowledge.claim":
      return `agent-knowledge:claim:${s.topic}`;
    case "knowledge.raw":
      return `agent-knowledge:raw:${s.sourceId}`;
    case "knowledge.stale":
      return `agent-knowledge:stale:${s.slug}`;
    case "system-prompt":
      return `system-prompt:${s.section}`;
    case "tool-doc":
      return s.aspect ? `tool-doc:${s.tool}:${s.aspect}` : `tool-doc:${s.tool}`;
    case "new-tool":
      return `new-tool:${s.name}`;
    case "rag":
      return `rag:${s.corpus}:${s.docId}`;
    case "memory":
      return `memory:${s.key}`;
    case "scaffolding":
      return `scaffolding:${s.concern}`;
    case "output-schema":
      return `output-schema:${s.field}`;
    case "websearch.outdated":
      return `websearch:outdated:${s.topic}`;
    case "prior-run-summary":
      return `prior-run-summary:${s.topic}`;
    case "cluster":
      return s.label;
  }
}
var FINDING_SUBJECT_GRAMMAR_PROMPT = [
  "Subjects MUST match this grammar \u2014 anything else is rejected at parse time and your work is wasted:",
  "",
  "  Knowledge loci (write to the agent-knowledge base):",
  "    agent-knowledge:wiki:<slug>[#<heading>]   create / update a wiki page",
  "    agent-knowledge:claim:<topic>             draft a claim / relation triple",
  "    agent-knowledge:raw:<source-id>           lift a raw source into a curated page",
  "    agent-knowledge:stale:<slug>              mark a page superseded",
  "",
  "  Runtime mutable surfaces (write to prompts / tools / scaffolding):",
  "    system-prompt:<section>                   add / replace a system-prompt section",
  "    tool-doc:<tool>[:<aspect>]                rewrite a tool description",
  "    new-tool:<name>                           propose a new tool surface",
  "    rag:<corpus>:<doc-id>                     ingest / correct a RAG document",
  "    memory:<key>                              invalidate / set a memory entry",
  "    scaffolding:<concern>                     change a precondition / retry / verifier",
  "    output-schema:<field>                     constrain the agent output shape",
  "",
  "  Stale signals (knowledge-poisoning only):",
  "    websearch:outdated:<topic>                stale web result",
  "    prior-run-summary:<topic>                 stale prior-run summary",
  "",
  "  Cluster label (failure-mode only):",
  '    <kebab-case-label>                        short cluster id, e.g. "tool-call-loop"',
  "",
  "Slugs / tool ids: [a-z0-9-]+ (lowercase kebab). Topics / keys / sections: free-form, trimmed."
].join("\n");
var KIND_EXPECTED_SUBJECTS = {
  "failure-mode": ["cluster"],
  "knowledge-gap": [
    "knowledge.wiki",
    "knowledge.claim",
    "knowledge.raw",
    "knowledge.stale",
    "tool-doc",
    "system-prompt",
    "memory",
    "websearch.outdated",
    "prior-run-summary"
  ],
  "knowledge-poisoning": [
    "knowledge.wiki",
    "knowledge.claim",
    "knowledge.raw",
    "tool-doc",
    "system-prompt",
    "memory",
    "websearch.outdated",
    "prior-run-summary"
  ],
  improvement: [
    "system-prompt",
    "tool-doc",
    "new-tool",
    "rag",
    "memory",
    "scaffolding",
    "output-schema",
    "knowledge.wiki",
    "knowledge.claim"
  ]
};
var FindingSubjectStringSchema = z.string().refine((s) => parseFindingSubject(s) !== null, {
  message: "subject does not match the finding-subject grammar"
});

// src/analyst/parse-tolerant.ts
function stripCodeFences(text) {
  const t = text.trim();
  const fence = /^```[a-zA-Z0-9]*\s*\n?([\s\S]*?)\n?```$/;
  const m = t.match(fence);
  return m ? m[1].trim() : t;
}
function dropTrailingCommas(s) {
  return s.replace(/,(\s*[}\]])/g, "$1");
}
function coerceJson(text) {
  const candidate = dropTrailingCommas(stripCodeFences(text));
  try {
    return JSON.parse(candidate);
  } catch {
    return void 0;
  }
}
function coerceToFindingRows(raw) {
  let value = raw;
  if (typeof value === "string") {
    const parsed = coerceJson(value);
    if (parsed === void 0) return [];
    value = parsed;
  }
  if (Array.isArray(value)) return value;
  if (value && typeof value === "object") {
    const inner = value.findings;
    if (Array.isArray(inner)) return inner;
    return [value];
  }
  return [];
}

// src/analyst/finding-signature.ts
import { z as z2 } from "zod";
var ANALYST_SEVERITIES = ["critical", "high", "medium", "low", "info"];
var RawAnalystFindingSchema = z2.object({
  severity: z2.enum(ANALYST_SEVERITIES),
  claim: z2.string().min(1).max(2e3),
  /**
   * Subject locus the finding is about. Validated at parse time
   * against the documented grammar (`finding-subject.ts`). Findings
   * with a malformed subject are rejected — they would have been
   * silently skipped by every downstream adapter, so failing loud at
   * parse time turns a hidden no-op into a kind-prompt audit signal.
   *
   * Optional because purely descriptive findings (no actionable
   * locus) are legitimate; they just don't route through the
   * KnowledgeAdapter / ImprovementAdapter.
   */
  subject: z2.string().max(400).refine((s) => parseFindingSubject(s) !== null, {
    message: "subject does not match the finding-subject grammar"
  }).optional(),
  evidence_uri: z2.string().min(1).max(2e3),
  evidence_excerpt: z2.string().max(2e3).optional(),
  confidence: z2.number().min(0).max(1),
  rationale: z2.string().max(4e3).optional(),
  recommended_action: z2.string().max(2e3).optional()
}).strict();
var RAW_FINDING_SCHEMA_PROMPT = `Each finding MUST be a JSON object with these fields:
  - severity: one of "critical" | "high" | "medium" | "low" | "info"
  - claim: one-sentence statement (max 2000 chars)
  - subject?: the routing locus this finding is about. It MUST be one of the exact subject forms listed in this kind's instructions above (e.g. \`system-prompt:<section>\`, \`agent-knowledge:wiki:<slug>\`, \`tool-doc:<tool>\`). A free phrase, a bare noun, or any form not in that list is REJECTED at parse time and the finding is discarded \u2014 omit subject entirely rather than guess a form.
  - evidence_uri: REQUIRED, never blank. Exactly one of "span://<trace_id>/<span_id>" (trace evidence), "artifact://<relative-path>" (files), "metric://<name>" (named scalars) \u2014 ALWAYS cite a real id surfaced by the tools. If you have no citable id, do not emit the finding.
  - evidence_excerpt?: short quote (<=2000 chars) from the cited span/artifact
  - confidence: number 0..1 \u2014 0.9+ when backed by exact quotes, 0.6-0.8 for inferred patterns, <0.5 for speculative
  - rationale?: one or two sentences explaining the reasoning
  - recommended_action?: concrete change phrased as an imperative ("Add ...", "Replace ...", "Stop ...") \u2014 omit when the finding is purely descriptive

Emit an empty array when the question has no findings to report. Do not fabricate evidence.`;
function parseRawFinding(row, log) {
  const result = RawAnalystFindingSchema.safeParse(row);
  if (result.success) return result.data;
  if (typeof row === "string") {
    const coerced = coerceJson(row);
    if (coerced !== void 0) {
      const retry = RawAnalystFindingSchema.safeParse(coerced);
      if (retry.success) return retry.data;
    }
  }
  log?.("finding rejected: schema failure", {
    issues: result.error.issues.map((i) => ({
      path: i.path.join("."),
      code: i.code,
      message: i.message
    }))
  });
  return null;
}

// src/analyst/structure-findings.ts
var SYSTEM = [
  "You convert a free-form trace-analysis report into a STRICT JSON array of findings.",
  "Output ONLY the JSON array \u2014 no prose, no code fences.",
  'Each element: {"severity":"critical|high|medium|low|info","claim":string,"evidence_uri":string,',
  '"subject"?:string,"rationale"?:string,"recommended_action"?:string,"confidence":number(0..1)}.',
  'evidence_uri cites the trace element the report referenced (e.g. "span://<trace>/<span>") or "report://summary".',
  "If the report asserts NO problems, output exactly []."
].join(" ");
function buildRows(raw, analystId, area) {
  const rows = coerceToFindingRows(raw);
  const out = [];
  for (const row of rows) {
    const normalized = row && typeof row === "object" && !Array.isArray(row) && !row.evidence_uri ? { ...row, evidence_uri: "report://summary" } : row;
    const parsed = parseRawFinding(normalized);
    if (!parsed) continue;
    out.push(
      makeFinding({
        analyst_id: analystId,
        area,
        subject: parsed.subject,
        claim: parsed.claim,
        rationale: parsed.rationale,
        severity: parsed.severity,
        confidence: parsed.confidence,
        evidence_refs: [
          {
            kind: parsed.evidence_uri.startsWith("span://") ? "span" : "artifact",
            uri: parsed.evidence_uri,
            excerpt: parsed.evidence_excerpt
          }
        ],
        recommended_action: parsed.recommended_action
      })
    );
  }
  return out;
}
async function structureFindings(opts) {
  const maxReasks = opts.maxReasks ?? 1;
  const llm = { baseUrl: opts.baseUrl, apiKey: opts.apiKey, fetch: opts.fetchImpl };
  let user = `TRACE-ANALYSIS REPORT:
${opts.report}

Return the findings JSON array.`;
  for (let attempt = 0; attempt <= maxReasks; attempt++) {
    const res = await callLlm(
      {
        model: opts.model,
        messages: [
          { role: "system", content: SYSTEM },
          { role: "user", content: user }
        ]
      },
      llm
    );
    const text = res.content.trim();
    const findings = buildRows(text, opts.analystId, opts.area);
    if (findings.length > 0) return { findings, outcome: "ok" };
    if (opts.report.trim().length < 200) return { findings: [], outcome: "ok" };
    user = `${user}

That produced no valid findings. The report DOES describe issues \u2014 re-extract them as the strict JSON array described in the system prompt. Output ONLY the array.`;
  }
  return { findings: [], outcome: "extraction_failed" };
}

// src/analyst/kind-factory.ts
import { AxJSRuntime, agent } from "@ax-llm/ax";
function createTraceAnalystKind(spec, opts) {
  const version = opts.versionSuffix ? `${spec.version}+${opts.versionSuffix}` : spec.version;
  return {
    id: spec.id,
    description: spec.description,
    inputKind: "trace-store",
    cost: spec.cost,
    version,
    async analyze(store, ctx) {
      const tools = spec.buildTools(store);
      const maxDepth = spec.recursion?.maxDepth ?? 0;
      const maxParallel = spec.recursion?.maxParallelSubagents ?? 2;
      const priorContext = renderPriorFindings(ctx.priorFindings);
      const actorDescription = spec.actorDescription.trim() + priorContext + "\n\n" + RAW_FINDING_SCHEMA_PROMPT + "\n\nFirst write `report`: a concise free-form prose diagnosis of what the traces show \u2014 what succeeded, what was suboptimal or failed \u2014 with concrete trace ids and numbers. THEN return the structured `findings` array (it MAY be empty when there is nothing to report). Use `final(...)` with the `{ report, findings }` payload when you are done.";
      const ax = agent(
        "question:string -> report:string, findings:json[]",
        {
          agentIdentity: {
            name: spec.id,
            description: spec.description
          },
          contextFields: ["question"],
          runtime: new AxJSRuntime({
            permissions: [],
            blockDynamicImport: true,
            allowedModules: [],
            freezeIntrinsics: true,
            blockShadowRealm: true,
            preventGlobalThisExtensions: false
          }),
          mode: maxDepth > 0 ? "advanced" : "simple",
          recursionOptions: maxDepth > 0 ? { maxDepth } : void 0,
          maxTurns: spec.maxTurns ?? 12,
          maxRuntimeChars: spec.maxRuntimeChars ?? 6e3,
          maxBatchedLlmQueryConcurrency: maxParallel,
          promptLevel: "detailed",
          // Trace analysis depends on exact prior tool results and runtime variables.
          contextPolicy: { preset: "full", budget: "balanced" },
          functions: { local: tools },
          actorOptions: {
            description: actorDescription,
            ...opts.model ? { model: opts.model } : {},
            showThoughts: false,
            thinkingTokenBudget: "none"
          },
          responderOptions: {
            description: spec.responderDescription ?? "Pass through the actor's `report` prose verbatim, and format the `findings` array exactly as the actor produced it. Do not add, drop, or summarize entries.",
            ...opts.model ? { model: opts.model } : {},
            showThoughts: false
          },
          bubbleErrors: [TraceFileMissingError]
        }
      );
      ctx.log?.(`analyst.kind ${spec.id} forward`, {
        max_depth: maxDepth,
        tool_count: tools.length,
        tags: ctx.tags
      });
      const result = await ax.forward(opts.ai, { question: deriveQuestion(ctx, spec) });
      const expectedSubjects = KIND_EXPECTED_SUBJECTS[spec.id];
      const out = [];
      const rawRows = Array.isArray(result.findings) ? result.findings : [];
      let rejectedWrongKind = 0;
      for (const row of rawRows) {
        const parsed = parseRawFinding(row, ctx.log);
        if (!parsed) continue;
        if (expectedSubjects && parsed.subject !== void 0) {
          const parsedSubject = parseFindingSubject(parsed.subject);
          if (parsedSubject === null) {
            ctx.log?.("finding rejected: subject failed to parse", {
              kind: spec.id,
              subject: parsed.subject
            });
            rejectedWrongKind += 1;
            continue;
          }
          if (!expectedSubjects.includes(parsedSubject.kind)) {
            ctx.log?.("finding rejected: subject variant not allowed for this kind", {
              kind: spec.id,
              subject_kind: parsedSubject.kind,
              subject: parsed.subject,
              allowed: expectedSubjects
            });
            rejectedWrongKind += 1;
            continue;
          }
        }
        const postProcessed = spec.postProcess?.(parsed, ctx) ?? parsed;
        if (!postProcessed) continue;
        out.push(toAnalystFinding(spec, postProcessed));
      }
      ctx.log?.(`analyst.kind ${spec.id} done`, {
        emitted: rawRows.length,
        accepted: out.length,
        rejected_wrong_subject: rejectedWrongKind
      });
      const report = typeof result.report === "string" ? result.report : "";
      if (out.length === 0 && report.trim().length >= 200) {
        if (opts.recovery) {
          const recovered = await structureFindings({
            report,
            analystId: spec.id,
            area: spec.area,
            model: opts.recovery.model ?? opts.model ?? "",
            baseUrl: opts.recovery.baseUrl,
            apiKey: opts.recovery.apiKey,
            fetchImpl: opts.recovery.fetchImpl
          });
          out.push(...recovered.findings);
          ctx.log?.(`analyst.kind ${spec.id} recovery`, {
            outcome: recovered.outcome,
            recovered: recovered.findings.length
          });
        }
        if (out.length === 0) {
          out.push(
            makeFinding({
              analyst_id: spec.id,
              area: spec.area,
              claim: "Analyst produced a diagnosis but no structured findings \u2014 see report.",
              rationale: report.slice(0, 1500),
              severity: "info",
              confidence: 0.3,
              evidence_refs: [
                { kind: "artifact", uri: "report://summary", excerpt: report.slice(0, 2e3) }
              ],
              metadata: { outcome: "extraction_failed" }
            })
          );
        }
      }
      return out;
    }
  };
}
function deriveQuestion(ctx, spec) {
  const focus = ctx.tags?.focus?.trim();
  const task = `Analyze this trace dataset with the available tools and report ${spec.area} findings. ${spec.description}`;
  return focus ? `${task} Focus: ${focus}.` : task;
}
function toAnalystFinding(spec, raw) {
  return makeFinding({
    analyst_id: spec.id,
    area: spec.area,
    subject: raw.subject,
    claim: raw.claim,
    rationale: raw.rationale,
    severity: raw.severity,
    confidence: raw.confidence,
    evidence_refs: [
      {
        kind: evidenceKindFromUri(raw.evidence_uri),
        uri: raw.evidence_uri,
        excerpt: raw.evidence_excerpt
      }
    ],
    recommended_action: raw.recommended_action,
    metadata: { kind_version: spec.version }
  });
}
function evidenceKindFromUri(uri) {
  if (uri.startsWith("span://")) return "span";
  if (uri.startsWith("artifact://")) return "artifact";
  if (uri.startsWith("metric://")) return "metric";
  if (uri.startsWith("event://")) return "event";
  if (uri.startsWith("finding://")) return "finding";
  return "artifact";
}
function renderPriorFindings(prior) {
  if (!prior || prior.length === 0) return "";
  const MAX_ROWS = 40;
  const rows = prior.slice(0, MAX_ROWS).map((f) => {
    const subject = f.subject ? ` [${f.subject}]` : "";
    return `  - id=${f.finding_id} ${f.severity}${subject} ${truncateForContext(f.claim, 160)}`;
  });
  const overflow = prior.length > MAX_ROWS ? `
  ... +${prior.length - MAX_ROWS} more prior findings (older history truncated)` : "";
  return [
    "",
    "",
    "PRIOR FINDINGS (from a previous run on related data):",
    "When the work you do now matches a row below, REUSE the `finding_id` (pass it as `id_basis`) so the cross-run diff stays stable.",
    "A finding that reappears with no remediation evidence SHOULD raise its `confidence` and may justify a higher `severity`.",
    ...rows,
    overflow
  ].filter(Boolean).join("\n");
}
function truncateForContext(s, max) {
  if (s.length <= max) return s;
  return `${s.slice(0, max - 1).trimEnd()}\u2026`;
}

// src/analyst/tool-groups.ts
var TOOL_NAMES_BY_GROUP = {
  all: /* @__PURE__ */ new Set(),
  discovery: /* @__PURE__ */ new Set(["getDatasetOverview", "queryTraces", "countTraces"]),
  discoveryAndRead: /* @__PURE__ */ new Set([
    "getDatasetOverview",
    "queryTraces",
    "countTraces",
    "viewTrace",
    "viewSpans"
  ]),
  discoveryAndSearch: /* @__PURE__ */ new Set([
    "getDatasetOverview",
    "queryTraces",
    "countTraces",
    "searchTrace",
    "searchSpan"
  ]),
  targeted: /* @__PURE__ */ new Set(["getDatasetOverview", "queryTraces", "viewSpans", "searchSpan"])
};
function buildTraceToolsForGroup(group, store) {
  const all = buildTraceAnalystTools({ store });
  if (group === "all") return all;
  const allow = TOOL_NAMES_BY_GROUP[group];
  if (!allow) throw new Error(`unknown trace tool group: ${group}`);
  return all.filter((tool) => allow.has(tool.name));
}

// src/analyst/kinds/failure-mode.ts
var ACTOR_PROMPT = `You are a failure-mode classifier for an OTLP trace dataset. Your job is to identify the **distinct ways agents failed** in this dataset, not to grade individual runs.

DISCOVERY \u2192 CLUSTER \u2192 CITE protocol:

1. Call \`traces.getDatasetOverview({})\` first. Use \`has_errors\`, \`models\`, \`agent_names\`, \`tools\`, and \`sample_trace_ids\` to size the failure surface.
2. Use \`traces.queryTraces({ filters: { has_errors: true }, limit })\` to pull error-bearing traces. Combine with \`traces.countTraces\` to see what fraction of the dataset failed.
3. For each candidate failure cluster, use \`traces.searchTrace\` with regex like \`STATUS_CODE_ERROR\`, \`MaxTurnsExceeded\`, \`assertion\`, \`unauthorized\`, \`timeout\`, \`429\`, \`5\\d\\d\`, the agent's specific error strings, or the names of its tools. Pull one or two representative traces per cluster, **not all** of them.
4. **Cluster, do not enumerate.** Two failures with the same root cause should be ONE finding citing both traces, not two findings. The point of this analyst is to compress N runs into K modes.
5. For each cluster you can defend with evidence, emit ONE finding with:
   - \`area\` = "failure-mode"
   - \`subject\` = a short label for the cluster ("tool-call-loop", "auth-revoked-mid-run", "agent-asked-clarification-too-late", ...)
   - \`claim\` = one sentence stating the mode
   - \`severity\` = "critical" when it blocks the run, "high" when the run finished degraded, "medium" when it slowed convergence
   - \`evidence_uri\` = \`span://<trace_id>/<span_id>\` of the most representative span
   - \`evidence_excerpt\` = the exact quote (e.g. error message, stuck tool call payload, contradictory turn output)
   - \`confidence\` = 0.85+ when multiple traces show the same shape; 0.6-0.8 for a single-trace inference; <0.5 for speculative.
   - \`recommended_action\` = imperative-phrased fix idea (kept short \u2014 the improvement-analyst will expand on these)

If the dataset has no failures, return an empty findings array \u2014 do NOT pad with low-confidence speculation.

**Delegate aggressively.** The recursion budget is there to be used:
- After your first \`getDatasetOverview\` + \`queryTraces\` calls, you should have 3-6 candidate failure clusters in mind. Spawn one \`llmQuery\` per cluster in a single batch \u2014 they investigate in parallel.
- A sub-investigator that finds its cluster is actually two distinct modes should split again at its own level. Recursion is meant to discover sub-modes, not to do trivial drilling that the parent could do in-line.
- Pass narrow context to each subagent: { question: 'investigate the auth-revoked-mid-run cluster', context: { trace_ids: ['abc', 'def'], suspected_root_cause: 'token refresh skipped on idle sessions' } }. Subagents need enough context to skip re-discovery but not the whole conversation.
- Each subagent returns its findings as JSON; the parent merges them. Do NOT have subagents call \`final()\` \u2014 they return their findings list to you, and you call \`final()\` once at the top.

OBSERVABILITY rules:
- Each non-final turn must emit at least one \`console.log\` for evidence.
- Reuse runtime variables across turns; don't recompute.
- Call \`final({ findings: [...] })\` exactly once, after you've gathered evidence for every cluster you intend to report.`;
var FAILURE_MODE_KIND_SPEC = {
  id: "failure-mode",
  description: "Clusters trace-dataset failures into distinct failure modes with cited evidence and a short recommended action.",
  area: "failure-mode",
  version: "1.0.0",
  actorDescription: ACTOR_PROMPT,
  buildTools: (store) => buildTraceToolsForGroup("all", store),
  recursion: { maxDepth: 3, maxParallelSubagents: 4 },
  maxTurns: 24,
  cost: { kind: "llm" }
};

// src/analyst/kinds/improvement.ts
var ACTOR_PROMPT2 = `You are a recursive-self-improvement analyst. Your job is to propose **concrete, locus-named edits** the agent's runtime should adopt to fix the failure modes, knowledge gaps, and poisonings present in this dataset.

Upstream analysts have already classified the problems. Your job is to convert each problem into a *change to make* and grade its expected leverage. Each finding is one proposed edit.

DISCOVERY \u2192 CANDIDATE-FIXES \u2192 COMPETE \u2192 CITE protocol:

1. \`traces.getDatasetOverview({})\` first. Note the agents, tools, and any system-prompt fingerprints (look for the prompt text echoed in early spans).
2. For each high-severity failure pattern, generate 2-3 candidate fixes. Real candidate axes:
   - **System-prompt edit** \u2014 add an instruction, remove a misleading one, restructure precedence
   - **Tool description edit** \u2014 rewrite a tool's description so the agent picks it correctly / passes valid args
   - **New tool** \u2014 add a tool the agent kept emulating in code
   - **RAG ingestion** \u2014 add a document or correct a stale one
   - **Memory invalidation** \u2014 clear cached prior-run decisions that no longer apply
   - **Scaffolding** \u2014 add a precondition check, a retry policy, a turn budget, a verification step
   - **Output schema** \u2014 narrow the agent's output to forbid the failure shape
3. **Compete candidate fixes via subagents.** For each failure cluster, spawn one \`llmQuery\` per candidate-fix axis you want to evaluate. Each subagent's job: simulate the fix on the cited traces and report (i) likely effect, (ii) side effects, (iii) implementation cost as small/medium/large. Pass the cluster's failing trace_ids and the candidate axis as context.
4. After subagents return, **pick the winning candidate per cluster** based on (effect / cost) and emit ONE finding. Discard the losing candidates \u2014 the output is the recommendation, not the candidate set.
5. **Cross-reference upstream findings.** If a finding cites a prior failure-mode or knowledge-gap finding, use \`evidence_uri = "finding://<prior-finding-id>"\` (the registry supports this kind). This builds the dependency graph that lets the dashboard show "fix #X resolves failure modes A, B, C."

For each winning recommendation, emit ONE finding with:
- \`area\` = "improvement"
- \`subject\` = the locus to edit: \`system-prompt:<section>\`, \`tool-doc:<tool-name>\`, \`new-tool:<proposed-name>\`, \`rag:<corpus>:<doc-id>\`, \`memory:<key>\`, \`scaffolding:<concern>\`, \`output-schema:<field>\`
- \`claim\` = one sentence stating the edit ("Add a precondition check to refuse tool X calls without arg Y")
- \`severity\` = leverage rating: "critical" when fix resolves a critical failure mode; "high" when it resolves a high; "medium" when it's a quality-of-life win; "info" when it's a cleanup with no behavioral effect
- \`evidence_uri\` = the failure-mode finding id this fix targets (\`finding://<id>\`) when it exists; else the most representative span
- \`evidence_excerpt\` = a fragment showing the problem the fix targets
- \`confidence\` = 0.85+ when the fix is mechanical and the failure mode is well-evidenced; 0.6-0.8 when the fix requires judgment; <0.5 for speculative
- \`rationale\` = why this candidate beat its alternatives (2 sentences max)
- \`recommended_action\` = the **literal edit**, phrased as a diff or a quoted replacement: "Replace section X with: '...'" or "Add tool with description: '...'" or "Set retry policy to max_attempts=3 with exponential backoff"

If no upstream failure findings exist in this run, derive your own from the trace dataset using the failure-mode protocol inline (\`searchTrace\` for STATUS_CODE_ERROR / MaxTurnsExceeded / etc.). But prefer to consume upstream findings when present \u2014 the kinds are designed to chain.

Do NOT propose a fix you cannot defend with evidence. "Tighten the prompt" is not a finding; "Add 'When the user asks for X, always Y' to the system prompt section "request-classification"" is.

OBSERVABILITY rules:
- Each non-final turn must emit at least one \`console.log\` for evidence.
- Call \`final({ findings: [...] })\` exactly once at the top level.`;
var IMPROVEMENT_KIND_SPEC = {
  id: "improvement",
  description: "Converts upstream failure / gap / poisoning findings into concrete locus-named edits (prompt, tool-doc, RAG, scaffolding) with leverage grades.",
  area: "improvement",
  version: "1.0.0",
  actorDescription: ACTOR_PROMPT2,
  buildTools: (store) => buildTraceToolsForGroup("all", store),
  recursion: { maxDepth: 3, maxParallelSubagents: 4 },
  maxTurns: 30,
  maxRuntimeChars: 12e3,
  cost: { kind: "llm" }
};

// src/analyst/kinds/knowledge-gap.ts
var ACTOR_PROMPT3 = `You are a knowledge-gap analyst for an OTLP trace dataset. Your job is to identify the **specific pieces of information the agent lacked, or that were stale**, that caused poor decisions.

The agent under analysis maintains a curated knowledge base via \`@tangle-network/agent-knowledge\` \u2014 a wiki of \`KnowledgePage\`s with raw source anchors, claims, and relations. The primary expected store of agent-knowable facts IS that wiki. A "knowledge gap" is anything the agent had to discover or guess at run-time that the wiki should have held \u2014 or an outdated/contradictory fact the agent picked up from a non-wiki source.

DISCOVERY \u2192 ATTRIBUTE-TO-LAYER \u2192 CITE protocol:

1. \`traces.getDatasetOverview({})\` first. Note which agents, tools, and models appear.
2. Pull traces where the agent shows gap signals. The strongest signals are:
   - Self-correction turns ("I assumed X but\u2026", "let me re-check", "actually,")
   - Clarifying-question turns where the agent asked the user something the runtime should have surfaced
   - Repeated retrieval / lookup calls for the same artifact with slightly varied queries
   - Tool errors that name a missing argument or unknown resource
   - Web-search calls returning pages dated before a known cutoff for content that changes (versioned APIs, schemas, policies)
   - Agent quoting a tool's docs / system prompt incorrectly because the actual text was insufficient
   - Fabricated identifiers that don't appear in dataset \`sample_trace_ids\`
   Use \`traces.searchTrace\` with patterns like \`I (don.?t|do not) know\`, \`assumed\`, \`unclear\`, \`could you (clarify|tell me|provide)\`, \`not found\`, \`undefined\`, \`unknown\`, \`null\`, dates older than the analysis window, or the agent's specific clarification phrases.
3. For each gap, identify the **layer of the runtime that should have prevented it**. The locus is the value of \`subject\` on the finding. Use one of:
   - \`agent-knowledge:wiki:<page-slug>\` \u2014 the wiki page that should exist but doesn't, or exists but lacks the claim
   - \`agent-knowledge:wiki:<page-slug>#<heading>\` \u2014 wiki page exists but a specific section is missing
   - \`agent-knowledge:claim:<topic>\` \u2014 a specific claim/relation triple that should be in the wiki
   - \`agent-knowledge:raw:<source-id>\` \u2014 raw source captured but never lifted into a curated page
   - \`agent-knowledge:stale:<page-slug>\` \u2014 wiki page exists but contradicts ground-truth evidence in this trace (the wiki itself drifted)
   - \`websearch:outdated:<topic>\` \u2014 agent relied on a web result that was stale; wiki should have superseded it
   - \`tool-doc:<tool-name>:<aspect>\` \u2014 tool description missed a behavior aspect (return shape, failure modes, side effects)
   - \`system-prompt:<section>\` \u2014 system prompt should have stated the rule directly
   - \`memory:<key>\` \u2014 prior-run memory should have surfaced an earlier decision
4. For each gap you can defend with evidence, emit ONE finding with:
   - \`area\` = "knowledge-gap"
   - \`subject\` = the locus string from the list above
   - \`claim\` = a sentence naming the missing or stale knowledge ("wiki has no page on invoice line-item shape, agent had to re-derive it from raw spans")
   - \`severity\` = "high" when the gap caused a failure or a clarifying question; "medium" when it caused unnecessary turns; "low" when it caused minor inefficiency
   - \`evidence_uri\` = \`span://<trace_id>/<span_id>\` of the moment the gap surfaced (the question, the self-correction, the retrieval miss, the stale web result)
   - \`evidence_excerpt\` = exact quote where the agent showed the gap
   - \`confidence\` = 0.85+ when the agent itself articulated the gap; 0.6-0.8 when inferred from behavior
   - \`recommended_action\` = phrased as a wiki edit when the locus is \`agent-knowledge:*\` ("Create wiki page \`invoice-line-items\` with claims: ..."), or as a prompt/tool-doc edit otherwise

**Delegate per layer.** After your first scan, you should have candidates spread across \`agent-knowledge:*\`, \`websearch:outdated\`, \`tool-doc:*\`, \`system-prompt:*\`, and \`memory:*\`. Spawn one \`llmQuery\` per layer in parallel \u2014 each subagent runs a focused detection (e.g. the \`agent-knowledge\` subagent looks for both missing-pages AND stale-pages; the \`websearch\` subagent looks specifically for date staleness signals; the \`tool-doc\` subagent looks for tool-call argument errors a fuller description would have prevented). Subagents return findings; you merge and emit one \`final({ findings })\` at the top.

Do NOT report a gap that the agent later recovered from cleanly within the same turn \u2014 that's resilience, not a gap. Cite the *non-recovery* version when both exist.

OBSERVABILITY rules:
- Each non-final turn must emit at least one \`console.log\` for evidence.
- Call \`final({ findings: [...] })\` exactly once at the top level.`;
var KNOWLEDGE_GAP_KIND_SPEC = {
  id: "knowledge-gap",
  description: "Identifies missing or stale pieces of knowledge \u2014 primarily against the agent-knowledge wiki \u2014 and attributes each to the runtime layer (wiki page, claim, raw source, websearch, tool-doc, system-prompt, memory) that should have held it.",
  area: "knowledge-gap",
  version: "1.0.0",
  actorDescription: ACTOR_PROMPT3,
  buildTools: (store) => buildTraceToolsForGroup("discoveryAndSearch", store),
  recursion: { maxDepth: 2, maxParallelSubagents: 4 },
  maxTurns: 18,
  cost: { kind: "llm" }
};

// src/analyst/kinds/knowledge-poisoning.ts
var ACTOR_PROMPT4 = `You are a knowledge-poisoning analyst for an OTLP trace dataset. Your job is to identify cases where the agent **confidently used wrong information** \u2014 not where it lacked information (that's the knowledge-gap analyst).

DISCOVERY \u2192 DUAL-VERIFY \u2192 CITE protocol:

1. \`traces.getDatasetOverview({})\` first. Identify the agents, models, and tools.
2. Pull traces where the agent's confident action was later contradicted. Strongest signals:
   - Agent stated a fact in one span; a later span surfaced contradictory evidence; the agent then proceeded anyway or fabricated reconciliation.
   - Tool call with stale arguments (an id that no longer exists, an API shape that changed).
   - Agent cited an \`agent-knowledge\` wiki page or claim whose content contradicts the trace's own evidence \u2014 the wiki itself drifted.
   - Web-search result the agent cited that returned an outdated page; agent treated it as canonical.
   - System-prompt instruction the agent followed that ground-truth evidence in the trace contradicts (e.g. prompt says "use endpoint A"; tool reply says "endpoint A deprecated, use B").
   - Repeated wrong-shape parsing despite the tool's actual output proving the shape.
3. Use \`traces.searchTrace\` with regex on phrases like \`actually\`, \`turns out\`, \`previously assumed\`, \`old version\`, \`deprecated\`, \`updated to\`, \`now uses\`, or specific entity names you suspect have changed.
4. For each candidate poisoning, **DUAL-VERIFY**:
   - Confirm the agent actually acted on the false belief (cite the span where it did)
   - Confirm the belief is actually false in this trace's own evidence (cite the span that contradicts it)
   Only emit a finding when both halves are nailed down. If you can only nail one, drop it \u2014 single-evidence poisoning findings are too speculative to be useful.

**Delegate the dual-verify.** Use the recursion budget so each candidate poisoning gets one subagent investigating "did the agent act?" and one investigating "is the belief false?". After your first scan, fire off N parallel \`llmQuery\` pairs (one cluster per pair). Subagents return their findings; you accept only the ones where BOTH halves of the pair were confirmed.

For each confirmed poisoning, emit ONE finding with:
- \`area\` = "knowledge-poisoning"
- \`subject\` = the source of the false belief, one of: \`agent-knowledge:wiki:<page-slug>\` (wiki page contradicts current ground truth), \`agent-knowledge:claim:<topic>\` (a specific claim/relation went stale), \`agent-knowledge:raw:<source-id>\` (the raw source is outdated and the wiki inherited the drift), \`websearch:outdated:<url-or-topic>\`, \`tool-doc:<tool>\`, \`system-prompt:<section>\`, \`memory:<key>\`, \`prior-run-summary:<topic>\`
- \`claim\` = one sentence: "agent believed X (from source S); evidence in trace shows X is false"
- \`severity\` = "critical" when poisoning caused a wrong user-visible action; "high" when caught internally but wasted significant work; "medium" for inefficiency only
- \`evidence_uri\` = \`span://<trace_id>/<span_id>\` of the action span (the moment the agent acted on the false belief)
- \`evidence_excerpt\` = exact quote of the confident-but-wrong claim or action
- \`confidence\` = 0.85+ when both halves are exact-quote backed; 0.6-0.8 when one half is inferred
- \`recommended_action\` = where the source should be updated and how ("Update wiki page \`X\` claim \`Y\` to '...'", "Invalidate raw source \`Z\` and re-curate", "Replace system-prompt section X with 'tool foo now returns Y'")

Do NOT report a finding if the agent caught and corrected the false belief in the same turn \u2014 that's the system working. Reserve poisoning for cases where the false belief shaped downstream action.

OBSERVABILITY rules:
- Each non-final turn must emit at least one \`console.log\` for evidence.
- Call \`final({ findings: [...] })\` exactly once at the top level.`;
var KNOWLEDGE_POISONING_KIND_SPEC = {
  id: "knowledge-poisoning",
  description: "Identifies confident-but-wrong actions caused by stale memory, contradicting RAG, deprecated tool docs, or outdated system-prompt instructions.",
  area: "knowledge-poisoning",
  version: "1.0.0",
  actorDescription: ACTOR_PROMPT4,
  buildTools: (store) => buildTraceToolsForGroup("all", store),
  recursion: { maxDepth: 2, maxParallelSubagents: 4 },
  maxTurns: 20,
  cost: { kind: "llm" }
};

// src/analyst/kinds/index.ts
var DEFAULT_TRACE_ANALYST_KINDS = [
  FAILURE_MODE_KIND_SPEC,
  KNOWLEDGE_GAP_KIND_SPEC,
  KNOWLEDGE_POISONING_KIND_SPEC,
  IMPROVEMENT_KIND_SPEC
];

// src/analyst/registry.ts
import { randomUUID } from "crypto";
var AnalystRegistry = class {
  analysts = /* @__PURE__ */ new Map();
  options;
  constructor(options = {}) {
    this.options = options;
  }
  register(analyst) {
    if (!analyst.id) throw new Error("AnalystRegistry.register: analyst.id is required");
    if (this.analysts.has(analyst.id)) {
      throw new Error(`AnalystRegistry.register: duplicate analyst id "${analyst.id}"`);
    }
    if (!analyst.version) {
      throw new Error(`AnalystRegistry.register: analyst "${analyst.id}" must declare a version`);
    }
    this.analysts.set(analyst.id, analyst);
  }
  list() {
    return Array.from(this.analysts.values()).map((a) => ({
      id: a.id,
      description: a.description,
      version: a.version,
      cost: a.cost
    }));
  }
  async run(runId, inputs, runOpts = {}) {
    for await (const ev of this.runStream(runId, inputs, runOpts)) {
      if (ev.type === "run-completed") return ev.result;
    }
    throw new Error("AnalystRegistry.run: stream completed without run-completed event");
  }
  /**
   * Streaming counterpart to `run()`. Emits `AnalystRunEvent` values
   * in real time — `run-started`, then per-analyst `skipped` /
   * `started` / `completed`, then a terminal `run-completed` whose
   * payload is the full `AnalystRunResult`. UIs use this to render
   * progress; persistence consumers use `run()` and read the result.
   *
   * Hooks (`onBeforeAnalyze` / `onAfterAnalyze` / `onError` /
   * `onComplete`) fire as before — streaming is additive, not a hook
   * replacement.
   */
  async *runStream(runId, inputs, runOpts = {}) {
    const correlationId = `ar_${randomUUID().slice(0, 12)}`;
    const log = this.options.log ?? (() => {
    });
    const hooks = this.options.hooks ?? {};
    const startedAt = (/* @__PURE__ */ new Date()).toISOString();
    const started = Date.now();
    const deadlineMs = runOpts.timeoutMs ? started + runOpts.timeoutMs : void 0;
    const selected = this.selectAnalysts(runOpts);
    const budget = runOpts.budget ?? this.options.defaultBudget;
    yield {
      type: "run-started",
      run_id: runId,
      correlation_id: correlationId,
      started_at: startedAt,
      analyst_ids: selected.map((a) => a.id)
    };
    const summaries = [];
    const allFindings = [];
    let totalCost = 0;
    let remainingUsd = budget?.totalUsd;
    const runnableCount = selected.filter(
      (a) => this.routeInput(a, inputs).kind !== "missing"
    ).length;
    for (const analyst of selected) {
      const t0 = Date.now();
      const input = this.routeInput(analyst, inputs);
      if (input.kind === "missing") {
        const summary = {
          analyst_id: analyst.id,
          status: "skipped",
          reason: `missing input of kind '${analyst.inputKind}'`,
          findings_count: 0,
          latency_ms: 0,
          cost_usd: 0
        };
        summaries.push(summary);
        log(`[analyst] skip ${analyst.id} \u2014 missing input`, { runId, kind: analyst.inputKind });
        await hooks.onAfterAnalyze?.({ analyst, summary, findings: [], runId });
        yield { type: "analyst-skipped", summary };
        continue;
      }
      const perBudget = allocateBudget(budget, {
        analyst,
        remainingUsd,
        runningCount: runnableCount
      });
      const ctx = {
        runId,
        correlationId,
        deadlineMs,
        budgetUsd: perBudget,
        chat: this.options.chat,
        tags: runOpts.tags,
        log: (msg, fields) => log(`[${analyst.id}] ${msg}`, { runId, correlationId, ...fields }),
        signal: runOpts.signal,
        priorFindings: selectPriorFindings(runOpts.priorFindings, analyst.id)
      };
      await hooks.onBeforeAnalyze?.({ analyst, ctx, runId });
      yield {
        type: "analyst-started",
        analyst_id: analyst.id,
        started_at: new Date(t0).toISOString()
      };
      try {
        const findings = await analyst.analyze(input.value, ctx);
        const latency = Date.now() - t0;
        const cost = sumFindingCost(findings);
        totalCost += cost;
        if (typeof remainingUsd === "number") remainingUsd = Math.max(0, remainingUsd - cost);
        allFindings.push(...findings);
        const summary = {
          analyst_id: analyst.id,
          status: "ok",
          findings_count: findings.length,
          latency_ms: latency,
          cost_usd: cost
        };
        summaries.push(summary);
        log(`[analyst] ok ${analyst.id}`, {
          runId,
          findings: findings.length,
          latency_ms: latency,
          cost_usd: cost
        });
        await hooks.onAfterAnalyze?.({ analyst, summary, findings, runId });
        yield { type: "analyst-completed", summary, findings };
      } catch (err) {
        const latency = Date.now() - t0;
        const e = err instanceof Error ? err : new Error(String(err));
        const hookFindings = await hooks.onError?.({ analyst, error: e, runId }) ?? [];
        if (hookFindings.length) allFindings.push(...hookFindings);
        const summary = {
          analyst_id: analyst.id,
          status: "failed",
          findings_count: hookFindings.length,
          latency_ms: latency,
          cost_usd: 0,
          error: { class: e.constructor.name, message: e.message }
        };
        summaries.push(summary);
        log(`[analyst] FAIL ${analyst.id}`, {
          runId,
          error_class: e.constructor.name,
          error: e.message
        });
        await hooks.onAfterAnalyze?.({ analyst, summary, findings: hookFindings, runId });
        yield { type: "analyst-completed", summary, findings: hookFindings };
      }
    }
    const result = {
      run_id: runId,
      correlation_id: correlationId,
      started_at: startedAt,
      ended_at: (/* @__PURE__ */ new Date()).toISOString(),
      findings: allFindings,
      per_analyst: summaries,
      total_cost_usd: totalCost
    };
    await hooks.onComplete?.({ result });
    yield { type: "run-completed", result };
  }
  selectAnalysts(opts) {
    let candidates = Array.from(this.analysts.values());
    if (opts.only?.length) {
      const only = new Set(opts.only);
      candidates = candidates.filter((a) => only.has(a.id));
    }
    if (opts.skip?.length) {
      const skip = new Set(opts.skip);
      candidates = candidates.filter((a) => !skip.has(a.id));
    }
    return candidates;
  }
  routeInput(analyst, inputs) {
    switch (analyst.inputKind) {
      case "trace-store":
        return inputs.traceStore ? { kind: "present", value: inputs.traceStore } : { kind: "missing" };
      case "artifact-dir":
        return inputs.artifactDir ? { kind: "present", value: inputs.artifactDir } : { kind: "missing" };
      case "run-record":
        return inputs.runRecord ? { kind: "present", value: inputs.runRecord } : { kind: "missing" };
      case "judge-input":
        return inputs.judgeInput ? { kind: "present", value: inputs.judgeInput } : { kind: "missing" };
      case "custom": {
        const v = inputs.custom?.[analyst.id];
        return v !== void 0 ? { kind: "present", value: v } : { kind: "missing" };
      }
    }
  }
};
function allocateBudget(policy, args) {
  if (!policy) return void 0;
  if (policy.allocate) {
    return policy.allocate({
      analyst: args.analyst,
      totalUsd: policy.totalUsd,
      remainingUsd: args.remainingUsd,
      runningCount: args.runningCount
    });
  }
  if (policy.totalUsd == null) return void 0;
  if (policy.weights) {
    const w = policy.weights[args.analyst.id] ?? 1;
    const totalWeight = Math.max(1, args.runningCount);
    return policy.totalUsd * w / totalWeight;
  }
  return policy.totalUsd / Math.max(1, args.runningCount);
}
function sumFindingCost(findings) {
  let sum = 0;
  for (const f of findings) {
    const c = f.metadata?.cost_usd;
    if (typeof c === "number" && Number.isFinite(c)) sum += c;
  }
  return sum;
}
function selectPriorFindings(source, analystId) {
  if (!source) return void 0;
  if (Array.isArray(source)) {
    const own2 = source.filter((f) => f.analyst_id === analystId);
    return own2.length > 0 ? own2 : void 0;
  }
  const record = source;
  const own = record[analystId] ?? [];
  const wildcard = record["*"] ?? [];
  const merged = [...own, ...wildcard];
  return merged.length > 0 ? merged : void 0;
}

export {
  FINDING_SUBJECT_KINDS,
  parseFindingSubject,
  renderFindingSubject,
  FINDING_SUBJECT_GRAMMAR_PROMPT,
  KIND_EXPECTED_SUBJECTS,
  FindingSubjectStringSchema,
  stripCodeFences,
  coerceJson,
  coerceToFindingRows,
  ANALYST_SEVERITIES,
  RawAnalystFindingSchema,
  RAW_FINDING_SCHEMA_PROMPT,
  parseRawFinding,
  structureFindings,
  createTraceAnalystKind,
  renderPriorFindings,
  buildTraceToolsForGroup,
  FAILURE_MODE_KIND_SPEC,
  IMPROVEMENT_KIND_SPEC,
  KNOWLEDGE_GAP_KIND_SPEC,
  KNOWLEDGE_POISONING_KIND_SPEC,
  DEFAULT_TRACE_ANALYST_KINDS,
  AnalystRegistry
};
//# sourceMappingURL=chunk-S4SYLDFX.js.map