import {
  FindingsStore,
  RunCritic,
  SEMANTIC_CONCEPT_JUDGE_VERSION,
  SKILL_USAGE_ANALYST,
  SkillUsageAnalyst,
  buildSkillUsageReport,
  defaultIsMaterial,
  diffFindings,
  emitSkillUsageFindings,
  runSemanticConceptJudge
} from "../chunk-ULW7AATT.js";
import {
  behavioralAnalyst,
  buildDefaultAnalystRegistry,
  createChatClient,
  deriveEfficiencyFindings
} from "../chunk-SFXDMFGV.js";
import "../chunk-HHWE3POT.js";
import {
  ANALYST_SEVERITIES,
  AnalystRegistry,
  CanonicalRawAnalystFindingSchema,
  DEFAULT_TRACE_ANALYST_KINDS,
  FAILURE_MODE_KIND_SPEC,
  FINDING_SUBJECT_GRAMMAR_PROMPT,
  FINDING_SUBJECT_KINDS,
  FINDING_SUBJECT_SYNTAX,
  FindingSubjectStringSchema,
  IMPROVEMENT_KIND_SPEC,
  KIND_EXPECTED_SUBJECTS,
  KNOWLEDGE_GAP_KIND_SPEC,
  KNOWLEDGE_POISONING_KIND_SPEC,
  POLICY_EDIT_AXES,
  POLICY_EDIT_CANDIDATE_RECORD_SCHEMA,
  POLICY_EDIT_TARGET_SURFACES,
  PolicyEditValidationError,
  RAW_FINDING_SCHEMA_PROMPT,
  RawAnalystEvidenceSchema,
  RawAnalystFindingSchema,
  admitPolicyEdit,
  applyPolicyEditToSurface,
  assertNoJudgeVerdict,
  buildTraceToolsForGroup,
  coerceJson,
  coerceToFindingRows,
  computeFindingId,
  computePolicyEditId,
  createAnalystAi,
  createTraceAnalystKind,
  evidenceRefsFromRawFinding,
  findingSubjectGrammarPromptFor,
  isJudgeVerdict,
  isPolicyEdit,
  isTraceObservable,
  makeFinding,
  makePolicyEdit,
  makePolicyEditCandidateRecord,
  parseCanonicalRawFinding,
  parseFindingSubject,
  parseRawFinding,
  policyEditFromFinding,
  policyEditsFromFindings,
  renderFindingSubject,
  renderPriorFindings,
  renderUpstreamFindings,
  scorePolicyEditReadiness,
  settleUsageReceiptFromCostLedger,
  stripCodeFences,
  structureFindings,
  validatePolicyEdit,
  validatePolicyEditCandidateRecord,
  validateUsageSettlementTimeout
} from "../chunk-EAWKAVID.js";
import "../chunk-NJC7U437.js";
import {
  CostLedger
} from "../chunk-ZMXDQ4K7.js";
import "../chunk-VI2UW6B6.js";
import "../chunk-PXD6ZFNY.js";
import "../chunk-PC4UYEBM.js";
import "../chunk-XJYR7XFV.js";
import "../chunk-VSMTAMNK.js";
import "../chunk-ONWEPEDO.js";
import "../chunk-K4DBDHLK.js";
import "../chunk-PZ5AY32C.js";

// src/analyst/adapters.ts
var ADAPTER_REV = "1";
function liftSeverity(s) {
  switch (s) {
    case "critical":
      return "critical";
    case "major":
      return "high";
    case "minor":
      return "medium";
    case "info":
      return "info";
  }
}
function createVerifierAdapter(opts) {
  const id = opts.id ?? "multi-layer-verifier";
  const area = opts.area ?? "verification";
  return {
    id,
    description: "Runs a MultiLayerVerifier and lifts each layer's findings into the analyst envelope.",
    inputKind: "custom",
    cost: { kind: "deterministic" },
    version: `verifier-${ADAPTER_REV}`,
    async analyze(env, ctx) {
      const report = await opts.verifier.run({ env, ...opts.options });
      const out = [];
      for (const layer of report.layers) {
        for (const finding of layer.findings) {
          out.push(liftLayerFinding(id, area, layer.layer, finding));
        }
        if (layer.status === "fail" || layer.status === "error" || layer.status === "timeout") {
          out.push(
            makeFinding({
              analyst_id: id,
              area,
              subject: layer.layer,
              claim: `layer "${layer.layer}" ${layer.status}: ${layer.reason ?? "no reason given"}`,
              severity: layer.status === "error" ? "high" : layer.status === "timeout" ? "medium" : "high",
              confidence: 1,
              evidence_refs: [],
              metadata: {
                layer_status: layer.status,
                duration_ms: layer.durationMs,
                score: layer.score,
                diagnostics: layer.diagnostics
              }
            })
          );
        }
      }
      ctx.log?.("verifier complete", {
        layers: report.layers.length,
        blended: report.blendedScore,
        all_pass: report.allPass
      });
      return out;
    }
  };
}
function liftLayerFinding(analyst_id, area, layer, f) {
  return makeFinding({
    analyst_id,
    area,
    subject: f.layer ?? layer,
    claim: f.message,
    severity: liftSeverity(f.severity),
    confidence: 0.85,
    evidence_refs: f.evidence ? [{ kind: "artifact", uri: "inline:evidence", excerpt: f.evidence }] : [],
    metadata: f.detail
  });
}
function createRunCriticAdapter(opts = {}) {
  const id = opts.id ?? "run-critic";
  const area = opts.area ?? "run-quality";
  const critic = opts.critic ?? new RunCritic();
  const threshold = opts.threshold ?? 0.5;
  return {
    id,
    description: "Scores a single run across success / grounding / drift / tool-quality and surfaces below-threshold dimensions.",
    inputKind: "custom",
    cost: { kind: "deterministic" },
    version: `run-critic-${ADAPTER_REV}`,
    async analyze(trace) {
      const score = critic.scoreTrace(trace);
      const out = [];
      const dims = [
        ["success", "critical", "run did not complete successfully"],
        ["goalProgress", "high", "goal progress is low"],
        ["repoGroundedness", "high", "output is poorly grounded in the repository"],
        ["toolUseQuality", "medium", "tool use quality is low"],
        ["patchQuality", "medium", "no real patch/edit evidence"],
        ["testReality", "high", "no real test/build evidence"],
        ["finalGate", "critical", "final gate is blocking"]
      ];
      for (const [dim, sev, msg] of dims) {
        const value = score[dim];
        if (typeof value === "number" && value < threshold) {
          out.push(
            makeFinding({
              analyst_id: id,
              area,
              subject: dim,
              claim: msg,
              rationale: `${dim}=${value.toFixed(2)} below threshold ${threshold}`,
              severity: sev,
              confidence: 1,
              evidence_refs: [],
              metadata: { dimension: dim, value, threshold, run_id: trace.run.runId }
            })
          );
        }
      }
      if (score.driftPenalty > 1 - threshold) {
        out.push(
          makeFinding({
            analyst_id: id,
            area,
            subject: "drift",
            claim: "agent output drifted from repository signal",
            rationale: `driftPenalty=${score.driftPenalty.toFixed(2)}`,
            severity: "medium",
            confidence: 0.9,
            evidence_refs: [],
            metadata: { drift_penalty: score.driftPenalty, notes: score.notes }
          })
        );
      }
      return out;
    }
  };
}
function createJudgeAdapter(opts) {
  const id = opts.id ?? "judge";
  const area = opts.area ?? "judge";
  const threshold = opts.threshold ?? 6;
  return {
    id,
    description: "Wraps an agent-eval JudgeFn into an analyst; below-threshold dimensions surface as findings.",
    inputKind: "judge-input",
    cost: opts.cost ?? { kind: "llm" },
    version: `judge-${ADAPTER_REV}`,
    async analyze(input) {
      const scores = await opts.judge(opts.tcloud, input);
      return scores.filter((s) => normalize10(s.score) < threshold).map((s) => liftJudgeScore(id, area, s));
    }
  };
}
function normalize10(s) {
  return s <= 1 ? s * 10 : s;
}
function liftJudgeScore(analyst_id, area, s) {
  const score10 = normalize10(s.score);
  const severity = score10 < 3 ? "critical" : score10 < 5 ? "high" : score10 < 7 ? "medium" : "low";
  return makeFinding({
    analyst_id,
    area,
    subject: s.dimension,
    claim: `${s.judgeName}/${s.dimension} scored ${score10.toFixed(1)}/10`,
    rationale: s.reasoning,
    severity,
    confidence: 0.8,
    evidence_refs: s.evidence ? [{ kind: "artifact", uri: "inline:evidence", excerpt: s.evidence }] : [],
    // Provenance: this finding IS a judge verdict (an acceptance score), not an
    // observation of behavior. The steer firewall (assertNoJudgeVerdict) rejects
    // it from steering — even when it cites an artifact above — because letting a
    // verdict steer the next attempt is the held-out judge leaking into the loop.
    derived_from_judge: true,
    metadata: { judge_name: s.judgeName, dimension: s.dimension, score_10: score10 }
  });
}
function createSemanticConceptJudgeAdapter(opts = {}) {
  const id = opts.id ?? "semantic-concept-judge";
  const area = opts.area ?? "concept-coverage";
  const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs);
  return {
    id,
    description: "Runs the semantic-concept judge and surfaces missing / weak concepts as findings.",
    inputKind: "custom",
    cost: {
      kind: "llm",
      models: opts.options?.model ? [opts.options.model] : void 0,
      settlement_timeout_ms: settlementTimeoutMs
    },
    version: `${SEMANTIC_CONCEPT_JUDGE_VERSION}-adapter-${ADAPTER_REV}`,
    async analyze(input, ctx) {
      const costLedger = new CostLedger(ctx.budgetUsd);
      let result;
      try {
        result = await runSemanticConceptJudge(input, {
          ...opts.options,
          costLedger,
          signal: ctx.signal
        });
      } finally {
        const usage = await settleUsageReceiptFromCostLedger(costLedger, {
          channel: "judge",
          timeoutMs: settlementTimeoutMs
        });
        if (!usage.settled) {
          ctx.log?.("semantic-concept judge provider settlement timed out", {
            pending_calls: usage.pendingCalls,
            timeout_ms: settlementTimeoutMs
          });
        }
        ctx.recordUsage?.(usage.receipt);
      }
      if (!result.available) {
        return [
          makeFinding({
            analyst_id: id,
            area,
            claim: "semantic-concept judge unavailable",
            rationale: result.error,
            severity: "info",
            confidence: 1,
            evidence_refs: [],
            metadata: { reason: result.error }
          })
        ];
      }
      const out = [];
      for (const f of result.findings) {
        if (f.present && f.score >= 7) continue;
        out.push(
          makeFinding({
            analyst_id: id,
            area,
            subject: f.concept,
            claim: f.present ? `concept "${f.concept}" is weak (${f.score}/10)` : `concept "${f.concept}" is missing`,
            rationale: f.evidence,
            severity: liftSeverity(f.severity),
            confidence: 0.85,
            evidence_refs: [{ kind: "artifact", uri: "inline:evidence", excerpt: f.evidence }],
            metadata: {
              concept: f.concept,
              present: f.present,
              score_10: f.score
            }
          })
        );
      }
      return out;
    }
  };
}
export {
  ANALYST_SEVERITIES,
  AnalystRegistry,
  CanonicalRawAnalystFindingSchema,
  DEFAULT_TRACE_ANALYST_KINDS,
  FAILURE_MODE_KIND_SPEC,
  FINDING_SUBJECT_GRAMMAR_PROMPT,
  FINDING_SUBJECT_KINDS,
  FINDING_SUBJECT_SYNTAX,
  FindingSubjectStringSchema,
  FindingsStore,
  IMPROVEMENT_KIND_SPEC,
  KIND_EXPECTED_SUBJECTS,
  KNOWLEDGE_GAP_KIND_SPEC,
  KNOWLEDGE_POISONING_KIND_SPEC,
  POLICY_EDIT_AXES,
  POLICY_EDIT_CANDIDATE_RECORD_SCHEMA,
  POLICY_EDIT_TARGET_SURFACES,
  PolicyEditValidationError,
  RAW_FINDING_SCHEMA_PROMPT,
  RawAnalystEvidenceSchema,
  RawAnalystFindingSchema,
  SKILL_USAGE_ANALYST,
  SkillUsageAnalyst,
  admitPolicyEdit,
  applyPolicyEditToSurface,
  assertNoJudgeVerdict,
  behavioralAnalyst,
  buildDefaultAnalystRegistry,
  buildSkillUsageReport,
  buildTraceToolsForGroup,
  coerceJson,
  coerceToFindingRows,
  computeFindingId,
  computePolicyEditId,
  createAnalystAi,
  createChatClient,
  createJudgeAdapter,
  createRunCriticAdapter,
  createSemanticConceptJudgeAdapter,
  createTraceAnalystKind,
  createVerifierAdapter,
  defaultIsMaterial,
  deriveEfficiencyFindings,
  diffFindings,
  emitSkillUsageFindings,
  evidenceRefsFromRawFinding,
  findingSubjectGrammarPromptFor,
  isJudgeVerdict,
  isPolicyEdit,
  isTraceObservable,
  liftSeverity,
  makeFinding,
  makePolicyEdit,
  makePolicyEditCandidateRecord,
  parseCanonicalRawFinding,
  parseFindingSubject,
  parseRawFinding,
  policyEditFromFinding,
  policyEditsFromFindings,
  renderFindingSubject,
  renderPriorFindings,
  renderUpstreamFindings,
  scorePolicyEditReadiness,
  stripCodeFences,
  structureFindings,
  validatePolicyEdit,
  validatePolicyEditCandidateRecord
};
//# sourceMappingURL=index.js.map