import { z } from 'zod'; import { MemoryProposalError } from './proposal.js'; import { retryAt } from './maintenanceQueue.js'; export const failureSchema = z.object({ kind: z.enum(['proposal', 'transient', 'conflict', 'unknown']), consecutive: z.number().int().nonnegative(), /** Consecutive invalid proposals only; the pause looks at this, not `consecutive`. */ proposalStreak: z.number().int().nonnegative().optional(), paused: z.boolean(), }); type Job = { attempts?: number; nextAttemptAt?: number; failure?: z.infer }; /** * Only a source that keeps producing invalid proposals — three in a row — is * parked: that failure reproduces with the same input, so retrying burns calls * without progress. Other failures interleaved in the streak reset it; an * outage followed by one bad answer is not a poisoned source. * Timeouts, rate limits, network, conflicts and unknown errors only back off * (capped at one hour by retryAt) and never pause. Pausing them used to recreate * the incident the attempt cap caused: a ~16-minute provider outage parked * every pending source until someone ran maintenance by hand, and TUI users * get no terminal notice. Legacy attempt counters never pause old work. */ export function recordJobFailure(job: Job, error: unknown): void { const message = error instanceof Error ? error.message : ''; const kind = error instanceof MemoryProposalError ? 'proposal' : /VERSION_CONFLICT|SOURCE_CHANGED/.test(message) ? 'conflict' : /timeout|超时|429|503|fetch|network|ECONN|连接/i.test(message) ? 'transient' : 'unknown'; // Changing failure categories is not recovery: backoff keeps growing across // kinds, so alternating failures cannot reset it. const consecutive = (job.failure?.consecutive ?? 0) + 1; const previous = job.failure?.proposalStreak ?? (job.failure?.kind === 'proposal' ? 1 : 0); const proposalStreak = kind === 'proposal' ? previous + 1 : 0; job.attempts = (job.attempts ?? 0) + 1; job.failure = { kind, consecutive, proposalStreak, paused: proposalStreak >= 3 }; job.nextAttemptAt = retryAt(consecutive); } /** Honors only proposal pauses, so sources parked by the old policy for * transient errors resume on their own after upgrade. */ export function isPausedJob(job: Job): boolean { return job.failure?.paused === true && job.failure.kind === 'proposal'; } export function jobEligible(job: Job, force = false, now = Date.now()): boolean { return force || (!isPausedJob(job) && (job.nextAttemptAt ?? 0) <= now); } type Partition = 'facts' | 'experience'; type Health = { partition: Partition; phase: 'learning' | 'scheduling'; failures: number; at: number }; const health = new Map(); /** Background services never write over a host's TUI. Durable queues retain * source failures; this bounded process snapshot also exposes scheduler/IO errors * that could not be persisted. No source text, paths or provider secrets. */ export function recordBackgroundLearningFailure(workspaceId: string, partition: Partition, phase: Health['phase']): void { const key = `${workspaceId}:${partition}`; const previous = health.get(key); health.delete(key); health.set(key, { partition, phase, failures: (previous?.failures ?? 0) + 1, at: Date.now() }); if (health.size > 128) health.delete(health.keys().next().value!); } export function backgroundLearningHealth(workspaceId: string): Health[] { return (['facts', 'experience'] as const).flatMap(partition => { const value = health.get(`${workspaceId}:${partition}`); return value ? [{ ...value }] : []; }); }