// src/governance/types.ts
function renderMarkdown(report) {
  const sevEmoji = {
    info: "\u2139\uFE0E",
    low: "\xB7",
    medium: "!",
    high: "!!",
    critical: "\u203C"
  };
  const lines = [];
  lines.push(`# ${report.framework} report \u2014 ${report.context.systemName}`);
  lines.push("");
  lines.push(`- Organization: **${report.context.organization}**`);
  lines.push(`- Period: ${report.context.periodStart} \u2192 ${report.context.periodEnd}`);
  lines.push(
    `- Owner: ${report.context.owner.role} ${report.context.owner.name} <${report.context.owner.email}>`
  );
  lines.push(`- Generated: ${report.generatedAt}`);
  lines.push("");
  lines.push(`## Summary \u2014 ${report.summary.overall}`);
  lines.push("");
  lines.push(`${report.summary.findings} finding(s).`);
  for (const [sev, n] of Object.entries(report.summary.byeverity)) {
    if (n > 0) lines.push(`- ${sevEmoji[sev]} ${sev}: ${n}`);
  }
  lines.push("");
  lines.push("## Findings");
  lines.push("");
  for (const f of report.findings) {
    lines.push(`### ${sevEmoji[f.severity]} ${f.id} \u2014 ${f.control}`);
    lines.push("");
    lines.push(f.summary);
    if (f.evidence) {
      lines.push("");
      lines.push(`**Evidence:** ${f.evidence}`);
    }
    if (f.remediation) {
      lines.push("");
      lines.push(`**Remediation:** ${f.remediation}`);
    }
    lines.push("");
  }
  return lines.join("\n");
}
function summarize(findings) {
  const byeverity = {
    info: 0,
    low: 0,
    medium: 0,
    high: 0,
    critical: 0
  };
  for (const f of findings) byeverity[f.severity]++;
  const overall = byeverity.critical + byeverity.high > 0 ? "non-compliant" : byeverity.medium + byeverity.low > 0 ? "compliant-with-findings" : "compliant";
  return { findings: findings.length, byeverity, overall };
}

// src/governance/eu-ai-act.ts
function classifyEuAiRisk(signals) {
  if (signals.biometricPublic || signals.socialScoring || signals.subliminal) return "unacceptable";
  if (signals.annexIII) return "high";
  if (signals.chatbot || signals.generatesSyntheticMedia) return "limited";
  return "minimal";
}
async function euAiActReport(ctx, signals) {
  const riskClass = classifyEuAiRisk(signals);
  const findings = [];
  if (riskClass === "unacceptable") {
    findings.push({
      id: "EU-ART-5",
      severity: "critical",
      control: "EU-AI-ACT:Article-5",
      summary: "Use case matches a prohibited practice under Article 5.",
      remediation: "Discontinue or substantially redesign the use case."
    });
  }
  if (riskClass === "high") {
    if (!ctx.redTeam) {
      findings.push({
        id: "EU-ART-9",
        severity: "high",
        control: "EU-AI-ACT:Article-9",
        summary: "High-risk system lacks documented adversarial-testing evidence (Art. 9 risk mgmt).",
        remediation: "Run redTeamDataset() + attach the report."
      });
    }
    if (ctx.datasets.length === 0) {
      findings.push({
        id: "EU-ART-10",
        severity: "high",
        control: "EU-AI-ACT:Article-10",
        summary: "No training/eval datasets recorded with provenance (Art. 10)."
      });
    }
    const runs = await ctx.traceStore.listRuns({
      since: Date.parse(ctx.periodStart),
      until: Date.parse(ctx.periodEnd)
    });
    if (runs.length === 0) {
      findings.push({
        id: "EU-ART-11",
        severity: "high",
        control: "EU-AI-ACT:Article-11",
        summary: "No eval runs recorded (Art. 11 technical documentation)."
      });
    }
    if (!signals.chatbot && !signals.generatesSyntheticMedia) {
    } else {
      findings.push({
        id: "EU-ART-13",
        severity: "info",
        control: "EU-AI-ACT:Article-13",
        summary: "Chatbot/synthetic-media transparency obligations apply; verify user-facing disclosures."
      });
    }
    if (!ctx.owner?.email) {
      findings.push({
        id: "EU-ART-14",
        severity: "high",
        control: "EU-AI-ACT:Article-14",
        summary: "No designated human overseer (Art. 14).",
        remediation: "Populate GovernanceContext.owner with the responsible individual."
      });
    }
    if (!ctx.outcomeStore) {
      findings.push({
        id: "EU-ART-15",
        severity: "medium",
        control: "EU-AI-ACT:Article-15",
        summary: "No post-deployment outcome measurement; accuracy + robustness are un-attested.",
        remediation: "Attach an OutcomeStore + run correlationStudy() over the reporting period."
      });
    }
  }
  if (riskClass === "limited") {
    findings.push({
      id: "EU-ART-52",
      severity: "info",
      control: "EU-AI-ACT:Article-52",
      summary: "Transparency obligations apply: disclose AI nature + synthetic content labeling.",
      remediation: "Ensure user-facing surfaces label AI-generated content."
    });
  }
  const payload = {
    riskClass,
    signals,
    articlesReviewed: riskClass === "high" ? ["5", "9", "10", "11", "13", "14", "15"] : riskClass === "limited" ? ["52"] : ["none"]
  };
  return {
    framework: "EU-AI-ACT",
    version: "Regulation-2024-1689",
    context: {
      organization: ctx.organization,
      systemName: ctx.systemName,
      periodStart: ctx.periodStart,
      periodEnd: ctx.periodEnd,
      owner: ctx.owner
    },
    summary: summarize(findings),
    findings,
    payload,
    generatedAt: (/* @__PURE__ */ new Date()).toISOString()
  };
}

// src/governance/nist-ai-rmf.ts
async function nistAiRmfReport(ctx) {
  const findings = [];
  if (!ctx.owner?.email) {
    findings.push({
      id: "G-1.1",
      severity: "high",
      control: "NIST-AI-RMF:GOVERN-1.1",
      summary: "No responsible owner recorded for the AI system.",
      remediation: "Assign an accountable individual + email in GovernanceContext.owner."
    });
  }
  if (ctx.datasets.length === 0) {
    findings.push({
      id: "G-1.3",
      severity: "high",
      control: "NIST-AI-RMF:GOVERN-1.3",
      summary: "No versioned datasets recorded for the evaluation period.",
      remediation: "Register each dataset with a Dataset manifest (content hash + provenance)."
    });
  } else {
    for (const manifest of ctx.datasets) {
      if (!manifest.contentHash || manifest.contentHash.length < 16) {
        findings.push({
          id: "G-1.3-hash",
          severity: "medium",
          control: "NIST-AI-RMF:GOVERN-1.3",
          summary: `Dataset "${manifest.name}" has weak or missing content hash.`,
          evidence: `contentHash="${manifest.contentHash}"`,
          remediation: "Call dataset.manifest() to compute SHA-256; commit the manifest alongside releases."
        });
      }
    }
  }
  if (!ctx.redTeam) {
    findings.push({
      id: "M-2.6",
      severity: "high",
      control: "NIST-AI-RMF:MEASURE-2.6",
      summary: "No red-team evaluation attached to the report period.",
      remediation: "Run redTeamDataset() against the system and attach the RedTeamReport to context.redTeam."
    });
  } else if (ctx.redTeam.overallPassRate < 0.8) {
    findings.push({
      id: "M-2.6-rate",
      severity: "high",
      control: "NIST-AI-RMF:MEASURE-2.6",
      summary: `Red-team pass rate ${(ctx.redTeam.overallPassRate * 100).toFixed(1)}% below 80% threshold.`,
      evidence: JSON.stringify(ctx.redTeam.passRateByCategory),
      remediation: "Harden the failing categories; rerun the battery."
    });
  }
  const runs = await ctx.traceStore.listRuns({
    since: Date.parse(ctx.periodStart),
    until: Date.parse(ctx.periodEnd)
  });
  if (runs.length === 0) {
    findings.push({
      id: "M-2.1",
      severity: "critical",
      control: "NIST-AI-RMF:MEASURE-2.1",
      summary: "No eval runs recorded for the reporting period.",
      remediation: "Emit traces for every deployment-relevant evaluation."
    });
  }
  if (!ctx.judgeCalibration || ctx.judgeCalibration.length === 0) {
    findings.push({
      id: "M-2.11",
      severity: "medium",
      control: "NIST-AI-RMF:MEASURE-2.11",
      summary: "No judge-vs-human calibration recorded.",
      remediation: "Build a human golden set; run calibrateJudge() before trusting LLM judge scores."
    });
  } else {
    const weak = ctx.judgeCalibration.filter((c) => Number.isFinite(c.pearson) && c.pearson < 0.6);
    if (weak.length > 0) {
      findings.push({
        id: "M-2.11-weak",
        severity: "medium",
        control: "NIST-AI-RMF:MEASURE-2.11",
        summary: `${weak.length} judge(s) show weak agreement with humans (Pearson < 0.6).`,
        remediation: "Retrain or replace the underperforming judges."
      });
    }
  }
  if (!ctx.outcomeStore) {
    findings.push({
      id: "MN-1.1",
      severity: "medium",
      control: "NIST-AI-RMF:MANAGE-1.1",
      summary: "No deployment outcomes captured \u2014 meta-eval correlation cannot be computed.",
      remediation: "Attach an OutcomeStore and ingest production outcome metrics."
    });
  } else {
    const outcomes = await ctx.outcomeStore.list({
      since: Date.parse(ctx.periodStart),
      until: Date.parse(ctx.periodEnd)
    });
    if (outcomes.length === 0) {
      findings.push({
        id: "MN-1.1-empty",
        severity: "medium",
        control: "NIST-AI-RMF:MANAGE-1.1",
        summary: "OutcomeStore present but no outcomes captured for the period."
      });
    }
  }
  const hashChecks = [];
  for (const manifest of ctx.datasets) {
    hashChecks.push({ name: manifest.name, ok: /^[0-9a-f]{64}$/.test(manifest.contentHash) });
  }
  const payload = {
    controlsEvaluated: [
      "GOVERN-1.1",
      "GOVERN-1.3",
      "MEASURE-2.1",
      "MEASURE-2.6",
      "MEASURE-2.11",
      "MANAGE-1.1"
    ],
    runCount: runs.length,
    redTeamPassRate: ctx.redTeam?.overallPassRate ?? null,
    datasetHashChecks: hashChecks
  };
  return {
    framework: "NIST-AI-RMF",
    version: "1.0.0",
    context: {
      organization: ctx.organization,
      systemName: ctx.systemName,
      periodStart: ctx.periodStart,
      periodEnd: ctx.periodEnd,
      owner: ctx.owner
    },
    summary: summarize(findings),
    findings,
    payload,
    generatedAt: (/* @__PURE__ */ new Date()).toISOString()
  };
}

// src/governance/soc2.ts
async function soc2Report(ctx) {
  const findings = [];
  const start = Date.parse(ctx.periodStart);
  const end = Date.parse(ctx.periodEnd);
  const runs = await ctx.traceStore.listRuns({ since: start, until: end });
  const failureRate = runs.length > 0 ? runs.filter((r) => r.outcome?.pass === false).length / runs.length : null;
  if (failureRate !== null && failureRate > 0.2) {
    findings.push({
      id: "CC7.1-fail-rate",
      severity: "medium",
      control: "SOC2:CC7.1",
      summary: `System failure rate ${(failureRate * 100).toFixed(1)}% over the period exceeds 20%.`,
      remediation: "Investigate failure clusters (failureClusterView) + prioritize remediation."
    });
  }
  if (runs.length === 0) {
    findings.push({
      id: "CC7.1-coverage",
      severity: "high",
      control: "SOC2:CC7.1",
      summary: "No telemetry runs recorded for the period \u2014 monitoring regime is incomplete."
    });
  }
  const aborted = runs.filter((r) => r.status === "aborted");
  if (aborted.length > runs.length * 0.05 && aborted.length >= 3) {
    findings.push({
      id: "CC7.2-abort",
      severity: "medium",
      control: "SOC2:CC7.2",
      summary: `${aborted.length} run(s) aborted \u2014 investigate pattern.`,
      remediation: "Use the bisector + failureClusterView to localize the trigger."
    });
  }
  const incidentEvents = await ctx.traceStore.events({
    kind: "policy_violation",
    since: start,
    until: end
  });
  const errorEvents = await ctx.traceStore.events({ kind: "error", since: start, until: end });
  const totalIncidents = incidentEvents.length + errorEvents.length;
  if (totalIncidents > 0) {
    findings.push({
      id: "CC7.3-resolution",
      severity: "low",
      control: "SOC2:CC7.3",
      summary: `${totalIncidents} incident-class event(s) recorded; resolution tracking is informal.`,
      remediation: 'Emit a resolution event (kind="log" with payload.resolves=<eventId>) per remediated incident.'
    });
  }
  const modelFingerprints = new Set(runs.map((r) => r.modelFingerprint).filter(Boolean));
  const promptHashes = new Set(runs.map((r) => r.promptSha).filter(Boolean));
  const codeSha = new Set(runs.map((r) => r.codeSha).filter(Boolean));
  if (codeSha.size === 0) {
    findings.push({
      id: "CC7.4-code",
      severity: "high",
      control: "SOC2:CC7.4",
      summary: "No codeSha recorded on runs \u2014 cannot attribute scores to a specific release.",
      remediation: "Populate Run.codeSha with the git SHA of the system at run time."
    });
  }
  if (promptHashes.size === 0) {
    findings.push({
      id: "CC7.4-prompt",
      severity: "medium",
      control: "SOC2:CC7.4",
      summary: "No promptSha recorded \u2014 prompt changes are untracked."
    });
  }
  const payload = {
    controls: ["CC7.1", "CC7.2", "CC7.3", "CC7.4"],
    runCount: runs.length,
    failureRate,
    abortedCount: aborted.length,
    incidentEventCount: totalIncidents,
    distinctReleases: {
      codeShas: codeSha.size,
      promptHashes: promptHashes.size,
      modelFingerprints: modelFingerprints.size
    }
  };
  return {
    framework: "SOC2",
    version: "2017-Common-Criteria",
    context: {
      organization: ctx.organization,
      systemName: ctx.systemName,
      periodStart: ctx.periodStart,
      periodEnd: ctx.periodEnd,
      owner: ctx.owner
    },
    summary: summarize(findings),
    findings,
    payload,
    generatedAt: (/* @__PURE__ */ new Date()).toISOString()
  };
}

export {
  renderMarkdown,
  summarize,
  classifyEuAiRisk,
  euAiActReport,
  nistAiRmfReport,
  soc2Report
};
//# sourceMappingURL=chunk-KKHDIONI.js.map