import type {
  BoundedFixture,
  BoundedScenario,
  BudgetThresholdObservation,
  ChildProcessScenario,
  ConsumptionLimitScenario,
  ConsumptionObservation,
  WaitRetryObservation,
  WaitRetryScenario,
  BudgetThresholdScenario,
} from "../../../fixtures/bounded/types.js";

export type { BoundedFixture };

export const BOUNDED_CAPABILITY = "universal-bounded";

export type BoundedViolation = {
  scenarioId: string;
  kind: string;
  fact: string;
  details?: unknown;
  laneEligibility?: "blocking" | "blocking-eligible";
};

const CONSUMPTION_DIMENSIONS = new Set([
  "body-bytes",
  "item-count",
  "nesting-depth",
  "decompressed-size",
  "stream-duration",
  "log-retention",
  "retries",
  "fan-out",
]);

const TERMINAL_LOOP_STATES = new Set(["completed", "failed", "busy", "wedged", "none"]);

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null;
}

export function sanitizeForEvidence(value: unknown): unknown {
  if (typeof value === "number" && !Number.isFinite(value)) {
    return String(value);
  }
  if (Array.isArray(value)) {
    return value.map((entry) => sanitizeForEvidence(entry));
  }
  if (isRecord(value)) {
    return Object.fromEntries(
      Object.entries(value).map(([key, entry]) => [key, sanitizeForEvidence(entry)]),
    );
  }
  return value;
}

export function isRuleExcepted(fixture: BoundedFixture, rule: string): boolean {
  return fixture.intentionalException?.rules.includes(rule) ?? false;
}

function parseTypedTerminalFailure(
  value: unknown,
  path: string,
): ConsumptionObservation["typedTerminalFailure"] {
  if (value === undefined) {
    return undefined;
  }
  if (!isRecord(value)) {
    throw new Error(`${path} must be an object`);
  }
  if (typeof value.type !== "string" || value.type.trim().length === 0) {
    throw new Error(`${path}.type must be a non-empty string`);
  }
  if (typeof value.observed !== "boolean") {
    throw new Error(`${path}.observed must be a boolean`);
  }
  return {
    type: value.type,
    observed: value.observed,
  };
}

function parseConsumptionObservation(value: unknown, index: number): ConsumptionObservation {
  if (!isRecord(value)) {
    throw new Error(`observations[${String(index)}] must be an object`);
  }
  if (typeof value.dimension !== "string" || !CONSUMPTION_DIMENSIONS.has(value.dimension)) {
    throw new Error(`observations[${String(index)}].dimension is invalid`);
  }
  if (typeof value.declaredLimit !== "number" || !Number.isFinite(value.declaredLimit)) {
    throw new Error(`observations[${String(index)}].declaredLimit must be a finite number`);
  }
  if (typeof value.peakObserved !== "number" || !Number.isFinite(value.peakObserved)) {
    throw new Error(`observations[${String(index)}].peakObserved must be a finite number`);
  }
  if (typeof value.limitEnforcedDuringConsumption !== "boolean") {
    throw new Error(
      `observations[${String(index)}].limitEnforcedDuringConsumption must be a boolean`,
    );
  }
  if (typeof value.rejectedAtConsumption !== "boolean") {
    throw new Error(`observations[${String(index)}].rejectedAtConsumption must be a boolean`);
  }

  const typedTerminalFailure = parseTypedTerminalFailure(
    value.typedTerminalFailure,
    `observations[${String(index)}].typedTerminalFailure`,
  );

  return {
    dimension: value.dimension as ConsumptionObservation["dimension"],
    declaredLimit: value.declaredLimit,
    peakObserved: value.peakObserved,
    limitEnforcedDuringConsumption: value.limitEnforcedDuringConsumption,
    rejectedAtConsumption: value.rejectedAtConsumption,
    ...(typedTerminalFailure !== undefined ? { typedTerminalFailure } : {}),
  };
}

function parseConsumptionLimitScenario(
  value: Record<string, unknown>,
  index: number,
): ConsumptionLimitScenario {
  if (!Array.isArray(value.observations) || value.observations.length === 0) {
    throw new Error(`scenarios[${String(index)}].observations must be a non-empty array`);
  }
  return {
    scenarioId: typeof value.scenarioId === "string" ? value.scenarioId : "",
    kind: "consumption-limit",
    observations: value.observations.map((observation, observationIndex) =>
      parseConsumptionObservation(observation, observationIndex),
    ),
  };
}

function parseWaitRetryObservation(value: unknown, index: number): WaitRetryObservation {
  if (!isRecord(value)) {
    throw new Error(`scenarios[${String(index)}].observation must be an object`);
  }
  if (value.loopKind !== "wait" && value.loopKind !== "retry") {
    throw new Error(`scenarios[${String(index)}].observation.loopKind must be wait or retry`);
  }
  if (
    value.boundedProgressRule !== undefined &&
    (typeof value.boundedProgressRule !== "string" || value.boundedProgressRule.trim().length === 0)
  ) {
    throw new Error(
      `scenarios[${String(index)}].observation.boundedProgressRule must be a non-empty string`,
    );
  }
  if (
    value.maxAttempts !== undefined &&
    (typeof value.maxAttempts !== "number" || !Number.isFinite(value.maxAttempts))
  ) {
    throw new Error(`scenarios[${String(index)}].observation.maxAttempts must be a finite number`);
  }
  if (
    value.maxWaitMs !== undefined &&
    (typeof value.maxWaitMs !== "number" || !Number.isFinite(value.maxWaitMs))
  ) {
    throw new Error(`scenarios[${String(index)}].observation.maxWaitMs must be a finite number`);
  }
  if (
    typeof value.attemptsObserved !== "number" ||
    (!Number.isFinite(value.attemptsObserved) && value.attemptsObserved !== Number.POSITIVE_INFINITY)
  ) {
    throw new Error(`scenarios[${String(index)}].observation.attemptsObserved must be a number`);
  }
  if (typeof value.elapsedMs !== "number" || !Number.isFinite(value.elapsedMs)) {
    throw new Error(`scenarios[${String(index)}].observation.elapsedMs must be a finite number`);
  }
  if (typeof value.cancellationPathAvailable !== "boolean") {
    throw new Error(
      `scenarios[${String(index)}].observation.cancellationPathAvailable must be a boolean`,
    );
  }
  if (
    typeof value.terminalState !== "string" ||
    !TERMINAL_LOOP_STATES.has(value.terminalState)
  ) {
    throw new Error(`scenarios[${String(index)}].observation.terminalState is invalid`);
  }
  if (typeof value.terminalFailureTyped !== "boolean") {
    throw new Error(
      `scenarios[${String(index)}].observation.terminalFailureTyped must be a boolean`,
    );
  }
  if (
    value.failureType !== undefined &&
    (typeof value.failureType !== "string" || value.failureType.trim().length === 0)
  ) {
    throw new Error(`scenarios[${String(index)}].observation.failureType must be a non-empty string`);
  }
  if (typeof value.statesDistinct !== "boolean") {
    throw new Error(`scenarios[${String(index)}].observation.statesDistinct must be a boolean`);
  }

  return {
    loopKind: value.loopKind,
    ...(typeof value.boundedProgressRule === "string"
      ? { boundedProgressRule: value.boundedProgressRule }
      : {}),
    ...(typeof value.maxAttempts === "number" ? { maxAttempts: value.maxAttempts } : {}),
    ...(typeof value.maxWaitMs === "number" ? { maxWaitMs: value.maxWaitMs } : {}),
    attemptsObserved: value.attemptsObserved,
    elapsedMs: value.elapsedMs,
    cancellationPathAvailable: value.cancellationPathAvailable,
    terminalState: value.terminalState as WaitRetryObservation["terminalState"],
    terminalFailureTyped: value.terminalFailureTyped,
    ...(typeof value.failureType === "string" ? { failureType: value.failureType } : {}),
    statesDistinct: value.statesDistinct,
  };
}

function parseWaitRetryScenario(value: Record<string, unknown>, index: number): WaitRetryScenario {
  return {
    scenarioId: typeof value.scenarioId === "string" ? value.scenarioId : "",
    kind: "wait-retry",
    observation: parseWaitRetryObservation(value.observation, index),
  };
}

function parseDeclaredInheritance(value: unknown, path: string): ChildProcessScenario["declared"] {
  if (!isRecord(value)) {
    throw new Error(`${path} must be an object`);
  }
  if (!Array.isArray(value.descriptors) || value.descriptors.some((entry) => typeof entry !== "number")) {
    throw new Error(`${path}.descriptors must be a number array`);
  }
  if (
    !Array.isArray(value.environmentKeys) ||
    value.environmentKeys.some((entry) => typeof entry !== "string")
  ) {
    throw new Error(`${path}.environmentKeys must be a string array`);
  }
  if (
    value.signals !== undefined &&
    (!Array.isArray(value.signals) || value.signals.some((entry) => typeof entry !== "string"))
  ) {
    throw new Error(`${path}.signals must be a string array`);
  }
  if (typeof value.workingDirectory !== "string" || value.workingDirectory.trim().length === 0) {
    throw new Error(`${path}.workingDirectory must be a non-empty string`);
  }
  if (
    (typeof value.processGroup !== "string" || value.processGroup.trim().length === 0) &&
  typeof value.processGroup !== "number"
  ) {
    throw new Error(`${path}.processGroup must be a non-empty string or number`);
  }

  return {
    descriptors: value.descriptors.filter((entry): entry is number => typeof entry === "number"),
    environmentKeys: value.environmentKeys.filter((entry): entry is string => typeof entry === "string"),
    ...(Array.isArray(value.signals)
      ? { signals: value.signals.filter((entry): entry is string => typeof entry === "string") }
      : {}),
    workingDirectory: value.workingDirectory,
    processGroup: value.processGroup,
  };
}

function parseObservedInheritance(value: unknown, path: string): ChildProcessScenario["observed"] {
  if (!isRecord(value)) {
    throw new Error(`${path} must be an object`);
  }
  if (!Array.isArray(value.descriptors) || value.descriptors.some((entry) => typeof entry !== "number")) {
    throw new Error(`${path}.descriptors must be a number array`);
  }
  if (!isRecord(value.environment)) {
    throw new Error(`${path}.environment must be an object`);
  }
  if (
    value.signals !== undefined &&
    (!Array.isArray(value.signals) || value.signals.some((entry) => typeof entry !== "string"))
  ) {
    throw new Error(`${path}.signals must be a string array`);
  }
  if (typeof value.workingDirectory !== "string" || value.workingDirectory.trim().length === 0) {
    throw new Error(`${path}.workingDirectory must be a non-empty string`);
  }
  if (
    (typeof value.processGroup !== "string" || value.processGroup.trim().length === 0) &&
    typeof value.processGroup !== "number"
  ) {
    throw new Error(`${path}.processGroup must be a non-empty string or number`);
  }

  const environment: Record<string, string> = {};
  for (const [key, entry] of Object.entries(value.environment)) {
    if (typeof entry !== "string") {
      throw new Error(`${path}.environment.${key} must be a string`);
    }
    environment[key] = entry;
  }

  return {
    descriptors: value.descriptors.filter((entry): entry is number => typeof entry === "number"),
    environment,
    ...(Array.isArray(value.signals)
      ? { signals: value.signals.filter((entry): entry is string => typeof entry === "string") }
      : {}),
    workingDirectory: value.workingDirectory,
    processGroup: value.processGroup,
  };
}

function parseChildProcessScenario(value: Record<string, unknown>, index: number): ChildProcessScenario {
  return {
    scenarioId: typeof value.scenarioId === "string" ? value.scenarioId : "",
    kind: "child-process",
    declared: parseDeclaredInheritance(value.declared, `scenarios[${String(index)}].declared`),
    observed: parseObservedInheritance(value.observed, `scenarios[${String(index)}].observed`),
  };
}

function parseBudgetThresholdObservation(
  value: unknown,
  path: string,
): BudgetThresholdObservation {
  if (!isRecord(value)) {
    throw new Error(`${path} must be an object`);
  }
  if (typeof value.violationClass !== "string") {
    throw new Error(`${path}.violationClass must be a string`);
  }
  if (typeof value.resourceKind !== "string" || value.resourceKind.trim().length === 0) {
    throw new Error(`${path}.resourceKind must be a non-empty string`);
  }

  switch (value.violationClass) {
    case "threshold-exceeded": {
      if (typeof value.observedValue !== "number" || !Number.isFinite(value.observedValue)) {
        throw new Error(`${path}.observedValue must be a finite number`);
      }
      if (typeof value.declaredThreshold !== "number" || !Number.isFinite(value.declaredThreshold)) {
        throw new Error(`${path}.declaredThreshold must be a finite number`);
      }
      if (typeof value.environmentContractConfirmed !== "boolean") {
        throw new Error(`${path}.environmentContractConfirmed must be a boolean`);
      }
      return {
        violationClass: "threshold-exceeded",
        resourceKind: value.resourceKind,
        observedValue: value.observedValue,
        declaredThreshold: value.declaredThreshold,
        environmentContractConfirmed: value.environmentContractConfirmed,
      };
    }
    case "unbounded-growth": {
      if (typeof value.growthBounded !== "boolean") {
        throw new Error(`${path}.growthBounded must be a boolean`);
      }
      return {
        violationClass: "unbounded-growth",
        resourceKind: value.resourceKind,
        growthBounded: value.growthBounded,
      };
    }
    case "integer-overflow": {
      if (typeof value.observedValue !== "number" || !Number.isFinite(value.observedValue)) {
        throw new Error(`${path}.observedValue must be a finite number`);
      }
      if (typeof value.overflowDetected !== "boolean") {
        throw new Error(`${path}.overflowDetected must be a boolean`);
      }
      return {
        violationClass: "integer-overflow",
        resourceKind: value.resourceKind,
        observedValue: value.observedValue,
        overflowDetected: value.overflowDetected,
      };
    }
    case "leaked-ownership": {
      if (
        typeof value.resourceIdentifier !== "string" ||
        value.resourceIdentifier.trim().length === 0
      ) {
        throw new Error(`${path}.resourceIdentifier must be a non-empty string`);
      }
      if (typeof value.ownerReleased !== "boolean") {
        throw new Error(`${path}.ownerReleased must be a boolean`);
      }
      return {
        violationClass: "leaked-ownership",
        resourceKind: value.resourceKind,
        resourceIdentifier: value.resourceIdentifier,
        ownerReleased: value.ownerReleased,
      };
    }
    default:
      throw new Error(`unsupported budget-threshold violation class: ${value.violationClass}`);
  }
}

function parseBudgetThresholdScenario(
  value: Record<string, unknown>,
  index: number,
): BudgetThresholdScenario {
  return {
    scenarioId: typeof value.scenarioId === "string" ? value.scenarioId : "",
    kind: "budget-threshold",
    observation: parseBudgetThresholdObservation(
      value.observation,
      `scenarios[${String(index)}].observation`,
    ),
  };
}

function parseScenario(value: unknown, index: number): BoundedScenario {
  if (!isRecord(value)) {
    throw new Error(`scenarios[${String(index)}] must be an object`);
  }
  if (typeof value.scenarioId !== "string" || value.scenarioId.trim().length === 0) {
    throw new Error(`scenarios[${String(index)}].scenarioId must be a non-empty string`);
  }
  if (typeof value.kind !== "string") {
    throw new Error(`scenarios[${String(index)}].kind must be a string`);
  }

  switch (value.kind) {
    case "consumption-limit":
      return parseConsumptionLimitScenario(value, index);
    case "wait-retry":
      return parseWaitRetryScenario(value, index);
    case "child-process":
      return parseChildProcessScenario(value, index);
    case "budget-threshold":
      return parseBudgetThresholdScenario(value, index);
    default:
      throw new Error(`unsupported scenario kind: ${value.kind}`);
  }
}

export function parseBoundedFixture(input: unknown): BoundedFixture {
  if (!isRecord(input)) {
    throw new Error("bounded fixture must be an object");
  }
  if (typeof input.fixtureId !== "string" || input.fixtureId.trim().length === 0) {
    throw new Error("fixtureId must be a non-empty string");
  }
  if (typeof input.boundedVersion !== "string" || input.boundedVersion.trim().length === 0) {
    throw new Error("boundedVersion must be a non-empty string");
  }
  if (!Array.isArray(input.scenarios) || input.scenarios.length === 0) {
    throw new Error("scenarios must be a non-empty array");
  }

  const fixture: BoundedFixture = {
    fixtureId: input.fixtureId,
    boundedVersion: input.boundedVersion,
    scenarios: input.scenarios.map((scenario, index) => parseScenario(scenario, index)),
  };

  if (isRecord(input.intentionalException)) {
    const rules = input.intentionalException.rules;
    const reason = input.intentionalException.reason;
    if (!Array.isArray(rules) || rules.some((rule) => typeof rule !== "string")) {
      throw new Error("intentionalException.rules must be a string array");
    }
    const parsedRules = rules.filter((rule): rule is string => typeof rule === "string");
    if (parsedRules.length !== rules.length) {
      throw new Error("intentionalException.rules must be a string array");
    }
    if (typeof reason !== "string" || reason.trim().length === 0) {
      throw new Error("intentionalException.reason must be a non-empty string");
    }
    fixture.intentionalException = { rules: parsedRules, reason };
  }

  return fixture;
}

function hasBoundedProgress(observation: WaitRetryObservation): boolean {
  return (
    observation.boundedProgressRule !== undefined ||
    observation.maxAttempts !== undefined ||
    observation.maxWaitMs !== undefined
  );
}

function limitExceeded(observation: ConsumptionObservation): boolean {
  return observation.peakObserved > observation.declaredLimit;
}

export function detectUni050Violations(scenario: BoundedScenario): BoundedViolation[] {
  if (scenario.kind !== "consumption-limit") {
    return [];
  }

  const violations: BoundedViolation[] = [];

  for (const observation of scenario.observations) {
    if (!observation.limitEnforcedDuringConsumption) {
      violations.push({
        scenarioId: scenario.scenarioId,
        kind: "post-buffer-limit",
        fact: `${observation.dimension} limit was enforced after buffering instead of during consumption`,
        details: sanitizeForEvidence(observation),
      });
      continue;
    }

    if (limitExceeded(observation) && !observation.rejectedAtConsumption) {
      violations.push({
        scenarioId: scenario.scenarioId,
        kind: "limit-not-enforced-during-consumption",
        fact: `${observation.dimension} exceeded declared limit without rejection during consumption`,
        details: sanitizeForEvidence(observation),
      });
    }

    if (
      limitExceeded(observation) &&
      observation.typedTerminalFailure !== undefined &&
      !observation.typedTerminalFailure.observed
    ) {
      violations.push({
        scenarioId: scenario.scenarioId,
        kind: "missing-typed-terminal-failure",
        fact: `${observation.dimension} limit breach lacked observable typed terminal failure`,
        details: sanitizeForEvidence(observation),
      });
    }
  }

  return violations;
}

export function detectUni052Violations(scenario: BoundedScenario): BoundedViolation[] {
  if (scenario.kind !== "wait-retry") {
    return [];
  }

  const violations: BoundedViolation[] = [];
  const observation = scenario.observation;

  if (!hasBoundedProgress(observation)) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "unbounded-progress",
      fact: `${observation.loopKind} loop lacked bounded progress rule`,
      details: sanitizeForEvidence(observation),
    });
  }

  if (!observation.cancellationPathAvailable) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "missing-cancellation-path",
      fact: `${observation.loopKind} loop lacked a cancellation path`,
      details: sanitizeForEvidence(observation),
    });
  }

  if (
    observation.maxAttempts !== undefined &&
    observation.attemptsObserved > observation.maxAttempts
  ) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "attempt-budget-exceeded",
      fact: `${observation.loopKind} loop exceeded declared attempt budget`,
      details: sanitizeForEvidence(observation),
    });
  }

  if (observation.maxWaitMs !== undefined && observation.elapsedMs > observation.maxWaitMs) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "wait-budget-exceeded",
      fact: `${observation.loopKind} loop exceeded declared wait budget`,
      details: sanitizeForEvidence(observation),
    });
  }

  if (!observation.statesDistinct) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "indistinct-terminal-states",
      fact: "busy, wedged, and completed states were not distinct",
      details: sanitizeForEvidence(observation),
    });
  }

  const requiresTypedFailure =
    observation.terminalState === "failed" ||
    observation.terminalState === "wedged" ||
    observation.terminalState === "none" ||
    observation.terminalState === "busy";

  if (requiresTypedFailure && !observation.terminalFailureTyped) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "missing-terminal-failure",
      fact: `${observation.loopKind} loop terminated without observable typed failure`,
      details: sanitizeForEvidence(observation),
    });
  }

  if (
    observation.terminalState === "none" &&
    observation.maxAttempts !== undefined &&
    observation.attemptsObserved >= observation.maxAttempts
  ) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "non-terminal-loop",
      fact: `${observation.loopKind} loop exhausted its budget without reaching a terminal state`,
      details: sanitizeForEvidence(observation),
    });
  }

  return violations;
}

function undeclaredEntries<T>(declared: T[], observed: T[]): T[] {
  const declaredSet = new Set(declared);
  return observed.filter((entry) => !declaredSet.has(entry));
}

export function detectUni053Violations(scenario: BoundedScenario): BoundedViolation[] {
  if (scenario.kind !== "child-process") {
    return [];
  }

  const violations: BoundedViolation[] = [];
  const { declared, observed } = scenario;

  const extraDescriptors = undeclaredEntries(declared.descriptors, observed.descriptors);
  if (extraDescriptors.length > 0) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "undeclared-descriptor",
      fact: "child process inherited undeclared file descriptors",
      details: sanitizeForEvidence({ extraDescriptors, declared, observed }),
    });
  }

  const observedEnvKeys = Object.keys(observed.environment);
  const extraEnvKeys = undeclaredEntries(declared.environmentKeys, observedEnvKeys);
  if (extraEnvKeys.length > 0) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "undeclared-environment",
      fact: "child process inherited undeclared environment variables",
      details: sanitizeForEvidence({ extraEnvKeys, declared, observed }),
    });
  }

  const declaredSignals = declared.signals ?? [];
  const observedSignals = observed.signals ?? [];
  const extraSignals = undeclaredEntries(declaredSignals, observedSignals);
  if (extraSignals.length > 0) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "undeclared-signal",
      fact: "child process inherited undeclared signal handlers",
      details: sanitizeForEvidence({ extraSignals, declared, observed }),
    });
  }

  if (observed.workingDirectory !== declared.workingDirectory) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "undeclared-working-directory",
      fact: "child process working directory did not match declared inheritance",
      details: sanitizeForEvidence({
        declared: declared.workingDirectory,
        observed: observed.workingDirectory,
      }),
    });
  }

  if (observed.processGroup !== declared.processGroup) {
    violations.push({
      scenarioId: scenario.scenarioId,
      kind: "undeclared-process-group",
      fact: "child process process-group membership did not match declared inheritance",
      details: sanitizeForEvidence({
        declared: declared.processGroup,
        observed: observed.processGroup,
      }),
    });
  }

  return violations;
}

export function detectUni054Violations(scenario: BoundedScenario): BoundedViolation[] {
  if (scenario.kind !== "budget-threshold") {
    return [];
  }

  const violations: BoundedViolation[] = [];
  const { observation } = scenario;

  switch (observation.violationClass) {
    case "threshold-exceeded": {
      if (
        observation.observedValue > observation.declaredThreshold &&
        !observation.environmentContractConfirmed
      ) {
        violations.push({
          scenarioId: scenario.scenarioId,
          kind: "threshold-exceeded-without-contract",
          fact: `${observation.resourceKind} exceeded declared threshold without confirmed environment contract`,
          details: sanitizeForEvidence(observation),
          laneEligibility: "blocking-eligible",
        });
      }
      break;
    }
    case "unbounded-growth": {
      if (!observation.growthBounded) {
        violations.push({
          scenarioId: scenario.scenarioId,
          kind: "unbounded-growth",
          fact: `${observation.resourceKind} grew without bound`,
          details: sanitizeForEvidence(observation),
          laneEligibility: "blocking",
        });
      }
      break;
    }
    case "integer-overflow": {
      if (observation.overflowDetected) {
        violations.push({
          scenarioId: scenario.scenarioId,
          kind: "integer-overflow",
          fact: `${observation.resourceKind} counter overflowed without arbitrary threshold`,
          details: sanitizeForEvidence(observation),
          laneEligibility: "blocking",
        });
      }
      break;
    }
    case "leaked-ownership": {
      if (!observation.ownerReleased) {
        violations.push({
          scenarioId: scenario.scenarioId,
          kind: "leaked-ownership",
          fact: `${observation.resourceKind} ownership leaked for ${observation.resourceIdentifier}`,
          details: sanitizeForEvidence(observation),
          laneEligibility: "blocking",
        });
      }
      break;
    }
    default: {
      const exhaustive: never = observation;
      throw new Error(`unsupported budget-threshold observation: ${String(exhaustive)}`);
    }
  }

  return violations;
}
