// ../core/src/codeAgent/types.ts
var RHEI_CODE_AGENT_SCHEMA_VERSION = 1;
var RHEI_CODE_AGENT_HANDOFF_KIND = "rhei_code_agent_handoff";
var RHEI_CODE_AGENT_RESULT_KIND = "rhei_code_agent_result";
var RHEI_CODE_AGENT_RESULT_SUMMARY_KIND = "rhei_code_agent_result_summary";
var RHEI_CODE_AGENT_RESULT_RANKING_KIND = "rhei_code_agent_result_ranking";
var RHEI_CODE_AGENT_TOKEN_ESTIMATE_VERSION = "char-div-4-v1";
// ../core/src/codeAgent/builders.ts
var RHEI_CODE_AGENT_ROLES_V1 = [
  "explore_agent",
  "engineer_agent",
  "review_agent",
  "validation_agent",
  "design_agent"
];
var RHEI_CODE_AGENT_DESIGN_OUTPUT_KINDS_V1 = [
  "architecture_review",
  "ux_review",
  "workflow_review",
  "design_doc",
  "decision_options",
  "recommended_slice",
  "risk_notes"
];
var DEFAULT_GENERATED_AT = Date.parse("2026-05-18T00:00:00.000Z");
var RHEI_CODE_AGENT_REPORT_ONLY_GUARDRAILS_V1 = {
  reportOnly: true,
  advisoryOnly: true,
  noAuthority: true,
  noProviderCalls: true,
  noWrites: true,
  noNetworkCalls: true,
  noHiddenExecution: true,
  noProcessExecution: true,
  noFilesystemSourceScan: true,
  noSourceReads: true,
  noSessionMutation: true,
  sourceContextGrantsNoAuthority: true,
  applyRequiresSeparateGatedTool: true,
  summarizeIsUtilityModeNotAgentRole: true
};
function buildRheiCodeAgentHandoffV1(args) {
  const generatedAt = args.generatedAt ?? DEFAULT_GENERATED_AT;
  const workflowPlan = args.workflowPlan ?? args.codeWorkHandoff?.workflowPlan;
  const sessionSelect = args.sessionSelect ?? workflowPlan?.sessionSelect;
  const oracleContextBundles = uniqueById([args.oracleContextBundle, ...args.oracleContextBundles ?? []], (bundle) => bundle.bundleId);
  const contextBundleIds = uniqueStrings([
    ...args.contextBundleIds ?? [],
    ...args.sourceRefs?.oracleContextBundleIds ?? [],
    ...oracleContextBundles.map((bundle) => bundle.bundleId)
  ]);
  const sourceRefs = buildSourceRefs(args, contextBundleIds);
  const contextRefs = buildContextRefs(args, sessionSelect);
  const expectedOutputKinds = uniqueOutputKinds(args.expectedOutputKinds ?? defaultExpectedOutputKinds(args.assignedRole));
  const roleDefinition = roleDefinitionFor(args.assignedRole);
  const goal = args.goal ?? args.objective ?? "Rhei Code Agent handoff";
  const handoffId = args.handoffId ?? `rhei-code-agent-handoff:${stableSlug(args.assignedRole)}:${stableSlug(goal)}`;
  const parentSessionId = args.parentSessionId ?? sourceRefs.codeSessionId;
  const workflowPlanId = args.workflowPlanId ?? sourceRefs.workflowPlanId;
  const codeWorkHandoffId = args.codeWorkHandoffId ?? sourceRefs.codeWorkHandoffId;
  const oracleSessionId = args.oracleSessionId ?? sourceRefs.oracleSessionId;
  const receipts = uniqueStrings([...args.receipts ?? [], ...sourceRefs.receiptRefs]);
  const scope = buildScope(args, sessionSelect, contextRefs, workflowPlan?.sourceRefs.serviceConnectionIds ?? []);
  const context = buildContext({ workflowPlan, codeWorkHandoff: args.codeWorkHandoff, oracleContextBundles, sessionSelect });
  const instructions = buildInstructions(args, goal, expectedOutputKinds);
  return {
    schemaVersion: RHEI_CODE_AGENT_SCHEMA_VERSION,
    kind: RHEI_CODE_AGENT_HANDOFF_KIND,
    mode: "handoff",
    handoffId,
    generatedAt,
    parentSessionId,
    workflowPlanId,
    codeWorkHandoffId,
    oracleSessionId,
    contextBundleIds,
    goal,
    objective: args.objective ?? goal,
    assignedRole: args.assignedRole,
    roleDefinition,
    task: args.task ?? goal,
    expectedOutputKinds,
    scope,
    context,
    instructions,
    instructionNotes: buildInstructionNotes(args),
    gates: buildGates(args, expectedOutputKinds),
    receipts,
    sourceRefs,
    contextRefs,
    workflowPlan,
    sessionSelect,
    codeWorkHandoff: args.codeWorkHandoff,
    oracleContextBundles,
    modelProfile: args.modelProfile ? modelProfileRef(args.modelProfile) : undefined,
    riskNotes: uniqueStrings(args.riskNotes ?? []),
    warnings: uniqueStrings([
      ...args.warnings ?? [],
      ...(args.codeWorkHandoff?.warnings ?? []).map((warning) => `code_work_handoff:${warning}`),
      ...(workflowPlan?.warnings ?? []).map((warning) => `workflow_plan:${warning}`)
    ]),
    execution: noExecution(),
    guardrails: reportOnlyGuardrails(),
    ...safetyFlags()
  };
}
function buildRheiCodeAgentResultV1(args) {
  const generatedAt = args.generatedAt ?? DEFAULT_GENERATED_AT;
  const assignedRole = args.assignedRole ?? args.sourceHandoff?.assignedRole ?? "explore_agent";
  const objective = args.objective ?? args.sourceHandoff?.goal ?? args.sourceHandoff?.objective ?? "Rhei Code Agent result";
  const sourceHandoffId = args.sourceHandoffId ?? args.sourceHandoff?.handoffId;
  const outputs = (args.outputs ?? []).map((output, index) => buildOutput(output, index));
  const status = args.status ?? inferStatus(outputs, args.riskNotes ?? []);
  const score = buildScore({ status, outputs, riskNotes: args.riskNotes ?? [], overrides: args.score });
  const rankingSignals = buildRankingSignals({ score, outputs, riskNotes: args.riskNotes ?? [], overrides: args.rankingSignals });
  const resultId = args.resultId ?? `rhei-code-agent-result:${stableSlug(assignedRole)}:${stableSlug(sourceHandoffId ?? objective)}`;
  return {
    schemaVersion: RHEI_CODE_AGENT_SCHEMA_VERSION,
    kind: RHEI_CODE_AGENT_RESULT_KIND,
    mode: "import_result",
    resultId,
    generatedAt,
    sourceHandoffId,
    assignedRole,
    objective,
    status,
    summary: args.summary,
    outputs,
    evidenceRefs: uniqueStrings(args.evidenceRefs ?? args.sourceHandoff?.contextRefs.evidenceRefs ?? []),
    receiptRefs: uniqueStrings(args.receiptRefs ?? args.sourceHandoff?.sourceRefs.receiptRefs ?? []),
    riskNotes: uniqueStrings(args.riskNotes ?? []),
    warnings: uniqueStrings(args.warnings ?? []),
    score,
    rankingSignals,
    execution: noExecution(),
    guardrails: reportOnlyGuardrails(),
    ...safetyFlags()
  };
}
function summarizeRheiCodeAgentResultsV1(args) {
  const generatedAt = args.generatedAt ?? DEFAULT_GENERATED_AT;
  const results = args.results.map(summaryItem);
  const aggregateScore = averageScore(args.results.map((result) => result.score), "Aggregate score across imported Rhei Code Agent results.");
  const summaryId = args.summaryId ?? `rhei-code-agent-result-summary:${stableSlug(args.objective)}:${args.results.length}`;
  return {
    schemaVersion: RHEI_CODE_AGENT_SCHEMA_VERSION,
    kind: RHEI_CODE_AGENT_RESULT_SUMMARY_KIND,
    mode: "summarize_result",
    summaryId,
    generatedAt,
    objective: args.objective,
    resultCount: args.results.length,
    sourceResultIds: args.results.map((result) => result.resultId),
    statusCounts: statusCounts(args.results),
    outputKindCounts: outputKindCounts(args.results),
    topRisks: uniqueStrings(args.results.flatMap((result) => result.riskNotes)).slice(0, 10),
    recommendedNextSlice: args.recommendedNextSlice,
    aggregateScore,
    results,
    warnings: uniqueStrings(args.warnings ?? []),
    execution: noExecution(),
    guardrails: reportOnlyGuardrails(),
    ...safetyFlags()
  };
}
function rankRheiCodeAgentResultsV1(args) {
  const generatedAt = args.generatedAt ?? DEFAULT_GENERATED_AT;
  const sorted = [...args.results].sort(compareResults);
  const recommendedResultId = sorted.find((result) => ["completed", "partial"].includes(result.status))?.resultId;
  const rankingId = args.rankingId ?? `rhei-code-agent-result-ranking:${stableSlug(args.objective)}:${args.results.length}`;
  return {
    schemaVersion: RHEI_CODE_AGENT_SCHEMA_VERSION,
    kind: RHEI_CODE_AGENT_RESULT_RANKING_KIND,
    mode: "rank_results",
    rankingId,
    generatedAt,
    objective: args.objective,
    sourceResultIds: args.results.map((result) => result.resultId),
    rankings: sorted.map((result, index) => ({
      rank: index + 1,
      resultId: result.resultId,
      assignedRole: result.assignedRole,
      status: result.status,
      score: result.score,
      rankingSignals: result.rankingSignals,
      rationale: result.score.rationale,
      recommended: result.resultId === recommendedResultId,
      riskNotes: result.riskNotes,
      ...safetyFlags()
    })),
    recommendedResultId,
    warnings: uniqueStrings(args.warnings ?? []),
    execution: noExecution(),
    guardrails: reportOnlyGuardrails(),
    ...safetyFlags()
  };
}
function roleDefinitionFor(role) {
  switch (role) {
    case "explore_agent":
      return roleDefinition(role, "Explore agent", "Map relevant context and report findings without edits.", ["context_map", "finding", "risk_notes"]);
    case "engineer_agent":
      return roleDefinition(role, "Engineer agent", "Plan implementation slices and patch proposals without applying changes.", ["implementation_plan", "patch_plan", "recommended_slice", "risk_notes"]);
    case "review_agent":
      return roleDefinition(role, "Review agent", "Review proposed work and identify correctness, maintainability, and safety risks.", ["review_notes", "finding", "risk_notes"]);
    case "validation_agent":
      return roleDefinition(role, "Validation agent", "Plan or summarize validation evidence without running hidden commands.", ["validation_plan", "validation_evidence", "risk_notes"]);
    case "design_agent":
      return roleDefinition(role, "Design agent", "Critique architecture, product, UX, and workflow options; recommend a bounded slice while staying report-only.", [...RHEI_CODE_AGENT_DESIGN_OUTPUT_KINDS_V1], ["architecture", "product", "ux", "workflow"]);
  }
}
function roleDefinition(role, title, purpose, defaultExpectedOutputKinds, designFocus) {
  return {
    role,
    title,
    purpose,
    defaultExpectedOutputKinds,
    designFocus,
    ...safetyFlags()
  };
}
function defaultExpectedOutputKinds(role) {
  return roleDefinitionFor(role).defaultExpectedOutputKinds;
}
function buildScope(args, sessionSelect, contextRefs, workflowServiceConnectionIds) {
  return {
    exactRefs: uniqueStrings([...args.scope?.exactRefs ?? [], ...contextRefs.exactRefs]),
    readSlices: uniqueReadSlices([
      ...args.scope?.readSlices ?? [],
      ...(sessionSelect?.readSlices ?? []).map((slice) => ({
        readSliceId: slice.readSliceId,
        path: slice.path,
        lines: slice.lines,
        role: mapReadSliceRole(slice.role),
        reason: slice.reason,
        tokenEstimate: slice.tokenEstimate
      }))
    ]),
    avoidRefs: uniqueStrings([...args.scope?.avoidRefs ?? [], ...contextRefs.avoidRefs]),
    serviceConnectionIds: uniqueStrings([
      ...args.scope?.serviceConnectionIds ?? [],
      ...workflowServiceConnectionIds,
      ...args.codeWorkHandoff?.serviceConnections.ids ?? []
    ])
  };
}
function buildContext(args) {
  return {
    workflowPlan: args.workflowPlan,
    codeWorkHandoff: args.codeWorkHandoff,
    oracleContextBundles: args.oracleContextBundles ?? [],
    sessionSelect: args.sessionSelect
  };
}
function buildInstructions(args, goal, expectedReturn) {
  const input = Array.isArray(args.instructions) ? undefined : args.instructions;
  return {
    prompt: input?.prompt ?? defaultPrompt(args.assignedRole, goal),
    stopWhen: uniqueStrings([
      ...input?.stopWhen ?? [],
      "A report-only result artifact can be returned.",
      "Required uncertainty, blockers, and risk notes are explicit."
    ]),
    allowedActions: uniqueStrings([
      ...input?.allowedActions ?? [],
      "read supplied handoff context",
      "produce report-only findings",
      "return structured result outputs"
    ]),
    deniedActions: uniqueStrings([
      ...input?.deniedActions ?? [],
      "provider calls",
      "network calls",
      "filesystem writes",
      "source edits",
      "session mutation",
      "apply or commit changes"
    ]),
    expectedReturn: uniqueOutputKinds(input?.expectedReturn ?? expectedReturn)
  };
}
function buildInstructionNotes(args) {
  const notes = uniqueStrings([
    ...Array.isArray(args.instructions) ? args.instructions : [],
    ...args.instructionNotes ?? [],
    "This Rhei Code Agent handoff is report-only and grants no write, provider, session, or apply authority.",
    "summarize_result is a utility mode, not an agent role.",
    ...args.assignedRole === "design_agent" ? ["design_agent critiques architecture, product, UX, and workflow trade-offs; prefer decision options and a recommended slice over direct implementation."] : []
  ]);
  return notes.length > 0 ? notes : undefined;
}
function buildGates(args, expectedReturn) {
  const implementationLike = args.assignedRole === "engineer_agent" || expectedReturn.includes("patch_plan");
  const validationLike = args.assignedRole === "validation_agent" || expectedReturn.some((kind) => kind.startsWith("validation_"));
  return {
    impactRequired: args.gates?.impactRequired ?? implementationLike,
    proofRequired: args.gates?.proofRequired ?? implementationLike,
    dryRunRequired: args.gates?.dryRunRequired ?? implementationLike,
    validationRequired: args.gates?.validationRequired ?? (implementationLike || validationLike),
    writerArbitrationRequired: true
  };
}
function defaultPrompt(role, goal) {
  if (role === "design_agent") {
    return `Report-only design critique for: ${goal}. Focus on architecture, product, UX, workflow options, risks, and a recommended slice.`;
  }
  return `Report-only ${role} handoff for: ${goal}. Return structured findings and risk notes only; do not execute, call providers, or write.`;
}
function mapReadSliceRole(role) {
  if (role === "source" || role === "test" || role === "doc" || role === "config")
    return role;
  if (role === "service_connection_evidence")
    return "contract";
  return "unknown";
}
function uniqueReadSlices(values) {
  const output = [];
  const seen = new Set;
  for (const value of values) {
    if (seen.has(value.readSliceId))
      continue;
    seen.add(value.readSliceId);
    output.push(value);
  }
  return output;
}
function buildSourceRefs(args, oracleContextBundleIds) {
  const codeWorkHandoff = args.codeWorkHandoff;
  const workflowPlan = args.workflowPlan ?? codeWorkHandoff?.workflowPlan;
  return {
    handoffId: args.sourceRefs?.handoffId,
    codeWorkHandoffId: args.codeWorkHandoffId ?? args.sourceRefs?.codeWorkHandoffId ?? codeWorkHandoff?.handoffId,
    workflowPlanId: args.workflowPlanId ?? args.sourceRefs?.workflowPlanId ?? workflowPlan?.workflowPlanId ?? codeWorkHandoff?.sourceRefs.workflowPlanId,
    strategyId: args.sourceRefs?.strategyId ?? workflowPlan?.sourceRefs.strategyId ?? codeWorkHandoff?.sourceRefs.strategyId,
    codeSessionId: args.parentSessionId ?? args.sourceRefs?.codeSessionId ?? codeWorkHandoff?.sourceRefs.sessionId,
    oracleSessionId: args.oracleSessionId ?? args.sourceRefs?.oracleSessionId,
    contextPacketIds: uniqueStrings([
      ...args.sourceRefs?.contextPacketIds ?? [],
      ...workflowPlan?.sourceRefs.contextPacketIds ?? [],
      ...codeWorkHandoff?.sourceRefs.contextPacketIds ?? []
    ]),
    oracleContextBundleIds: uniqueStrings([...args.sourceRefs?.oracleContextBundleIds ?? [], ...oracleContextBundleIds]),
    oraclePromptPacketIds: uniqueStrings([
      ...args.sourceRefs?.oraclePromptPacketIds ?? [],
      ...(workflowPlan?.oraclePromptPackets ?? []).map((packet) => packet.packetId),
      ...(codeWorkHandoff?.oracle.promptPackets ?? []).map((packet) => packet.packetId)
    ]),
    receiptRefs: uniqueStrings([...args.sourceRefs?.receiptRefs ?? [], ...codeWorkHandoff?.receipts.refs ?? []])
  };
}
function buildContextRefs(args, sessionSelect) {
  const codeWorkContext = args.codeWorkHandoff?.contextRefs;
  return {
    exactRefs: uniqueStrings([...args.contextRefs?.exactRefs ?? [], ...sessionSelect?.exactRefs ?? [], ...codeWorkContext?.exactRefs ?? []]),
    sourceRefs: uniqueStrings([...args.contextRefs?.sourceRefs ?? [], ...codeWorkContext?.sourceRefs ?? []]),
    evidenceRefs: uniqueStrings([...args.contextRefs?.evidenceRefs ?? [], ...codeWorkContext?.evidenceRefs ?? []]),
    avoidRefs: uniqueStrings([...args.contextRefs?.avoidRefs ?? [], ...sessionSelect?.avoidRefs ?? [], ...codeWorkContext?.avoidRefs ?? []]),
    pathOnlyRefs: uniqueStrings([...args.contextRefs?.pathOnlyRefs ?? [], ...sessionSelect?.pathOnlyRefs ?? [], ...codeWorkContext?.pathOnlyRefs ?? []]),
    deferredRefs: uniqueStrings([...args.contextRefs?.deferredRefs ?? [], ...sessionSelect?.deferredRefs ?? [], ...codeWorkContext?.deferredRefs ?? []]),
    readSliceIds: uniqueStrings([
      ...args.contextRefs?.readSliceIds ?? [],
      ...(sessionSelect?.readSlices ?? []).map((slice) => slice.readSliceId),
      ...codeWorkContext?.readSliceIds ?? []
    ])
  };
}
function modelProfileRef(modelProfile) {
  if (!modelProfile)
    return;
  return {
    profileId: modelProfile.profileId,
    role: modelProfile.role,
    provider: modelProfile.provider,
    modelRef: modelProfile.modelRef,
    reasoningEffort: modelProfile.reasoningEffort,
    configurable: modelProfile.configurable,
    ...safetyFlags()
  };
}
function buildOutput(args, index) {
  return {
    outputId: args.outputId ?? `agent-output:${index + 1}:${stableSlug(args.outputKind)}`,
    outputKind: args.outputKind,
    title: args.title,
    summary: args.summary,
    content: args.content,
    refs: uniqueStrings(args.refs ?? []),
    riskNotes: uniqueStrings(args.riskNotes ?? []),
    confidence: clamp01(args.confidence ?? 0.5),
    ...safetyFlags()
  };
}
function inferStatus(outputs, riskNotes) {
  if (outputs.length === 0)
    return riskNotes.length > 0 ? "blocked" : "not_run";
  return "completed";
}
function buildScore(args) {
  const averageConfidence = args.outputs.length > 0 ? args.outputs.reduce((sum, output) => sum + output.confidence, 0) / args.outputs.length : 0;
  const relevance = clamp01(args.overrides?.relevance ?? averageConfidence);
  const completeness = clamp01(args.overrides?.completeness ?? statusCompleteness(args.status));
  const evidenceStrength = clamp01(args.overrides?.evidenceStrength ?? evidenceStrengthFromOutputs(args.outputs));
  const riskPenalty = clamp01(args.overrides?.riskPenalty ?? Math.min(args.riskNotes.length * 0.08, 0.4));
  const blockedPenalty = clamp01(args.overrides?.blockedPenalty ?? (args.status === "blocked" || args.status === "failed" ? 0.35 : 0));
  const score = clamp01(args.overrides?.score ?? (relevance + completeness + evidenceStrength) / 3 - riskPenalty - blockedPenalty);
  return {
    score,
    confidence: clamp01(args.overrides?.confidence ?? averageConfidence),
    relevance,
    completeness,
    evidenceStrength,
    riskPenalty,
    blockedPenalty,
    rationale: args.overrides?.rationale ?? "Deterministic report-only score from status, output confidence, evidence refs, and risk notes.",
    ...safetyFlags()
  };
}
function buildRankingSignals(args) {
  const proposalReady = args.outputs.some((output) => [
    "implementation_plan",
    "patch_plan",
    "review_notes",
    "validation_plan",
    "validation_evidence",
    "architecture_review",
    "ux_review",
    "workflow_review",
    "design_doc",
    "decision_options",
    "recommended_slice"
  ].includes(output.outputKind));
  const patchPreviewQuality = args.outputs.some((output) => output.outputKind === "patch_plan") ? args.score.completeness : 0;
  const highRisk = args.riskNotes.some((note) => /high|broad|violation|write|provider|network|spawn/i.test(note));
  const complianceViolations = uniqueStrings(args.overrides?.complianceViolations ?? args.riskNotes.filter((note) => note.startsWith("compliance_violation:")).map((note) => note.replace(/^compliance_violation:/, "")));
  const complianceNoWriteNoProvider = args.overrides?.complianceNoWriteNoProvider ?? !complianceViolations.some((violation) => ["writes", "apply_executed", "provider_calls"].includes(violation));
  const complianceNoNetwork = args.overrides?.complianceNoNetwork ?? !complianceViolations.includes("network_calls");
  const repeatedReadCount = Math.max(0, Math.floor(args.overrides?.repeatedReadCount ?? 0));
  const wastedReadPenalty = clamp01(args.overrides?.wastedReadPenalty ?? Math.min(0.5, repeatedReadCount * 0.1));
  const efficiency = clamp01(args.overrides?.efficiency ?? 1 - wastedReadPenalty - args.score.blockedPenalty);
  return {
    requiredRefRecall: clamp01(args.overrides?.requiredRefRecall ?? args.score.relevance),
    proposalSafetyQuality: clamp01(args.overrides?.proposalSafetyQuality ?? (proposalReady && !highRisk ? args.score.completeness : args.score.completeness * 0.6)),
    proposalReady: args.overrides?.proposalReady ?? proposalReady,
    patchPreviewQuality: clamp01(args.overrides?.patchPreviewQuality ?? patchPreviewQuality),
    proofRiskValidationStrength: clamp01(args.overrides?.proofRiskValidationStrength ?? Math.max(0, args.score.evidenceStrength - args.score.riskPenalty)),
    efficiency,
    tokenEstimate: args.overrides?.tokenEstimate,
    repeatedReadCount,
    wastedReadPenalty,
    complianceNoWriteNoProvider,
    complianceNoNetwork,
    noLiveCompliance: args.overrides?.noLiveCompliance ?? (complianceNoWriteNoProvider && complianceNoNetwork && complianceViolations.length === 0),
    complianceViolations,
    rationale: args.overrides?.rationale ?? "Deterministic ranking signals from required-ref recall, proposal quality, patch/proof/validation strength, efficiency, and no-live compliance.",
    ...safetyFlags()
  };
}
function summaryItem(result) {
  return {
    resultId: result.resultId,
    assignedRole: result.assignedRole,
    status: result.status,
    summary: result.summary,
    outputKinds: uniqueOutputKinds(result.outputs.map((output) => output.outputKind)),
    score: result.score.score,
    riskNotes: result.riskNotes,
    ...safetyFlags()
  };
}
function averageScore(scores, rationale) {
  if (scores.length === 0) {
    return {
      score: 0,
      confidence: 0,
      relevance: 0,
      completeness: 0,
      evidenceStrength: 0,
      riskPenalty: 0,
      blockedPenalty: 0,
      rationale,
      ...safetyFlags()
    };
  }
  return {
    score: average(scores.map((score) => score.score)),
    confidence: average(scores.map((score) => score.confidence)),
    relevance: average(scores.map((score) => score.relevance)),
    completeness: average(scores.map((score) => score.completeness)),
    evidenceStrength: average(scores.map((score) => score.evidenceStrength)),
    riskPenalty: average(scores.map((score) => score.riskPenalty)),
    blockedPenalty: average(scores.map((score) => score.blockedPenalty)),
    rationale,
    ...safetyFlags()
  };
}
function statusCounts(results) {
  return {
    completed: results.filter((result) => result.status === "completed").length,
    partial: results.filter((result) => result.status === "partial").length,
    blocked: results.filter((result) => result.status === "blocked").length,
    failed: results.filter((result) => result.status === "failed").length,
    not_run: results.filter((result) => result.status === "not_run").length
  };
}
function outputKindCounts(results) {
  const counts = {};
  for (const output of results.flatMap((result) => result.outputs)) {
    counts[output.outputKind] = (counts[output.outputKind] ?? 0) + 1;
  }
  return counts;
}
function compareResults(a, b) {
  return b.score.score - a.score.score || b.rankingSignals.requiredRefRecall - a.rankingSignals.requiredRefRecall || b.rankingSignals.proposalSafetyQuality - a.rankingSignals.proposalSafetyQuality || b.rankingSignals.proofRiskValidationStrength - a.rankingSignals.proofRiskValidationStrength || b.rankingSignals.efficiency - a.rankingSignals.efficiency || b.score.evidenceStrength - a.score.evidenceStrength || a.generatedAt - b.generatedAt;
}
function statusCompleteness(status) {
  switch (status) {
    case "completed":
      return 1;
    case "partial":
      return 0.65;
    case "blocked":
      return 0.25;
    case "failed":
      return 0.1;
    case "not_run":
      return 0;
  }
}
function evidenceStrengthFromOutputs(outputs) {
  if (outputs.length === 0)
    return 0;
  const refs = uniqueStrings(outputs.flatMap((output) => output.refs));
  return clamp01(refs.length / Math.max(outputs.length * 2, 1));
}
function noExecution() {
  return {
    attempted: false,
    providerCalls: false,
    networkCalls: false,
    processExecution: false,
    hiddenExecution: false,
    sourceReads: false,
    writes: false,
    sessionMutation: false
  };
}
function reportOnlyGuardrails() {
  return { ...RHEI_CODE_AGENT_REPORT_ONLY_GUARDRAILS_V1 };
}
function safetyFlags() {
  return {
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true,
    noProviderCalls: true,
    noWrites: true
  };
}
function uniqueOutputKinds(values) {
  return [...new Set(values)];
}
function uniqueById(values, idFor) {
  const output = [];
  const seen = new Set;
  for (const value of values) {
    if (!value)
      continue;
    const id = idFor(value);
    if (seen.has(id))
      continue;
    seen.add(id);
    output.push(value);
  }
  return output;
}
function uniqueStrings(values) {
  const output = [];
  const seen = new Set;
  for (const value of values) {
    const text = typeof value === "string" ? value.trim() : "";
    if (!text || seen.has(text))
      continue;
    seen.add(text);
    output.push(text);
  }
  return output;
}
function stableSlug(value) {
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 96) || "agent";
}
function clamp01(value) {
  if (Number.isNaN(value))
    return 0;
  return Math.max(0, Math.min(1, value));
}
function average(values) {
  if (values.length === 0)
    return 0;
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}
export {
  summarizeRheiCodeAgentResultsV1,
  rankRheiCodeAgentResultsV1,
  buildRheiCodeAgentResultV1,
  buildRheiCodeAgentHandoffV1,
  RHEI_CODE_AGENT_TOKEN_ESTIMATE_VERSION,
  RHEI_CODE_AGENT_SCHEMA_VERSION,
  RHEI_CODE_AGENT_ROLES_V1,
  RHEI_CODE_AGENT_RESULT_SUMMARY_KIND,
  RHEI_CODE_AGENT_RESULT_RANKING_KIND,
  RHEI_CODE_AGENT_RESULT_KIND,
  RHEI_CODE_AGENT_REPORT_ONLY_GUARDRAILS_V1,
  RHEI_CODE_AGENT_HANDOFF_KIND,
  RHEI_CODE_AGENT_DESIGN_OUTPUT_KINDS_V1
};
