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

export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

export type TaskStatus = "queued" | "running" | "judging" | "retry_wait" | "succeeded" | "failed" | "canceled";

export interface QueuedStatusReason {
  code: string;
  label: string;
  message: string;
  blockerTaskId?: string | null;
  blockerQueueId?: string | null;
  waitPosition?: number | null;
  activeRunSlotCount?: number | null;
  maxActiveQueues?: number | null;
  memory?: JsonValue;
}

export type RunMode = "initial" | "retry";

export type CodeQueueServiceRole = "combined" | "read" | "write" | "scheduler";

export type JudgeDecision = "complete" | "retry" | "fail";

export type CodeExecutionMode = "default" | "windows-native";

export type OutputChannel = "system" | "user" | "assistant" | "reasoning" | "command" | "diff" | "tool" | "error";

export type TerminalStatus = "completed" | "interrupted" | "failed" | null;

export type TranscriptKind = "ran" | "explored" | "edited" | "plan" | "message" | "system" | "error";

export type CodeQueueExecutionPlane = "scheduler-execution-plane" | "postgres-control-plane";

export type CodeQueueExecutionHealth = "healthy" | "degraded" | "split-brain" | "stale-active";
export type CodeQueueEffectiveLiveness = "healthy" | "live" | "degraded" | "at-risk";
export type CodeQueueRecommendedAction = "none" | "continue-supervision" | "observe-degraded" | "investigate-heartbeat-risk";

export type CodeQueueRecoveryCandidateReason =
  | "scheduler-local-active"
  | "owner-heartbeat-fresh"
  | "owner-heartbeat-expired"
  | "owner-heartbeat-missing"
  | "not-db-active";

export interface SchedulerActiveRunHeartbeat {
  taskId: string;
  queueId: string;
  attempt: number;
  activeTurnId: string | null;
  codexThreadId: string | null;
  owner: string;
  schedulerInstance: string;
  executionPlane: "scheduler-execution-plane";
  agentPort: string;
  status: TaskStatus;
  lastLocalHeartbeatAt: string;
  lastObservedAgentEventAt: string | null;
  lastPersistedTraceAt: string | null;
  outputMaxSeq: number;
  source: "scheduler";
}

export interface CodeQueueExecutionDiagnostics {
  state: CodeQueueExecutionHealth;
  health: CodeQueueExecutionHealth;
  degraded: boolean;
  splitBrain: boolean;
  splitBrainLive: boolean;
  effectiveLiveness: CodeQueueEffectiveLiveness;
  recommendedAction: CodeQueueRecommendedAction;
  livenessSummary: string;
  executionStateSource: CodeQueueExecutionPlane;
  controlPlane: string;
  databaseActiveTaskIds: string[];
  databaseActiveTaskCount: number;
  schedulerActiveTaskIds: string[];
  schedulerActiveTaskCount: number;
  schedulerActiveRunSlotCount: number;
  schedulerActiveQueueIds: string[];
  schedulerProcessingQueueIds: string[];
  schedulerOrphanedActiveTaskIds: string[];
  schedulerOrphanedActiveTaskCount: number;
  activeHeartbeatTaskIds: string[];
  activeHeartbeatCount: number;
  heartbeatFreshTaskIds: string[];
  heartbeatExpiredTaskIds: string[];
  heartbeatMissingTaskIds: string[];
  staleRecoveryCandidateTaskIds: string[];
  heartbeatRiskTaskIds: string[];
  traceGapTaskIds: string[];
  traceGapNotStaleTaskIds: string[];
  schedulerHeartbeatStaleMs: number;
  now: string;
  lastSchedulerHeartbeatAt: string | null;
  lastObservedAgentEventAt: string | null;
  lastPersistedTraceAt: string | null;
  oaPublisher: JsonValue | null;
  reasons: string[];
  guidance: string[];
}

export interface RuntimeConfig {
  host: string;
  port: number;
  dataDir: string;
  instanceId: string;
  environment: string;
  namespace: string;
  databaseName: string;
  deployServiceId: string;
  deployRef: string;
  deployCommit: string;
  deployRequestedCommit: string;
  serviceRole: CodeQueueServiceRole;
  schedulerEnabled: boolean;
  schedulerPollIntervalMs: number;
  startupOaBackfillEnabled: boolean;
  outputArchiveDir: string;
  logFile: string;
  defaultWorkdir: string;
  mainProviderId: string;
  remoteDefaultWorkdir: string;
  executionProviderIds: string[];
  remoteCodexEnvKeys: string[];
  skillsPath: string;
  runnerSkillsSourcePath: string;
  resolvedRunnerSkillsPath: () => string;
  codexHome: string;
  opencodeXdgDir: string;
  sourceCodexConfig: string;
  codexSqliteLogExportEnabled: boolean;
  codexSqliteLogExportIntervalMs: number;
  codexSqliteLogExportBatchSize: number;
  codexSqliteLogMaxBytes: number;
  memoryWatchdogThresholdBytes: number;
  memoryWatchdogIntervalMs: number;
  defaultModel: string;
  codexModels: string[];
  defaultReasoningEffort: string | null;
  modelReasoningEfforts: Record<string, string>;
  sandbox: "read-only" | "workspace-write" | "danger-full-access";
  approvalPolicy: "untrusted" | "on-failure" | "on-request" | "never";
  defaultMaxAttempts: number;
  codeModels: string[];
  deepseekApiKey: string;
  deepseekApiBase: string;
  deepseekModel: string;
  minimaxApiKey: string;
  minimaxApiBase: string;
  minimaxModel: string;
  minimaxM3Model: string;
  judgeTimeoutMs: number;
  judgeRepairAttempts: number;
  judgeMaxTokens: number;
  turnNoActivityTimeoutMs: number;
  databaseUrl: string;
  databasePoolMax: number;
  databaseFlushIntervalMs: number;
  databaseClaimTimeoutMs: number;
  oaEventFlowBaseUrl: string;
  notifyClaudeQqEnabled: boolean;
  notifyClaudeQqBaseUrl: string;
  notifyClaudeQqTargetType: "private" | "group";
  notifyClaudeQqUserId: string;
  notifyClaudeQqGroupId: string;
  notifyClaudeQqMaxResponseChars: number;
  notifyClaudeQqTimeoutMs: number;
  notifyClaudeQqSendAttempts: number;
  notifyClaudeQqRetryIntervalMs: number;
  notifyClaudeQqMaxOutboxItems: number;
  maxInMemoryOutputRecords: number;
  maxInMemoryEventRecords: number;
  maxActiveQueues: number;
  egressProxyEnabled: boolean;
  egressProxyUrl: string;
  egressProxyNoProxy: string;
  devContainerMasterHost: string;
  devContainerDefaultProviderId: string;
  devContainerImage: string;
  devContainerWorkdir: string;
  windowsNativeCodexBridgeDir: string;
  windowsNativeCodexCommand: string;
  windowsNativeCodexConnectHost: string;
  windowsNativeCodexDefaultWorkdir: string;
  windowsNativeCodexIdleTimeoutMs: number;
}

export interface QueueTaskRequest {
  prompt: string;
  queueId?: string;
  providerId?: string;
  cwd?: string;
  model?: string;
  reasoningEffort?: string;
  executionMode?: CodeExecutionMode;
  requestedExecutionMode?: string | null;
  maxAttempts?: number;
  referenceTaskIds?: string[];
  basePrompt?: string;
  referenceInjection?: ReferenceInjectionRecord | null;
}

export interface LiveOutput {
  seq: number;
  at: string;
  channel: OutputChannel;
  text: string;
  method?: string;
  itemId?: string;
}

export interface ArchivedLiveOutput extends LiveOutput {
  op?: "set" | "append";
}

export interface TranscriptLine {
  seq: number;
  at: string;
  durationMs?: number;
  kind: TranscriptKind;
  title: string;
  status?: string;
  commandPreview?: string;
  commandOmittedLines?: number;
  bodyPreview?: string;
  bodyOmittedLines?: number;
  stdoutPreview?: string;
  stdoutOmittedLines?: number;
  stderrPreview?: string;
  stderrOmittedLines?: number;
  rawSeqs: number[];
  fullPrompt?: string;
  fullPromptLines?: number;
  fullPromptChars?: number;
  foldedReferencePrompt?: boolean;
}

export interface CodexEventSummary {
  at: string;
  method: string;
  itemType?: string;
  status?: string;
  message?: string;
  textPreview?: string;
}

export interface AttemptSummary {
  index: number;
  mode: RunMode;
  startedAt: string;
  finishedAt: string;
  providerId?: string;
  executionMode?: CodeExecutionMode;
  terminalStatus: TerminalStatus;
  transportClosedBeforeTerminal: boolean;
  appServerExitCode: number | null;
  appServerSignal: string | null;
  error: string | null;
  events?: CodexEventSummary[];
  inputPrompt?: string;
  inputPromptPreview?: string;
  inputPromptChars?: number;
  inputPromptLines?: number;
  finalResponse?: string;
  finalResponsePreview: string;
  finalResponseChars?: number;
  judge?: JudgeResult | null;
  judgeAt?: string | null;
  judgeSeq?: number | null;
  feedbackPrompt?: string;
  feedbackPromptPreview?: string;
  feedbackPromptChars?: number;
  feedbackPromptLines?: number;
  feedbackPromptSource?: string;
  feedbackPromptForAttempt?: number | null;
  stderrTail: string;
  outputStartSeq?: number | null;
  outputEndSeq?: number | null;
  runnerErrorClassification?: JsonValue | null;
  errorCount?: number;
}

export interface JudgeResult {
  decision: JudgeDecision;
  confidence: number;
  reason: string;
  continuePrompt?: string;
  source: "minimax" | "fallback";
  failureDetails?: JudgeFailureDetails | null;
  raw?: JsonValue;
}

export interface JudgeFailureDetails {
  provider: "minimax";
  stage: "request" | "http" | "parse" | "validation" | "unknown";
  model: string;
  apiBase: string;
  occurredAt: string;
  durationMs: number;
  timeoutMs: number;
  timedOut: boolean;
  errorName: string;
  errorMessage: string;
  repairAttempt?: number;
  maxRepairAttempts?: number;
  promptChars?: number;
  promptLines?: number;
  payloadBytes?: number;
  responseStatus?: number | null;
  responseTextPreview?: string;
  responseTextChars?: number;
  responseContentPreview?: string;
  responseContentChars?: number;
}

export interface FeedbackPromptRecord {
  text: string;
  preview: string;
  chars: number;
  lines: number;
  source: string;
  forAttempt: number | null;
  truncated: boolean;
}

export interface ParsedJudgeJson {
  value: Record<string, unknown>;
  source: string;
}

export interface MiniMaxJudgeResponse {
  rawText: string;
  content: string;
  diagnostics: {
    provider: "minimax";
    model: string;
    apiBase: string;
    durationMs: number;
    timeoutMs: number;
    promptChars: number;
    promptLines: number;
    payloadBytes: number;
    responseStatus: number;
    responseTextChars: number;
    responseContentChars: number;
  };
}

export interface ReferenceInjectionSummaryItem {
  round: number;
  roundIndex: number;
  taskId: string;
  viaTaskId: string | null;
  status: TaskStatus;
  providerId: string;
  executionMode?: CodeExecutionMode;
  model: string;
  cwd: string;
  createdAt: string;
  updatedAt: string;
  promptChars: number;
  finalResponseChars: number;
  finalResponseAt: string | null;
  finalResponseSource: string;
  referenceTaskIds: string[];
  cliHint: string;
}

export interface ReferenceInjectionRecord {
  version: 2;
  injectedAt: string;
  basePrompt: string;
  directReferenceTaskIds: string[];
  maxRounds: number | null;
  truncated: boolean;
  itemCount: number;
  items: ReferenceInjectionSummaryItem[];
}

export interface PromptHistoryItem {
  seq: number;
  at: string;
  method: "turn/steer";
  text: string;
  steerId?: string;
}

export interface QueueTask {
  id: string;
  queueId: string;
  queueEnteredAt: string;
  prompt: string;
  basePrompt: string;
  referenceTaskIds: string[];
  referenceInjection: ReferenceInjectionRecord | null;
  providerId: string;
  cwd: string;
  model: string;
  reasoningEffort: string | null;
  executionMode: CodeExecutionMode;
  requestedExecutionMode?: string | null;
  maxAttempts: number;
  status: TaskStatus;
  createdAt: string;
  updatedAt: string;
  startedAt: string | null;
  finishedAt: string | null;
  readAt: string | null;
  currentAttempt: number;
  currentMode: RunMode | null;
  codexThreadId: string | null;
  activeTurnId: string | null;
  schedulerHeartbeat?: SchedulerActiveRunHeartbeat | null;
  finalResponse: string;
  stepCount?: number;
  llmStepCount?: number;
  outputMaxSeq?: number;
  lastError: string | null;
  lastJudge: JudgeResult | null;
  judgeFailCount: number;
  promptHistory: PromptHistoryItem[];
  output: LiveOutput[];
  events: CodexEventSummary[];
  attempts: AttemptSummary[];
  cancelRequested: boolean;
  nextPrompt: string | null;
  nextMode: RunMode | null;
}

export interface PersistedState {
  version: 1;
  updatedAt: string;
  nextSeq: number;
  queues: QueueRecord[];
  tasks: QueueTask[];
}

export interface ClaudeQqNotificationItem {
  id: string;
  kind: string;
  dedupKey: string;
  target: string;
  message: string;
  createdAt: string;
  updatedAt: string;
  attempts: number;
  nextAttemptAt: string;
  lastError: string | null;
  sentAt: string | null;
}

export interface ClaudeQqNotificationOutboxState {
  version: 1;
  updatedAt: string;
  items: ClaudeQqNotificationItem[];
}

export interface ClaudeQqNotificationRow {
  id: string;
  kind: string;
  dedup_key: string;
  target: string;
  message: string;
  created_at: Date | string;
  updated_at: Date | string;
  attempts: number;
  next_attempt_at: Date | string;
  last_error: string | null;
  sent_at: Date | string | null;
}

export interface QueueRecord {
  id: string;
  name: string;
  createdAt: string;
  updatedAt: string;
}

export interface WorkdirRecord {
  providerId: string;
  executionMode: CodeExecutionMode;
  path: string;
  createdAt: string;
  updatedAt: string;
}

export interface AppServerExit {
  code: number | null;
  signal: string | null;
  stderrTail: string;
}

export interface CodexRunResult {
  threadId: string | null;
  turnId: string | null;
  finalResponse: string;
  terminalStatus: TerminalStatus;
  terminalError: string | null;
  transportClosedBeforeTerminal: boolean;
  appServerExit: AppServerExit;
  runnerErrorClassification?: JsonValue | null;
  events: CodexEventSummary[];
}

export interface SessionFileChange {
  callId: string;
  at: string;
  name: string;
  input: string;
  output: string;
}

export interface SessionCommandOutput {
  callId: string;
  at: string;
  stdout: string;
  stderr: string;
  output: string;
  exitCode: number | null;
}

export interface JudgeProbeCase {
  id: string;
  prompt: string;
  finalResponse: string;
  expected: JudgeDecision;
  expectedContinuePromptIncludes?: string[];
  expectedContinuePromptExcludes?: string[];
  expectedContinuePromptMaxChars?: number;
  expectedContinuePromptMaxLines?: number;
  terminalStatus: TerminalStatus;
  cancelRequested?: boolean;
  transportClosedBeforeTerminal?: boolean;
  terminalError?: string | null;
  stderrTail?: string;
  outputs?: Array<{ channel: OutputChannel; text: string; method?: string }>;
  events?: CodexEventSummary[];
}

export interface DevContainerPlan {
  providerId: string;
  containerName: string;
  image: string;
  workdir: string;
  containerWorkdir: string;
  remoteCodexHome: string;
  remoteOpencodeXdgDir: string;
  masterHost: string;
  tunId: number;
  tunName: string;
  serverIp: string;
  clientIp: string;
  natChain: string;
  egressFirewallChain: string;
  keyDir: string;
  masterKeyPath: string;
}

export interface DevContainerCommandLog {
  name: string;
  providerId: string | null;
  exitCode: number | null;
  signal: NodeJS.Signals | null;
  durationMs: number;
  stdout: string;
  stderr: string;
}

export interface CgroupMemoryUsage {
  currentBytes: number;
  inactiveFileBytes: number;
  workingSetBytes: number;
  swapCurrentBytes: number;
  swapMaxBytes: number | null;
}
