// SPEC: PJ2026-0104010803 Workbench唯一投影 draft-2026-07-12-p0-admission-failure-identity.
// Responsibility: Typed pre-admission AgentRun failure classification regressions.

import assert from "node:assert/strict";
import { test } from "bun:test";

import { classifyCodeAgentDispatchFailure } from "./code-agent-dispatch-failure.ts";

test("classifies rollout-in-progress as an explicit retryable transient failure", () => {
  const failure = classifyCodeAgentDispatchFailure({
    failureKind: "rollout-in-progress",
    statusCode: 503,
    retryable: true,
    dispatchStage: "run-create"
  });

  assert.equal(failure.failureKind, "rollout-in-progress");
  assert.equal(failure.reason, "rollout-in-progress");
  assert.equal(failure.retryable, true);
  assert.equal(failure.recoveryAction, "wait-for-rollout");
  assert.match(failure.userMessage, /滚动更新/u);
});

test("classifies fixed diagnostic schema-invalid as permanent dispatcher/runtime misconfiguration", () => {
  const failure = classifyCodeAgentDispatchFailure({
    failureKind: "schema-invalid",
    statusCode: 400,
    retryable: false,
    dispatchStage: "command-create",
    runId: "run_fixed_trace",
    agentRunError: {
      failureKind: "schema-invalid",
      traceId: "trc_agentrun_upstream",
      message: "command schema rejected"
    }
  });

  assert.equal(failure.failureKind, "schema-invalid");
  assert.equal(failure.reason, "dispatcher-runtime-misconfigured");
  assert.equal(failure.retryable, false);
  assert.equal(failure.recoveryAction, "repair-agentrun-dispatch-contract");
  assert.equal(failure.runId, "run_fixed_trace");
  assert.equal(failure.commandId, null);
  assert.equal(failure.upstreamTraceId, "trc_agentrun_upstream");
  assert.match(failure.userMessage, /未进入实时事件流/u);
});

test("keeps provider/profile and unknown permanent failures distinguishable", () => {
  const profile = classifyCodeAgentDispatchFailure({ failureKind: "provider-profile-unconfigured", statusCode: 422, retryable: false });
  assert.equal(profile.reason, "provider-profile-unconfigured");
  assert.equal(profile.recoveryAction, "configure-provider-profile");
  assert.equal(profile.retryable, false);

  const unknown = classifyCodeAgentDispatchFailure({ failureKind: "new-manager-failure", statusCode: 418, retryable: false });
  assert.equal(unknown.failureKind, "new-manager-failure");
  assert.equal(unknown.reason, "unknown-dispatch-failure");
  assert.equal(unknown.recoveryAction, "inspect-agentrun-diagnostic");
  assert.equal(unknown.retryable, false);
  assert.match(unknown.userMessage, /未识别/u);
});
