// 重构前 index.ts 只读参考：commit 6a04144d3f5103014f75b637d7e6bc2f45bf007f，blob 56e590c1a6b5ca7ad128bf2c992f60e46c355a58；可用 `git show 6a04144d3f5103014f75b637d7e6bc2f45bf007f:src/components/microservices/code-queue/src/index.ts` 查看。

import { minimaxM27Model } from "./code-agent/common";
import { openCodeTransportClosedBeforeTerminal, remoteOpenCodeRunCommandForTest } from "./code-agent/opencode";
import { applyJudgeSafetyOverridesForTest, continuePromptSourceBudgetChars, miniMaxJudgeMessages, parsedContinuePromptForJudge, parseJudgeJson, queueRecoveryRetryPrompt, retryPrompt } from "./judge";
import { codeQueueEnvironmentHintTitle, injectCodeQueueEnvironmentHint, promptWithCodeQueueEnvironmentHint, userPromptForDisplay } from "./prompts";
import { buildTaskTranscript, safePreview, taskTraceSummaryFixtureResponse, transcriptLineSummaryLines } from "./task-view";
import type { ActiveRunSlotWaiter } from "./code-agent/common";
import type { OaTraceStepSummary } from "./oa-events";
import type { JsonValue, LiveOutput, QueueTask, QueuedStatusReason, QueueTaskRequest, RuntimeConfig, SchedulerActiveRunHeartbeat, TaskStatus } from "./types";

export interface SelfTestsContext {
  config: Pick<RuntimeConfig, "defaultModel" | "defaultReasoningEffort" | "defaultWorkdir" | "mainProviderId" | "maxActiveQueues">;
  activeRunSlotCount: () => number;
  activeRunSlotReservations: Set<string>;
  activeRunSlotWaiters: ActiveRunSlotWaiter[];
  availableQueueStartSlotsFor: (activeSlotCount: number, maxActiveQueues?: number) => number;
  defaultQueueId: string;
  enqueueActiveRunSlotWaiter: (task: QueueTask) => ActiveRunSlotWaiter;
  injectReferencedTaskContext: (request: QueueTaskRequest, finder?: (id: string) => QueueTask | null | Promise<QueueTask | null>, injectedAt?: string) => Promise<QueueTaskRequest>;
  moveTaskToQueueForTest: (task: QueueTask, req: Request) => Promise<Response>;
  nextRunnableTaskFrom: (queueId: string, tasks?: QueueTask[]) => QueueTask | null;
  normalizeTask: (task: QueueTask) => QueueTask;
  nowIso: () => string;
  processingQueues: Set<string>;
  queueActiveTasksForRestartRetry: (reason: string, method: string, options?: { onlyActiveRuns?: boolean; taskIds?: Set<string> }) => number;
  queueHeadTask: (queueId: string, tasks?: QueueTask[]) => QueueTask | null;
  queuedStatusReason: (task: QueueTask, tasks?: QueueTask[]) => QueuedStatusReason | null;
  removeActiveRunSlotWaiter: (waiter: ActiveRunSlotWaiter) => void;
  resolveReasoningEffort: (model: string, explicit?: string | null) => string | null;
  runDatabaseClaimMoveSelfTest?: () => Promise<JsonValue | null>;
  runTraceSummaryContractSelfTest?: () => JsonValue;
  staleActiveRecoverySelfTest: () => Promise<JsonValue>;
  taskIsRecoverableOrphanedActive: (task: QueueTask, staleMs?: number) => boolean;
  tasks: () => QueueTask[];
  updateProcessingFlag: () => void;
}

let context: SelfTestsContext | null = null;

export function configureSelfTests(runtimeContext: SelfTestsContext): void {
  context = runtimeContext;
}

function ctx(): SelfTestsContext {
  if (context === null) throw new Error("self-tests module is not configured");
  return context;
}

function terminalTask(task: QueueTask): boolean {
  return task.status === "succeeded" || task.status === "failed" || task.status === "canceled";
}

function testTask(id: string, prompt: string, finalResponse: string, referenceTaskIds: string[] = [], createdAt = ctx().nowIso()): QueueTask {
  return ctx().normalizeTask({
    id,
    queueId: ctx().defaultQueueId,
    queueEnteredAt: createdAt,
    prompt,
    basePrompt: prompt,
    referenceTaskIds,
    referenceInjection: null,
    providerId: ctx().config.mainProviderId,
    cwd: ctx().config.defaultWorkdir,
    model: ctx().config.defaultModel,
    reasoningEffort: ctx().resolveReasoningEffort(ctx().config.defaultModel, ctx().config.defaultReasoningEffort),
    executionMode: "default",
    maxAttempts: 1,
    status: "succeeded",
    createdAt,
    updatedAt: createdAt,
    startedAt: createdAt,
    finishedAt: createdAt,
    readAt: null,
    currentAttempt: 1,
    currentMode: "initial",
    codexThreadId: null,
    activeTurnId: null,
    finalResponse,
    lastError: null,
    lastJudge: null,
    judgeFailCount: 0,
    promptHistory: [],
    output: finalResponse.length > 0 ? [{ seq: 1, at: createdAt, channel: "assistant", text: finalResponse, method: "item/agentMessage" }] : [],
    events: [],
    attempts: [],
    cancelRequested: false,
    nextPrompt: null,
    nextMode: null,
  });
}

function assertReferenceTest(condition: boolean, message: string): void {
  if (!condition) throw new Error(message);
}

function traceSelfTestTask(): QueueTask {
  const basePrompt = "Trace sync contract fixture";
  const at = "2026-05-19T00:00:00.000Z";
  return ctx().normalizeTask({
    id: "codex_trace_sync_fixture",
    queueId: ctx().defaultQueueId,
    queueEnteredAt: at,
    prompt: basePrompt,
    basePrompt,
    referenceTaskIds: [],
    referenceInjection: null,
    providerId: ctx().config.mainProviderId,
    cwd: ctx().config.defaultWorkdir,
    model: ctx().config.defaultModel,
    reasoningEffort: ctx().resolveReasoningEffort(ctx().config.defaultModel, ctx().config.defaultReasoningEffort),
    executionMode: "default",
    maxAttempts: 2,
    status: "running",
    createdAt: at,
    updatedAt: "2026-05-19T00:05:00.000Z",
    startedAt: at,
    finishedAt: null,
    readAt: null,
    currentAttempt: 2,
    currentMode: "retry",
    codexThreadId: "thread_trace_sync_fixture",
    activeTurnId: "turn_trace_sync_fixture",
    finalResponse: "",
    lastError: null,
    lastJudge: null,
    judgeFailCount: 0,
    promptHistory: [],
    output: [
      { seq: 1, at, channel: "user", text: basePrompt, method: "enqueue" },
      { seq: 2, at: "2026-05-19T00:01:00.000Z", channel: "command", text: "attempt 1 / 2\nrg src/components/microservices/code-queue/src/task-view.ts", method: "item/started", itemId: "call-1" },
      { seq: 3, at: "2026-05-19T00:01:30.000Z", channel: "assistant", text: "Attempt 1 judge complete.", method: "judge" },
    ],
    events: [],
    attempts: [
      {
        index: 1,
        mode: "initial",
        startedAt: "2026-05-19T00:00:05.000Z",
        finishedAt: "2026-05-19T00:02:00.000Z",
        terminalStatus: "completed",
        transportClosedBeforeTerminal: false,
        appServerExitCode: 0,
        appServerSignal: null,
        error: null,
        finalResponse: "Attempt 1 answer",
        finalResponsePreview: "Attempt 1 answer",
        finalResponseChars: 16,
        stderrTail: "",
        judge: { decision: "complete", confidence: 1, reason: "attempt 1 ok", source: "fallback" },
        judgeAt: "2026-05-19T00:02:00.000Z",
        judgeSeq: 3,
        outputStartSeq: 2,
        outputEndSeq: 3,
      },
    ],
    cancelRequested: false,
    nextPrompt: null,
    nextMode: null,
  });
}

function traceSyncAttemptSteps(): Map<number, OaTraceStepSummary[]> {
  const attempt2: OaTraceStepSummary[] = [
    { eventSequence: 20, seq: 20, at: "2026-05-19T00:06:00.000Z", kind: "ran", title: "Run", status: "item/started", summaryLines: ["attempt 2 / 2", "pnpm test"], rawSeqs: [20], scopeId: "task:codex_trace_sync_fixture:attempt:2", attemptIndex: 2, source: "oa-event-flow" },
    { eventSequence: 21, seq: 21, at: "2026-05-19T00:06:20.000Z", kind: "explored", title: "Read", status: "item/completed", summaryLines: ["src/components/microservices/code-queue/src/task-view.ts"], rawSeqs: [21], scopeId: "task:codex_trace_sync_fixture:attempt:2", attemptIndex: 2, source: "oa-event-flow" },
  ];
  return new Map([[2, attempt2]]);
}

function traceSyncAllSteps(): OaTraceStepSummary[] {
  return [
    { eventSequence: 1, seq: 1, at: "2026-05-19T00:00:10.000Z", kind: "message", title: "Assistant message", status: "item/completed", summaryLines: ["Judge complete for attempt 1"], rawSeqs: [3], scopeId: "task:codex_trace_sync_fixture", attemptIndex: null, source: "oa-event-flow" },
    { eventSequence: 20, seq: 20, at: "2026-05-19T00:06:00.000Z", kind: "ran", title: "Run", status: "item/started", summaryLines: ["attempt 2 / 2", "pnpm test"], rawSeqs: [20], scopeId: "task:codex_trace_sync_fixture:attempt:2", attemptIndex: 2, source: "oa-event-flow" },
    { eventSequence: 21, seq: 21, at: "2026-05-19T00:06:20.000Z", kind: "explored", title: "Read", status: "item/completed", summaryLines: ["src/components/microservices/code-queue/src/task-view.ts"], rawSeqs: [21], scopeId: "task:codex_trace_sync_fixture:attempt:2", attemptIndex: 2, source: "oa-event-flow" },
  ];
}

function runTraceSummaryContractSelfTest(): JsonValue {
  const task = traceSelfTestTask();
  const summary = taskTraceSummaryFixtureResponse(task, {
    stats: null,
    taskStats: null,
    allSteps: traceSyncAllSteps(),
    attemptSteps: traceSyncAttemptSteps(),
  }) as Record<string, unknown>;
  const attempts = Array.isArray(summary.attempts) ? summary.attempts as Record<string, unknown>[] : [];
  const currentAttempt = attempts.find((attempt) => Number(attempt.index) === 2) ?? null;
  assertReferenceTest(String(summary.statsSource || "").startsWith("raw-trace"), "trace summary should surface raw-trace fallback state");
  assertReferenceTest(summary.traceStatsReason === "oa-event-flow-stats-unavailable-raw-trace-present", "trace summary should explain degraded sync");
  assertReferenceTest(summary.traceStatsState === "degraded", "trace summary should mark degraded sync state");
  assertReferenceTest(Number(summary.stepCount ?? 0) > 0, "trace summary should expose fallback step count");
  assertReferenceTest(Array.isArray(attempts) && attempts.length >= 2, "trace summary should materialize latest running attempt");
  assertReferenceTest(Number(currentAttempt?.index ?? 0) === 2, "trace summary should include attempt 2");
  assertReferenceTest(Number(currentAttempt?.stepCount ?? 0) > 0, "attempt 2 should expose a live step count");
  assertReferenceTest(String(currentAttempt?.statsSource || "") === "raw-trace-fallback" || String(currentAttempt?.statsSource || "") === "oa-event-flow", "attempt 2 should not be permanently unavailable");
  assertReferenceTest(String(currentAttempt?.traceStatsState || "") === "degraded" || String(currentAttempt?.traceStatsState || "") === "ready", "attempt 2 should surface a visible sync state");
  return {
    ok: true,
    taskId: task.id,
    statsSource: String(summary.statsSource || ""),
    traceStatsState: String(summary.traceStatsState || ""),
    traceStatsReason: String(summary.traceStatsReason || ""),
    stepCount: Number(summary.stepCount ?? 0),
    attempt2: currentAttempt as JsonValue,
  };
}

async function runReferenceInjectionSelfTest(): Promise<JsonValue> {
  const at = "2026-05-08T00:00:00.000Z";
  const taskA = testTask("codex_1000_aaaaaa", "A base prompt", "A final", [], at);
  const injectedB = await ctx().injectReferencedTaskContext({
    prompt: "引用 Code Queue 任务 codex_1000_aaaaaa。\n\n本次任务：\nB user prompt",
    referenceTaskIds: [taskA.id],
  }, (id) => id === taskA.id ? taskA : null, "2026-05-08T00:01:00.000Z");
  const taskB = testTask("codex_1001_bbbbbb", injectedB.prompt, "B final", injectedB.referenceTaskIds, "2026-05-08T00:02:00.000Z");
  taskB.basePrompt = injectedB.basePrompt ?? "";
  taskB.referenceInjection = injectedB.referenceInjection ?? null;
  const injectedC = await ctx().injectReferencedTaskContext({
    prompt: "C user prompt",
    referenceTaskIds: [taskB.id],
  }, (id) => id === taskA.id ? taskA : id === taskB.id ? taskB : null, "2026-05-08T00:03:00.000Z");
  const promptC = injectedC.prompt;
  const hintedC = injectCodeQueueEnvironmentHint(injectedC);
  assertReferenceTest(injectedB.basePrompt === "B user prompt", "B basePrompt should strip frontend reference hint");
  assertReferenceTest(taskB.referenceInjection?.items.length === 1, "B should have one reference item");
  assertReferenceTest(injectedC.basePrompt === "C user prompt", "C basePrompt should be raw C prompt");
  assertReferenceTest((injectedC.referenceInjection?.items.length ?? 0) === 2, "C should include B and A as two structured graph items");
  assertReferenceTest(hintedC.prompt.startsWith(codeQueueEnvironmentHintTitle), "C should include the Code Queue environment hint");
  assertReferenceTest(userPromptForDisplay(hintedC.prompt) === "C user prompt", "C display prompt should strip environment and reference injection");
  assertReferenceTest(promptWithCodeQueueEnvironmentHint(hintedC.prompt) === hintedC.prompt, "environment hint injection should be idempotent");
  const indexA = promptC.indexOf("Round 1.1 referenced task codex_1000_aaaaaa");
  const indexB = promptC.indexOf("Round 2.1 referenced task codex_1001_bbbbbb");
  assertReferenceTest(indexA >= 0, "C should include upstream A as round 1");
  assertReferenceTest(indexB > indexA, "C should include direct B after upstream A");
  assertReferenceTest(promptC.includes("----- Reference Round 1/2 -----"), "C should include explicit round 1 separator");
  assertReferenceTest(promptC.includes("----- Reference Round 2/2 -----"), "C should include explicit round 2 separator");
  assertReferenceTest(promptC.indexOf("----- Reference Round 1/2 -----") < indexA, "round 1 separator should appear before A");
  assertReferenceTest(promptC.indexOf("----- Reference Round 2/2 -----") < indexB, "round 2 separator should appear before B");
  assertReferenceTest(promptC.includes("### Initial prompt\nB user prompt"), "C should inject B base prompt, not B injected prompt");
  assertReferenceTest(!promptC.includes("### Initial prompt\n# Code Queue 已解析引用上下文"), "C should not nest prior injected prompt blocks");
  assertReferenceTest(promptC.includes("injectedAt: 2026-05-08T00:03:00.000Z"), "C should include injection timestamp");
  assertReferenceTest(promptC.includes("# 本次任务\nC user prompt"), "C should include current user prompt");
  const deepTasks: QueueTask[] = [];
  for (let index = 0; index < 8; index += 1) {
    const id = `codex_${2000 + index}_${"abcdef".slice(0, 6 - String(index).length)}${index}`;
    const parent = deepTasks.at(-1);
    deepTasks.push(testTask(id, `deep prompt ${index}`, `deep final ${index}`, parent === undefined ? [] : [parent.id], `2026-05-08T00:${String(10 + index).padStart(2, "0")}:00.000Z`));
  }
  const deepById = new Map(deepTasks.map((task) => [task.id, task]));
  const injectedDeep = await ctx().injectReferencedTaskContext({
    prompt: "Deep user prompt",
    referenceTaskIds: [deepTasks.at(-1)?.id ?? ""],
  }, (id) => deepById.get(id) ?? null, "2026-05-08T00:30:00.000Z");
  assertReferenceTest(injectedDeep.referenceInjection?.itemCount === 8, "deep reference chain should not truncate at six rounds");
  assertReferenceTest(injectedDeep.referenceInjection?.truncated === false, "deep reference chain should be marked complete");
  assertReferenceTest(injectedDeep.prompt.includes("----- Reference Round 8/8 -----"), "deep reference chain should expose all eight rounds");
  const retryTask = testTask("codex_3000_retry", injectedDeep.prompt, "", injectedDeep.referenceTaskIds, "2026-05-08T00:31:00.000Z");
  retryTask.basePrompt = injectedDeep.basePrompt ?? "";
  retryTask.referenceInjection = injectedDeep.referenceInjection ?? null;
  const retryAfterDeepReference = retryPrompt(retryTask, { decision: "retry", confidence: 1, reason: "Service restarted while task was active", source: "fallback" });
  const recoveryAfterDeepReference = queueRecoveryRetryPrompt(retryTask, "Service restarted while task was active");
  const explicitLongContinuePrompt = [
    "请保留并完成以下所有验收点，不要截断：",
    ...Array.from({ length: 80 }, (_, index) => `验收点 ${index + 1}: 基于当前 thread 上文补齐缺失证据，并在最终 response 中写出真实命令/API/UI 结果。`),
  ].join("\n");
  const explicitRetryPrompt = retryPrompt(retryTask, { decision: "retry", confidence: 1, reason: "Long MiniMax feedback fixture", continuePrompt: explicitLongContinuePrompt, source: "minimax" });
  const liveMutatingDevicePodPrompt = [
    "DEV test class: live-mutating hardware smoke on G14 DEV device-pod only.",
    "",
    "Allowed live mutation:",
    "- 仅允许通过 `hwpod` 修改 `device-pod-71-freq` 的 `workspace:/projects/01_baseline` 下 firmware 源码和 Keil project membership。",
    "",
    "Forbidden actions:",
    "- 禁止使用 `/app/tools/tran.mjs`，禁止上传临时脚本。",
    "",
    "Closeout fields:",
    "- `DEV test class`、`Allowed mutation actually used`、`Forbidden actions avoided`。",
  ].join("\n");
  const liveMutatingDevicePodTask = testTask("codex_live_mutating_device_pod_retry", liveMutatingDevicePodPrompt, "", [], "2026-05-08T00:32:00.000Z");
  const liveMutatingDevicePodRetry = applyJudgeSafetyOverridesForTest(liveMutatingDevicePodTask, {
    threadId: "thread_live_mutating_device_pod_retry",
    turnId: "turn_live_mutating_device_pod_retry",
    finalResponse: "",
    terminalStatus: "failed",
    terminalError: "unexpected status 503 Service Unavailable",
    transportClosedBeforeTerminal: false,
    appServerExit: { code: 0, signal: null, stderrTail: "" },
    events: [],
  }, { decision: "retry", confidence: 0.7, reason: "Codex turn 失败。", continuePrompt: "继续完成原始任务。", source: "fallback" });
  const liveMutatingContinuePrompt = liveMutatingDevicePodRetry.continuePrompt ?? "";
  let longMiniMaxPromptRejectedAtSource = false;
  try {
    parsedContinuePromptForJudge({ continuePrompt: `${"x".repeat(continuePromptSourceBudgetChars + 1)}` }, "retry");
  } catch {
    longMiniMaxPromptRejectedAtSource = true;
  }
  assertReferenceTest(retryAfterDeepReference.length < 2600, "retry prompt should stay compact for referenced tasks");
  assertReferenceTest(recoveryAfterDeepReference.length < 2200, "queue recovery prompt should stay compact for referenced tasks");
  assertReferenceTest(!retryAfterDeepReference.includes("Reference Round"), "retry prompt should not re-inject reference rounds");
  assertReferenceTest(!recoveryAfterDeepReference.includes("Reference Round"), "queue recovery prompt should not re-inject reference rounds");
  assertReferenceTest(explicitRetryPrompt === explicitLongContinuePrompt, "explicit continuePrompt should not be tail-truncated");
  assertReferenceTest(!explicitRetryPrompt.includes("已截断"), "explicit continuePrompt should not include truncation marker");
  assertReferenceTest(liveMutatingContinuePrompt.includes("live-mutating hardware smoke"), "live-mutating retry should preserve the original authorization summary");
  assertReferenceTest(liveMutatingContinuePrompt.includes("hwpod"), "live-mutating retry should preserve tool authorization details");
  assertReferenceTest(!liveMutatingContinuePrompt.includes("只读 continuation"), "live-mutating retry must not be downgraded to read-only continuation");
  assertReferenceTest(!liveMutatingContinuePrompt.includes("不改变运行态、生产态或持久化状态"), "live-mutating retry must not add generic read-only mutation bans");
  assertReferenceTest(longMiniMaxPromptRejectedAtSource, "over-budget MiniMax continuePrompt should be rejected for source repair");
  return {
    ok: true,
    cases: [
      { name: "strip_frontend_hint_to_basePrompt", ok: true },
      { name: "multi_round_reference_graph", ok: true, itemCount: injectedC.referenceInjection?.itemCount ?? 0 },
      { name: "no_nested_injection_block", ok: true },
      { name: "chronological_round_order", ok: true },
      { name: "timestamp_and_round_separators", ok: true },
      { name: "environment_hint_injected_and_stripped_from_display", ok: true },
      { name: "deep_reference_graph_not_six_round_truncated", ok: true, itemCount: injectedDeep.referenceInjection?.itemCount ?? 0 },
      { name: "retry_prompt_does_not_reinject_reference_graph", ok: true, chars: retryAfterDeepReference.length },
      { name: "queue_recovery_prompt_is_compact", ok: true, chars: recoveryAfterDeepReference.length },
      { name: "explicit_continue_prompt_not_tail_truncated", ok: true, chars: explicitRetryPrompt.length },
      { name: "live_mutating_retry_not_downgraded_to_readonly", ok: true, chars: liveMutatingContinuePrompt.length },
      { name: "over_budget_minimax_continue_prompt_requires_source_repair", ok: true, budgetChars: continuePromptSourceBudgetChars },
    ],
    promptPreview: safePreview(promptC, 1200),
  };
}

function queueOrderTestTask(id: string, status: TaskStatus, createdAt: string, queueEnteredAt: string): QueueTask {
  const task = testTask(id, `${id} prompt`, status === "succeeded" ? `${id} final` : "", [], createdAt);
  task.queueId = "queue_order_test";
  task.queueEnteredAt = queueEnteredAt;
  task.status = status;
  task.updatedAt = queueEnteredAt;
  task.startedAt = status === "running" || status === "judging" ? queueEnteredAt : null;
  task.finishedAt = terminalTask(task) ? queueEnteredAt : null;
  task.currentAttempt = status === "queued" ? 0 : 1;
  task.currentMode = status === "queued" ? null : "retry";
  task.nextMode = status === "retry_wait" ? "retry" : null;
  task.nextPrompt = status === "retry_wait" ? "continue" : null;
  return ctx().normalizeTask(task);
}

function selfTestSchedulerHeartbeat(task: QueueTask, lastLocalHeartbeatAt: string): SchedulerActiveRunHeartbeat {
  return {
    taskId: task.id,
    queueId: task.queueId,
    attempt: 1,
    activeTurnId: task.activeTurnId,
    codexThreadId: task.codexThreadId,
    owner: "self-test",
    schedulerInstance: "self-test",
    executionPlane: "scheduler-execution-plane",
    agentPort: "codex",
    status: task.status,
    lastLocalHeartbeatAt,
    lastObservedAgentEventAt: lastLocalHeartbeatAt,
    lastPersistedTraceAt: lastLocalHeartbeatAt,
    outputMaxSeq: 0,
    source: "scheduler",
  };
}

async function runStaleActiveRecoverySelfTest(): Promise<JsonValue> {
  return await ctx().staleActiveRecoverySelfTest();
}

async function runQueueClaimMoveSelfTest(): Promise<JsonValue> {
  const at = "2026-05-17T06:09:46.702Z";
  const task = queueOrderTestTask("codex_claim_move_self_test", "running", at, at);
  task.queueId = "claim_move_source";
  task.startedAt = at;
  task.currentAttempt = 1;
  task.currentMode = "initial";
  task.codexThreadId = "thread_claim_move_self_test";
  task.activeTurnId = "turn_claim_move_self_test";
  task.updatedAt = at;
  const before = ctx().tasks().slice();
  ctx().tasks().push(task);
  try {
    const response = await ctx().moveTaskToQueueForTest(task, new Request("http://code-queue.local/api/tasks/codex_claim_move_self_test/move", {
      method: "POST",
      body: JSON.stringify({ queueId: "claim_move_target" }),
      headers: { "content-type": "application/json" },
    }));
    const body = await response.json() as Record<string, JsonValue>;
    assertReferenceTest(response.status === 409, "moving a claimed/running task must return 409");
    assertReferenceTest(task.queueId === "claim_move_source", "running task queueId must remain unchanged after rejected move");
    assertReferenceTest(task.status === "running", "running task status must remain running after rejected move");
    assertReferenceTest(task.currentAttempt === 1, "running task currentAttempt must remain claimed after rejected move");
    const databaseRace = await ctx().runDatabaseClaimMoveSelfTest?.() ?? null;
    return {
      ok: true,
      cases: [
        { name: "move_running_task_returns_409", ok: true, status: response.status },
        { name: "rejected_move_preserves_queue", ok: true, queueId: task.queueId },
        { name: "rejected_move_preserves_claim_markers", ok: true, status: task.status, currentAttempt: task.currentAttempt, startedAt: task.startedAt },
        ...(databaseRace === null ? [] : [{ name: "database_claim_blocks_stale_move", ok: true, result: databaseRace }]),
      ],
      response: body as JsonValue,
    };
  } finally {
    ctx().tasks().splice(0, ctx().tasks().length, ...before);
  }
}

function runQueueOrderingSelfTest(): JsonValue {
  const activeRetry = queueOrderTestTask("codex_4000_active", "retry_wait", "2026-05-11T09:00:00.000Z", "2026-05-11T09:00:00.000Z");
  const movedOlderCreated = queueOrderTestTask("codex_3999_moved", "queued", "2026-05-11T08:00:00.000Z", "2026-05-11T08:00:00.000Z") as QueueTask & { queueEnteredAt?: string };
  delete (movedOlderCreated as Partial<QueueTask>).queueEnteredAt;
  movedOlderCreated.output.push({ seq: 2, at: "2026-05-11T09:30:00.000Z", channel: "system", text: "moved from queue=default to queue=queue_order_test\n", method: "queue/move" });
  ctx().normalizeTask(movedOlderCreated as QueueTask);
  const blockedByRetry = [movedOlderCreated, activeRetry];
  const runningHead = queueOrderTestTask("codex_4100_running", "running", "2026-05-11T10:00:00.000Z", "2026-05-11T10:00:00.000Z");
  const queuedBehindRunning = queueOrderTestTask("codex_4101_queued", "queued", "2026-05-11T10:01:00.000Z", "2026-05-11T10:01:00.000Z");
  const terminalAhead = queueOrderTestTask("codex_4200_done", "succeeded", "2026-05-11T11:00:00.000Z", "2026-05-11T11:00:00.000Z");
  const queuedAfterTerminal = queueOrderTestTask("codex_4201_queued", "queued", "2026-05-11T11:01:00.000Z", "2026-05-11T11:01:00.000Z");
  const mergeTargetEarly = queueOrderTestTask("codex_4300_target_early", "queued", "2026-05-11T12:00:00.000Z", "2026-05-11T12:00:00.000Z");
  const mergeSourceMiddle = queueOrderTestTask("codex_4301_source_middle", "queued", "2026-05-11T12:01:00.000Z", "2026-05-11T12:01:00.000Z");
  const mergeTargetLate = queueOrderTestTask("codex_4302_target_late", "queued", "2026-05-11T12:02:00.000Z", "2026-05-11T12:02:00.000Z");
  mergeTargetEarly.queueId = "queue_merge_target";
  mergeSourceMiddle.queueId = "queue_merge_target";
  mergeTargetLate.queueId = "queue_merge_target";
  const orphanRunning = queueOrderTestTask("codex_4400_orphan_running", "running", "2026-05-11T13:00:00.000Z", "2026-05-11T13:00:00.000Z");
  orphanRunning.queueId = "queue_orphan_recovery";
  orphanRunning.activeTurnId = null;
  orphanRunning.schedulerHeartbeat = selfTestSchedulerHeartbeat(orphanRunning, "2026-05-11T13:00:00.000Z");
  const queuedBehindOrphan = queueOrderTestTask("codex_4401_queued", "queued", "2026-05-11T13:01:00.000Z", "2026-05-11T13:01:00.000Z");
  queuedBehindOrphan.queueId = "queue_orphan_recovery";
  const originalMaxActiveQueues = ctx().config.maxActiveQueues;
  const beforeTasks = ctx().tasks().slice();

  assertReferenceTest(ctx().queueHeadTask("queue_order_test", blockedByRetry)?.id === activeRetry.id, "retry_wait head must keep blocking a moved older-created task");
  assertReferenceTest(ctx().nextRunnableTaskFrom("queue_order_test", blockedByRetry)?.id === activeRetry.id, "next runnable should be the retry_wait head");
  assertReferenceTest(ctx().nextRunnableTaskFrom("queue_order_test", [queuedBehindRunning, runningHead]) === null, "running head must block queued tasks behind it");
  assertReferenceTest(ctx().nextRunnableTaskFrom("queue_order_test", [queuedAfterTerminal, terminalAhead])?.id === queuedAfterTerminal.id, "terminal head should not block later queued task");
  assertReferenceTest(ctx().queueHeadTask("queue_merge_target", [mergeTargetLate, mergeSourceMiddle, mergeTargetEarly])?.id === mergeTargetEarly.id, "merged queue should keep the earliest queueEnteredAt task first");
  assertReferenceTest(ctx().queuedStatusReason(queuedBehindRunning, [runningHead, queuedBehindRunning])?.label === "PREV TASK", "queued task behind an active same-queue task should expose PREV TASK reason");
  assertReferenceTest(ctx().availableQueueStartSlotsFor(8, 0) === Number.POSITIVE_INFINITY, "maxActiveQueues=0 should leave queue-to-queue concurrency unbounded");
  assertReferenceTest(ctx().availableQueueStartSlotsFor(0, 1) === 1, "empty active run slots should leave one slot available");
  assertReferenceTest(ctx().availableQueueStartSlotsFor(1, 1) === 0, "one active run slot should exhaust maxActiveQueues=1");
  try {
    const marker = "__queue_order_idle_processing_self_test__";
    const beforeSlotCount = ctx().activeRunSlotCount();
    const hadProcessingMarker = ctx().processingQueues.has(marker);
    const hadReservationMarker = ctx().activeRunSlotReservations.has(marker);
    ctx().processingQueues.add(marker);
    assertReferenceTest(ctx().activeRunSlotCount() === beforeSlotCount, "processing idle queue must not consume an active run slot");
    ctx().activeRunSlotReservations.add(marker);
    assertReferenceTest(ctx().activeRunSlotCount() === beforeSlotCount + (hadReservationMarker ? 0 : 1), "reserved running queue must consume an active run slot");
    if (!hadProcessingMarker) ctx().processingQueues.delete(marker);
    if (!hadReservationMarker) ctx().activeRunSlotReservations.delete(marker);
  } finally {
    ctx().config.maxActiveQueues = originalMaxActiveQueues;
    ctx().updateProcessingFlag();
  }
  {
    const waiterCount = ctx().activeRunSlotWaiters.length;
    const firstWaiter = ctx().enqueueActiveRunSlotWaiter(activeRetry);
    const secondWaiter = ctx().enqueueActiveRunSlotWaiter(queuedAfterTerminal);
    try {
      assertReferenceTest(ctx().activeRunSlotWaiters[waiterCount]?.id === firstWaiter.id, "first active run slot waiter should keep FIFO position");
      assertReferenceTest(ctx().activeRunSlotWaiters[waiterCount + 1]?.id === secondWaiter.id, "second active run slot waiter should not jump ahead");
    } finally {
      ctx().removeActiveRunSlotWaiter(firstWaiter);
      ctx().removeActiveRunSlotWaiter(secondWaiter);
    }
  }
  {
    const reservationMarker = "queue_orphan_recovery";
    const hadSameQueueReservation = ctx().activeRunSlotReservations.has(reservationMarker);
    try {
      ctx().tasks().push(orphanRunning, queuedBehindOrphan);
      ctx().activeRunSlotReservations.add(reservationMarker);
      assertReferenceTest(ctx().taskIsRecoverableOrphanedActive(orphanRunning, 0), "same-queue run slot reservation must not hide an orphaned task");
      const recovered = ctx().queueActiveTasksForRestartRetry("orphaned active task self-test", "self-test", { taskIds: new Set([orphanRunning.id]) });
      assertReferenceTest(recovered >= 1, "orphaned running task should be recovered for retry");
      assertReferenceTest(orphanRunning.status === "retry_wait", "orphaned running task should become retry_wait");
      assertReferenceTest(orphanRunning.activeTurnId === null, "orphaned running task should clear activeTurnId");
      assertReferenceTest(orphanRunning.lastError === "orphaned active task self-test", "orphaned running task should record recovery reason");
      assertReferenceTest(ctx().nextRunnableTaskFrom("queue_orphan_recovery")?.id === orphanRunning.id, "recovered orphan should be the next runnable queue head");
    } finally {
      if (!hadSameQueueReservation) ctx().activeRunSlotReservations.delete(reservationMarker);
      ctx().tasks().splice(0, ctx().tasks().length, ...beforeTasks);
    }
  }

  return {
    ok: true,
    cases: [
      { name: "retry_wait_head_blocks_moved_older_created_task", ok: true, head: activeRetry.id, moved: movedOlderCreated.id },
      { name: "running_head_blocks_later_queued_task", ok: true },
      { name: "terminal_task_does_not_block_queue", ok: true },
      { name: "queue_merge_preserves_chronological_task_order", ok: true },
      { name: "queued_reason_prev_task", ok: true },
      { name: "max_active_queues_zero_is_unbounded", ok: true },
      { name: "idle_processing_queue_does_not_consume_active_run_slot", ok: true },
      { name: "active_run_slot_waiters_are_fifo", ok: true },
      { name: "orphaned_running_task_recovers_to_retry_wait", ok: true },
    ],
  };
}

function opencodeTraceOutput(seq: number, tool: string, input: Record<string, JsonValue>, output: string, status = "completed", metadata: Record<string, JsonValue> | null = null): LiveOutput {
  return {
    seq,
    at: "2026-05-12T00:00:00.000Z",
    channel: "tool",
    method: "opencode/tool",
    text: `${JSON.stringify({
      type: "tool_use",
      sessionID: "ses_trace_self_test",
      part: {
        type: "tool",
        tool,
        id: `prt_trace_${seq}`,
        state: {
          status,
          input,
          output,
          ...(metadata === null ? {} : { metadata }),
          time: { start: 1000, end: 1337 },
        },
      },
    })}\n`,
    itemId: `prt_trace_${seq}`,
  };
}

function partialOpencodeTraceOutput(seq: number): LiveOutput {
  const raw = JSON.stringify({
    type: "tool_use",
    sessionID: "ses_trace_self_test",
    part: {
      type: "tool",
      tool: "bash",
      id: `prt_trace_${seq}`,
      state: {
        status: "completed",
        input: { command: "git diff -- src/components/frontend/src/trace.tsx" },
        output: `diff --git a/src/components/frontend/src/trace.tsx b/src/components/frontend/src/trace.tsx\n${"x".repeat(3000)}`,
      },
    },
  });
  return {
    seq,
    at: "2026-05-12T00:00:00.000Z",
    channel: "tool",
    method: "opencode/tool",
    text: `${raw.slice(0, 700)}...`,
    itemId: `prt_trace_${seq}`,
  };
}

function runTracePortSelfTest(): JsonValue {
  const task = testTask("codex_5000_trace", "trace prompt", "", [], "2026-05-12T00:00:00.000Z");
  task.model = minimaxM27Model;
  task.output = [
    { seq: 1, at: "2026-05-12T00:00:00.000Z", channel: "system", method: "queue", text: "attempt 1/1 queue=default provider=main-server cwd=/root/unidesk mode=initial model=minimax-m2.7 port=opencode\n" },
    { seq: 2, at: "2026-05-12T00:00:00.000Z", channel: "system", method: "opencode/step-start", text: "opencode run started session=ses_trace_self_test\n" },
    opencodeTraceOutput(3, "grep", { command: "rg -n trace src/components/microservices/code-queue/src/index.ts" }, "src/components/microservices/code-queue/src/index.ts:1:trace"),
    { seq: 4, at: "2026-05-12T00:00:00.000Z", channel: "system", method: "opencode/step-finish", text: "opencode run finished reason=tool-calls\n" },
    opencodeTraceOutput(5, "edit", { filePath: "src/components/frontend/src/trace.tsx" }, "Edit applied successfully.", "completed", {
      diff: "Index: src/components/frontend/src/trace.tsx\n===================================================================\n--- src/components/frontend/src/trace.tsx\n+++ src/components/frontend/src/trace.tsx\n@@ -1,1 +1,2 @@\n const before = true;\n+const after = true;\n",
    }),
    opencodeTraceOutput(6, "bash", { command: "bunx tsc -p scripts/tsconfig.json --noEmit" }, "ok"),
    partialOpencodeTraceOutput(7),
    { seq: 8, at: "2026-05-12T00:00:00.000Z", channel: "reasoning", method: "opencode/reasoning", text: "hidden reasoning\n" },
    { seq: 9, at: "2026-05-12T00:00:00.000Z", channel: "assistant", method: "opencode/text", text: "<think>hidden reasoning</think>\n" },
  ];
  const transcript = buildTaskTranscript(task, 20, 0);
  const explored = transcript.find((line) => line.seq === 3);
  const edited = transcript.find((line) => line.seq === 5);
  const ran = transcript.find((line) => line.seq === 6);
  const partial = transcript.find((line) => line.seq === 7);
  if (explored === undefined || edited === undefined || ran === undefined || partial === undefined) throw new Error("opencode trace self-test transcript lines missing");
  assertReferenceTest(explored.kind === "explored", "opencode grep tool should normalize to explored trace line");
  assertReferenceTest(edited.kind === "edited", "opencode edit tool should normalize to edited trace line");
  assertReferenceTest(ran.kind === "ran", "opencode bash command should normalize to ran trace line");
  assertReferenceTest(partial.kind === "explored", "truncated opencode tool JSON should still normalize from command preview");
  assertReferenceTest(Number(explored.durationMs ?? 0) === 337, "opencode tool duration should be preserved");
  assertReferenceTest(transcriptLineSummaryLines(edited).some((line) => line.includes("trace.tsx")), "summary lines should expose edited path");
  assertReferenceTest(String(edited.bodyPreview || "").includes("+const after = true;"), "opencode edit should use metadata diff for line diff display");
  assertReferenceTest(!transcript.some((line) => line.status === "opencode/step-start" || line.status === "opencode/step-finish"), "opencode step boundaries should stay out of trace");
  assertReferenceTest(!transcript.some((line) => String(line.bodyPreview || "").includes("<think>hidden reasoning</think>")), "reasoning-only opencode assistant text should not duplicate reasoning");

  const codexWebSearchTask = testTask("codex_5004_web_search", "codex web search prompt", "", [], "2026-05-12T00:01:00.000Z");
  codexWebSearchTask.output = [
    { seq: 30, at: "2026-05-12T00:01:00.000Z", channel: "tool", method: "item/started", itemId: "ws_trace", text: "item/started: webSearch\n" },
    { seq: 31, at: "2026-05-12T00:01:01.000Z", channel: "tool", method: "item/completed", itemId: "ws_trace", text: "item/completed: webSearch status=completed\n" },
  ];
  const webSearchTranscript = buildTaskTranscript(codexWebSearchTask, 20, 0);
  const webSearchLines = webSearchTranscript.filter((line) => line.rawSeqs.includes(30) || line.rawSeqs.includes(31));
  assertReferenceTest(webSearchLines.length === 1, "codex WebSearch start/completed lifecycle should coalesce into one trace line");
  assertReferenceTest(webSearchLines[0]?.kind === "explored", "codex WebSearch should count as an explored/read trace line");
  assertReferenceTest([30, 31].every((seq) => webSearchLines[0]?.rawSeqs.includes(seq)), "codex WebSearch trace line should preserve lifecycle raw seqs");

  const codexTask = testTask("codex_5002_interleaved_command", "codex command prompt", "", [], "2026-05-12T00:02:00.000Z");
  codexTask.output = [
    { seq: 10, at: "2026-05-12T00:02:00.000Z", channel: "command", method: "item/started", itemId: "call_long", text: "item/started: /bin/bash -lc \"python3 - <<'PY'\\nprint('hello')\\nPY\" status=inProgress\n" },
    { seq: 11, at: "2026-05-12T00:02:01.000Z", channel: "command", method: "item/commandExecution/outputDelta", itemId: "call_long", text: "first line\n" },
    { seq: 12, at: "2026-05-12T00:02:02.000Z", channel: "system", method: "startup", text: "Service restarted while task was active; task queued for retry\n" },
    { seq: 13, at: "2026-05-12T00:02:03.000Z", channel: "command", method: "item/commandExecution/outputDelta", itemId: "call_long", text: "second line\n" },
    { seq: 14, at: "2026-05-12T00:02:04.000Z", channel: "command", method: "item/started", itemId: "call_other", text: "item/started: /bin/bash -lc \"git status --short\" status=inProgress\n" },
    { seq: 15, at: "2026-05-12T00:02:05.000Z", channel: "command", method: "item/completed", itemId: "call_other", text: "item/completed: /bin/bash -lc \"git status --short\" status=completed\n" },
    { seq: 16, at: "2026-05-12T00:02:06.000Z", channel: "command", method: "item/commandExecution/outputDelta", itemId: "call_long", text: "third line\n" },
    { seq: 17, at: "2026-05-12T00:02:07.000Z", channel: "command", method: "item/completed", itemId: "call_long", text: "item/completed: /bin/bash -lc \"python3 - <<'PY'\\nprint('hello')\\nPY\" status=completed\n" },
  ];
  const codexTranscript = buildTaskTranscript(codexTask, 20, 0);
  const longCommandLines = codexTranscript.filter((line) => line.rawSeqs.includes(11) || line.rawSeqs.includes(13) || line.rawSeqs.includes(16));
  assertReferenceTest(longCommandLines.length === 1, "interleaved command output deltas should stay in one trace command line");
  const longCommand = longCommandLines[0];
  if (longCommand === undefined) throw new Error("interleaved command trace line missing");
  assertReferenceTest(longCommand.kind === "ran", "interleaved shell command should be a ran trace line");
  assertReferenceTest(String(longCommand.commandPreview || "").includes("python3 - <<"), "interleaved command trace line should retain command preview");
  assertReferenceTest(["first line", "second line", "third line"].every((part) => String(longCommand.bodyPreview || "").includes(part)), "interleaved command trace line should aggregate all output chunks");
  assertReferenceTest(transcriptLineSummaryLines(longCommand).some((line) => line.includes("$ python3 - <<")), "interleaved command summary should expose the command before expansion");

  const fragmentedMessageTask = testTask("codex_5003_fragmented_message", "message fragments prompt", "", [], "2026-05-12T00:03:00.000Z");
  fragmentedMessageTask.output = [
    { seq: 20, at: "2026-05-12T00:03:00.000Z", channel: "assistant", method: "item/agentMessage/delta", itemId: "msg_a", text: "Hello " },
    { seq: 21, at: "2026-05-12T00:03:01.000Z", channel: "assistant", method: "item/agentMessage/delta", itemId: "msg_a", text: "world.\n" },
    { seq: 22, at: "2026-05-12T00:03:02.000Z", channel: "reasoning", method: "item/reasoning/summaryTextDelta", itemId: "rsn_a", text: "Thinking " },
    { seq: 23, at: "2026-05-12T00:03:03.000Z", channel: "reasoning", method: "item/reasoning/summaryTextDelta", itemId: "rsn_a", text: "done.\n" },
  ];
  const fragmentedTranscript = buildTaskTranscript(fragmentedMessageTask, 20, 0);
  const assistantMessages = fragmentedTranscript.filter((line) => line.title === "Assistant message");
  const reasoningMessages = fragmentedTranscript.filter((line) => line.title === "Reasoning");
  assertReferenceTest(assistantMessages.length === 1, "assistant message deltas should coalesce into one trace line");
  assertReferenceTest(String(assistantMessages[0]?.bodyPreview || "").includes("Hello world."), "assistant message trace line should contain the joined assistant text");
  assertReferenceTest([20, 21].every((seq) => assistantMessages[0]?.rawSeqs.includes(seq)), "assistant message trace line should preserve raw seqs");
  assertReferenceTest(reasoningMessages.length === 1, "reasoning deltas should coalesce into one trace line");
  assertReferenceTest(String(reasoningMessages[0]?.bodyPreview || "").includes("Thinking done."), "reasoning trace line should contain the joined reasoning text");

  const remoteTask = testTask("codex_5001_remote_opencode", "remote command prompt", "", [], "2026-05-12T00:01:00.000Z");
  remoteTask.providerId = "D601";
  remoteTask.cwd = "/home/ubuntu";
  remoteTask.model = minimaxM27Model;
  const remoteCommand = remoteOpenCodeRunCommandForTest(remoteTask, "hello 'world'");
  assertReferenceTest(remoteCommand.includes("exec opencode"), "remote opencode command must exec the opencode binary, not the run subcommand");
  assertReferenceTest(!remoteCommand.includes("exec 'run'") && !remoteCommand.includes("exec run --format"), "remote opencode command must not regress to exec run");
  assertReferenceTest(!openCodeTransportClosedBeforeTerminal(true, true, false), "exit=0 plus current final response must be terminal even without step_finish");
  assertReferenceTest(openCodeTransportClosedBeforeTerminal(true, false, false), "exit=0 without final response and step_finish is not a completed turn");
  assertReferenceTest(openCodeTransportClosedBeforeTerminal(false, true, true), "non-zero exit remains a transport failure even with partial text");
  return {
    ok: true,
    cases: [
      { name: "opencode_tool_to_explored", ok: true, title: explored?.title ?? null },
      { name: "opencode_tool_to_edited", ok: true, title: edited?.title ?? null },
      { name: "opencode_tool_to_ran", ok: true, title: ran?.title ?? null },
      { name: "partial_opencode_tool_to_explored", ok: true, title: partial?.title ?? null },
      { name: "step_boundaries_filtered", ok: true },
      { name: "reasoning_duplicate_filtered", ok: true },
      { name: "interleaved_command_output_single_trace_line", ok: true, rawSeqs: longCommand?.rawSeqs ?? [] },
      { name: "interleaved_command_summary_has_command", ok: true, summaryLines: longCommand ? transcriptLineSummaryLines(longCommand) : [] },
      { name: "codex_web_search_lifecycle_coalesced", ok: true, rawSeqs: webSearchLines[0]?.rawSeqs ?? [] },
      { name: "message_fragments_coalesced", ok: true, assistantRawSeqs: assistantMessages[0]?.rawSeqs ?? [], reasoningRawSeqs: reasoningMessages[0]?.rawSeqs ?? [] },
      { name: "duration_preserved", ok: true, durationMs: explored?.durationMs ?? null },
      { name: "remote_opencode_exec_includes_binary", ok: true },
      { name: "opencode_exit0_final_without_step_finish_is_terminal", ok: true },
      { name: "opencode_exit0_without_final_or_step_finish_is_transport_closed", ok: true },
      { name: "opencode_nonzero_exit_is_transport_closed", ok: true },
    ],
    transcript: transcript.filter((line) => line.seq >= 2).map((line) => ({
      seq: line.seq,
      kind: line.kind,
      title: line.title,
      status: line.status,
      commandPreview: line.commandPreview,
      summaryLines: transcriptLineSummaryLines(line),
      durationMs: line.durationMs ?? null,
    })),
  } as unknown as JsonValue;
}

function runJudgeInfraSelfTest(): JsonValue {
  const thinkThenJson = [
    "<think>The tool command seems to be garbled. Let me inspect the file.</think>",
    "只能根据 evidence 判定，最终 JSON 如下：",
    "{\"decision\":\"complete\",\"confidence\":0.91,\"reason\":\"证据完整\",\"continuePrompt\":\"\"}",
  ].join("\n");
  const fencedJson = [
    "```json",
    "{\"decision\":\"retry\",\"confidence\":0.8,\"reason\":\"缺少 live 验证\",\"continuePrompt\":\"继续补齐 live 验证证据。\"}",
    "```",
  ].join("\n");
  const labeledContinue = "json:\n{\"decision\":\"continue\",\"confidence\":0.7,\"reason\":\"还要继续\",\"continuePrompt\":\"继续执行剩余验收。\"}";
  const parsedThink = parseJudgeJson(thinkThenJson);
  const parsedFenced = parseJudgeJson(fencedJson);
  const parsedContinue = parseJudgeJson(labeledContinue);
  assertReferenceTest(parsedThink.value.decision === "complete", "judge parser should extract JSON after think/tool-like prose");
  assertReferenceTest(parsedFenced.value.decision === "retry", "judge parser should extract fenced JSON");
  assertReferenceTest(parsedContinue.value.decision === "continue", "judge parser should accept continue alias");

  const repairMessages = miniMaxJudgeMessages("{\"instruction\":\"fixture\"}", {
    error: "MiniMax judge did not return parseable JSON after denoise",
    previousAnswerRaw: "<think>Let me just look at the trace.tsx file.</think>\nLet me inspect files first.",
  });
  assertReferenceTest(repairMessages.length === 3, "repair request should include system, original user, and repair user messages");
  assertReferenceTest(repairMessages.every((message) => message.role !== "assistant"), "repair request must not echo malformed output as assistant history");
  assertReferenceTest(repairMessages[0]?.content.includes("没有工具访问") === true, "system prompt should prohibit tool/file inspection");
  assertReferenceTest(repairMessages[2]?.content.includes("previousAnswerRaw") === true, "repair request should preserve the bad answer as inert data");
  assertReferenceTest(repairMessages[2]?.content.includes("不要延续") === true, "repair request should explicitly stop continuing bad agent-like output");

  return {
    ok: true,
    cases: [
      { name: "parse_think_then_json", ok: true, source: parsedThink.source },
      { name: "parse_fenced_json", ok: true, source: parsedFenced.source },
      { name: "parse_continue_alias", ok: true, source: parsedContinue.source },
      { name: "repair_without_assistant_echo", ok: true, roles: repairMessages.map((message) => message.role) },
      { name: "repair_blocks_tool_like_continuation", ok: true },
    ],
  };
}

export { runJudgeInfraSelfTest, runQueueClaimMoveSelfTest, runQueueOrderingSelfTest, runReferenceInjectionSelfTest, runStaleActiveRecoverySelfTest, runTracePortSelfTest, runTraceSummaryContractSelfTest };
