Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
diagnose a failed CoS task unattended and retry it when the investigation lands
[._.]/ Adam Eivyd4425a07ffc8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6cab3a0f8c..5791626524 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **A failed CoS task now diagnoses itself and comes back on its own.** A failing task used to pile up a queue of approval-gated tasks — the crash filed one, the provider failure filed another, repeated orphaning filed a third — and then, even after the cause was fixed, the original task sat `blocked` until someone un-blocked it by hand (or the 14-day reaper quietly retired it as stale). Both halves of that are now automatic. Every failure-driven investigation is filed through one producer, so they share a single approval policy, a single storm counter, and a single dedup fingerprint: unattended by default, held for you in exactly the two cases where another unattended agent would just repeat itself — the same cause was already investigated in the last 24 hours, or failures are cascading rather than isolated — and the task says which of the two it is. Completing an investigation, whether an agent finished it or you fixed the cause and ticked it off, then automatically retries every task that failure was blocking. Bounded at two automatic retries per task, after which the task stays blocked and says the retry loop gave up rather than still showing the original failure. A task you terminated or paused, one parked awaiting your arbitration, and one waiting on a repository path you have to fix are never revived behind your back.+- **Series Autopilot now protects the author’s originating story intent.** The Universe Builder starter idea is included in foundation-cache invalidation, rendered ahead of derived canon for the independent foundation judge, and supplied explicitly to arc generation with a hard rule against replacing its ontology, protagonists, or core story engine. Full-control runs still unlock derived world fields, but they keep the human-authored starter idea locked.- **Character-first foundation repair gets a quality-first runtime.** Productive ensemble work may run for up to two hours instead of being discarded at ten minutes, while a finite ceiling still stops a genuinely hung provider.- **Episode synopsis revisions are now restorable.** Text-stage history snapshots preserve input-only stages as well as generated output, so regenerating an episode plan can no longer discard the prior synopsis merely because that planning stage stores its authored text in `input`.diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex a6aed15ab7..c30152a193 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -38,10 +38,12 @@ const statusIcons = {};// Why an approval-required task is waiting on the user, keyed by the namespaced-// `metadata.approvalReason` token its producer stamped. Today only the auto-filed-// agent-failure investigations write one (server:-// agentErrorAnalysis.resolveInvestigationApproval); other producers that hold a-// task add their own entries here rather than a parallel field.+// `metadata.approvalReason` token its producer stamped. Every failure-driven+// investigation producer writes one through the same policy (server:+// agentErrorAnalysis.resolveInvestigationApproval / resolveAutoInvestigationApproval+// — agent failures, AI-provider failures, critical crashes, repeated orphaning),+// so the two tokens below cover all of them. Other producers that hold a task add+// their own entries here rather than a parallel field.const APPROVAL_REASON_HINTS = {'investigation-loop:repeat-fingerprint': 'Held for you: this same failure cause was investigated within the last 24 hours and came back.','investigation-loop:failure-storm': 'Held for you: this hour is nearly out of investigation budget — failures are cascading, not isolated.'diff --git a/server/lib/README.md b/server/lib/README.mdindex f7bbcca85b..552e534906 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -241,6 +241,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `jsonExtract.js` | Pull JSON blocks out of LLM responses. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). || `taskParser.js` | Parse `TASKS.md` format. || `taskPauseHold.js` | The user-PAUSE hold — pure metadata helpers shared by the writer (`pauseAgent`), the reader (`resumeAgent`), and the clearer (`updateTask`). `AGENT_PAUSED_CATEGORY` is the `blockedCategory` a pause stamps; `PAUSE_METADATA_KEYS` names every key it writes; `pauseMetadata({agentId, pausedAt, workspacePath, runId})` arms it and `clearedPauseMetadata()` releases it (undefined-valued, so `updateTask` deletes rather than serializing `"null"`); `isAgentPausedTask(task)` / `isResumablePausedTask(task, agentId)` answer whether a pause is still live and whether it is THIS agent's. `updateTask` clears the whole set whenever the task leaves `blocked`, so a revive by any path (dedupe, cooldown expiry, manual unblock) can't leave a task running under a stale pause. Also carries the cycle-safe RELEASE adapter (#3730) `agentManagement.js` registers at load — `resolvePausedTaskResume(task)` hands `updateTask` the paused run's resume pointer before the write (so any un-block resumes on the preserved worktree, not just the Resume dialog) and `retirePausedAgent(agentId, taskId, branchName)` retires the paused record after it. |+| `taskBlockCategories.js` | The `blockedCategory` vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. `PAUSED_BLOCKED_CATEGORIES` (paused until something outside the task changes — keeps the resume pointer), `USER_DECISION_BLOCKED_CATEGORIES` (user intent / open decision — the reaper's exemption), `NON_AUTO_RETRY_BLOCK_CATEGORIES` (their union — a completed investigation must never revive these). Pure. || `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. || `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. || `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |@@ -270,6 +271,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. || `issueLength.js` | Per-issue size targets fed into text stages. |+| `investigationTasks.js` | Investigation-task identity, the approval policy, and the auto-retry decision — shared by the producers (`services/investigationTaskProducer.js`), the reaper (`cosTaskStore.js`, which used to hand-copy the predicate to dodge an import cycle) and the retry (`services/investigationRetry.js`). `isInvestigationTask(task)` (durable `isInvestigation` marker, falling back to the `INVESTIGATION_HEADLINE_PREFIX` headline for pre-#2615 / peer-synced tasks); `buildInvestigationFingerprint(task, analysis)` / `investigationFingerprint({category, kind, scope})` → the `category:kind:scope` dedup key; `resolveInvestigationApproval({fingerprint, tasks, recentCreations})` → unattended by default (#3714), held only on a `repeat-fingerprint` or `failure-storm` loop, with `approvalReason` + `loopProse` for the queue UI; `couldReleaseBlockedTasks(investigation)` is the pure pre-read gate for `resolveInvestigationRetryTargets({investigation, tasksById})`, which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its `RETRY_SKIP_REASONS` reason (an `auto-expired` completion, a non-`blocked` task, a `NON_AUTO_RETRY_BLOCK_CATEGORIES` block, or a task past `MAX_AUTO_RETRIES_PER_TASK`); `autoRetryMetadata(task, investigationId, now)` stamps the budget that survives the revive's own `failureCount` reset. Pure. || `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. || `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. || `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex bcf3096a32..250e9f757b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -225,6 +225,7 @@ export * from './htmlToText.js';export * from './jsonExtract.js';export * from './taskParser.js';export * from './taskPauseHold.js';+export * from './taskBlockCategories.js';export * from './taskRequeue.js';export * from './taskRetryHold.js';export * from './taxonomyTally.js';@@ -248,6 +249,7 @@ export * from './localLlmDisk.js';export * from './localModelHeuristics.js';export * from './loraDataset.js';export * from './issueLength.js';+export * from './investigationTasks.js';export * from './mediaItemKey.js';export * from './migrationMarker.js';export * from './modelPricing.js';diff --git a/server/lib/investigationTasks.js b/server/lib/investigationTasks.jsnew file mode 100644index 0000000000..94ae1923bf--- /dev/null+++ b/server/lib/investigationTasks.js@@ -0,0 +1,301 @@+/**+ * Investigation tasks — identity, fingerprinting, and the auto-retry decision.+ *+ * Pure helpers shared by the three parties that all have to agree on what an+ * investigation task IS and which failure it tracks: the producer+ * (`agentErrorAnalysis.js`), the reaper (`cosTaskStore.js`, which used to+ * hand-copy the predicate to dodge a `cosTaskStore ↔ cos.js ↔+ * agentErrorAnalysis` import cycle), and the retry+ * (`services/investigationRetry.js`, which owns the why).+ */++import { NON_AUTO_RETRY_BLOCK_CATEGORIES } from './taskBlockCategories.js';++export { NON_AUTO_RETRY_BLOCK_CATEGORIES };++// Stable headline every investigation task created by `agentErrorAnalysis` has+// ever started with — the one signal present on BOTH tasks carrying the durable+// `isInvestigation` marker and pre-#2615 tasks that predate it (including tasks+// synced from a not-yet-upgraded federated peer, which a local migration can't+// reach).+export const INVESTIGATION_HEADLINE_PREFIX = '[Auto] Investigate agent failure';++// Task metadata survives a markdown round-trip, so booleans come back as the+// strings 'true'/'false'. Local to keep this module import-free of the services+// layer, where the generic `isTruthyMeta` lives.+const truthyMeta = (value) => value === true || value === 'true';++/**+ * Is this task an investigation task? Prefers the durable metadata marker and+ * falls back to the legacy headline shape so investigations persisted before+ * the marker existed are still recognized. Pure.+ */+export function isInvestigationTask(task) {+ if (truthyMeta(task?.metadata?.isInvestigation)) return true;+ return typeof task?.description === 'string'+ && task.description.trimStart().startsWith(INVESTIGATION_HEADLINE_PREFIX);+}++/**+ * Durable dedup key for investigation tasks: same failure category against the+ * same kind of task in the same app is the same cause. Deliberately NOT keyed+ * on the free-text failure message — for `unknown`-category failures that is a+ * raw agent-output line that varies per run, which is exactly the dedup hole+ * that let near-identical investigations pile up (#2615). Pure.+ */+export function buildInvestigationFingerprint(originalTask, analysis) {+ return investigationFingerprint({+ category: analysis?.category,+ kind: originalTask?.metadata?.analysisType+ || originalTask?.metadata?.selfImprovementType+ || originalTask?.taskType,+ scope: originalTask?.metadata?.app+ });+}++/**+ * The `category:kind:scope` key itself, for producers whose failure has no+ * originating CoS task to derive one from (an AI-provider outage, an uncaught+ * server exception). Same three-segment shape, built by the same function, so a+ * change to the format can't leave those producers writing a key the dedup scan+ * no longer recognizes. Pure.+ */+export function investigationFingerprint({ category, kind, scope } = {}) {+ return `${category || 'unknown'}:${kind || 'task'}:${scope || 'none'}`;+}++// ===== Approval policy (#3714) =====++/**+ * Rolling circuit breaker across ALL fingerprints, mirroring `autoFixer.js`'s+ * `tripCircuit`: at most {@link INVESTIGATION_CIRCUIT_MAX_CREATIONS}+ * investigation tasks per window. A systemic failure storm (provider outage,+ * broken spawn path) fails MANY distinct tasks at once, each minting a distinct+ * fingerprint — the per-fingerprint dedup alone can't stop that fan-out. The+ * window is rolling, so the circuit auto-closes as creations age out.+ */+export const INVESTIGATION_CIRCUIT_WINDOW_MS = 60 * 60 * 1000; // 1 hour+export const INVESTIGATION_CIRCUIT_MAX_CREATIONS = 3;++/**+ * How recently a PRIOR investigation of the same cause must have finished for a+ * fresh failure to count as a LOOP rather than an unrelated recurrence. The same+ * fingerprint tripping again months later is new work (fingerprints are coarse —+ * `category:kind:scope`, deliberately not keyed on the message); the same+ * fingerprint tripping again the day after we investigated it means the last+ * investigation did not hold, and burning another unattended agent on it just+ * spins. Wider than the circuit window on purpose: the circuit measures a storm+ * in progress, this measures "we already tried and it came back".+ */+export const INVESTIGATION_LOOP_WINDOW_MS = 24 * 60 * 60 * 1000; // 24 hours++/**+ * How many investigations already filed inside the circuit window make the NEXT+ * one a storm rather than ordinary traffic. Derived from the circuit cap, not a+ * magic number: the last slot before the circuit stops filing tasks at all is+ * the one worth a human. A couple of unrelated agent failures in an hour is+ * normal on a busy install and must stay unattended — otherwise this gate+ * re-creates the stall it exists to remove. The `max(1, …)` floor keeps a+ * hypothetical cap of 1 from making the threshold 0, which would hold EVERY+ * investigation — the exact inversion of this policy.+ */+export const INVESTIGATION_STORM_HOLD_THRESHOLD = Math.max(1, INVESTIGATION_CIRCUIT_MAX_CREATIONS - 1);++/**+ * Namespace for the loop reason when stamped as the task's generic+ * `metadata.approvalReason` — the shared "why is this waiting on me?" key any+ * approval-required producer can write (cosTaskGenerator computes the same+ * concept for its safety-kind / confidence holds). Prefixing keeps this+ * vocabulary from colliding with theirs in one flat namespace. The client's+ * `TaskItem.jsx` renders a hint per token.+ */+export const INVESTIGATION_APPROVAL_REASON_PREFIX = 'investigation-loop:';++/**+ * Human-facing prose for each loop reason, rendered into the task body so the+ * user reading the queue knows WHY this one stopped for them when the previous+ * investigation did not. Counts are interpolated from the constants above so the+ * prose can't drift from the thresholds it describes.+ */+export const LOOP_REASON_PROSE = {+ 'repeat-fingerprint': `This exact failure cause was already investigated within the last ${INVESTIGATION_LOOP_WINDOW_MS / (60 * 60 * 1000)} hours and it has come back — the previous fix did not hold, so this one is held for you instead of spawning another unattended agent that would repeat it.`,+ 'failure-storm': `${INVESTIGATION_STORM_HOLD_THRESHOLD} other agent failure(s) were already filed for investigation this hour, one slot short of the circuit breaker suppressing them entirely — failures are cascading rather than isolated, so this one is held for you rather than spending another unattended agent on a symptom.`+};++/**+ * Did a genuine investigation of this fingerprint already finish inside the loop+ * window? `auto-expired` completions don't count — the reaper flips those to+ * `completed` because their origin tasks went away (cosTaskStore's+ * `sweepResolvedFailureTasks`), so nothing was ever actually attempted and+ * holding the next one for a human would punish a cleanup, not a loop. Pure.+ */+function priorInvestigationSettledRecently(tasks, fingerprint, now) {+ return tasks.some((t) => {+ if (t.status !== 'completed') return false;+ if (t.metadata?.investigationFingerprint !== fingerprint) return false;+ if (t.metadata?.resolution === 'auto-expired') return false;+ const settledAt = Date.parse(t.metadata?.updatedAt);+ // An undated completion can't be proved recent — treat it as old, so the+ // default stays "auto-approve" rather than silently gating on a legacy task.+ if (!Number.isFinite(settledAt)) return false;+ return now - settledAt < INVESTIGATION_LOOP_WINDOW_MS;+ });+}++/**+ * Approval policy for a new investigation task.+ *+ * An agent failure is ordinary, expected traffic: the whole point of an+ * investigation task is that CoS diagnoses its own failures without a human in+ * the loop, so the DEFAULT is auto-approved and unattended. Human approval is+ * reserved for a failure LOOP — the two shapes where letting another agent run+ * unattended would just repeat what already didn't work:+ *+ * - `repeat-fingerprint` — we investigated this exact cause within the last+ * {@link INVESTIGATION_LOOP_WINDOW_MS} and it is back.+ * - `failure-storm` — the circuit window is already at+ * {@link INVESTIGATION_STORM_HOLD_THRESHOLD} investigations, i.e. failures+ * are cascading rather than isolated. (One slot later the circuit stops+ * filing tasks at all; this is the last one before that ceiling.)+ *+ * Pure — every input is injected so the branching is unit-testable.+ *+ * @param {{ fingerprint: string, tasks: object[], recentCreations?: number, now?: number }} args+ * @returns {{ approvalRequired: boolean, loopReason: 'repeat-fingerprint'|'failure-storm'|null,+ * approvalReason: string|null, loopProse: string|null }}+ */+export function resolveInvestigationApproval({+ fingerprint,+ tasks = [],+ recentCreations = 0,+ now = Date.now()+} = {}) {+ if (priorInvestigationSettledRecently(tasks, fingerprint, now)) return approvalVerdict('repeat-fingerprint');+ if (recentCreations >= INVESTIGATION_STORM_HOLD_THRESHOLD) return approvalVerdict('failure-storm');+ return approvalVerdict(null);+}++/** The full verdict for one loop reason (`null` = unattended). Pure. */+function approvalVerdict(loopReason) {+ return {+ approvalRequired: !!loopReason,+ loopReason,+ approvalReason: loopReason ? `${INVESTIGATION_APPROVAL_REASON_PREFIX}${loopReason}` : null,+ loopProse: loopReason ? LOOP_REASON_PROSE[loopReason] : null+ };+}++/** The neutral, unattended verdict — what a failed policy read falls open to. Pure. */+export const UNATTENDED_APPROVAL_VERDICT = Object.freeze(approvalVerdict(null));++// ===== Auto-retry of the tasks an investigation was blocking =====++/**+ * How many times ONE task may be auto-revived off a completed investigation+ * before it stays blocked for a human. This is the outer bound on the+ * investigate → retry → fail → investigate loop, and it is deliberately+ * independent of `MAX_TASK_RETRIES`: a revive resets the per-attempt failure+ * budget (that is what makes it a real retry), so without a separate counter+ * that survives the reset the loop would have no ceiling at all.+ *+ * Two is the useful number. The first auto-retry covers the common case — the+ * investigation found a config/env cause, fixed it, and the task now runs. A+ * second covers a fix that needed a follow-up. A third would mean the+ * investigations are not converging, which is a human's problem.+ */+export const MAX_AUTO_RETRIES_PER_TASK = 2;++/**+ * Why a named affected task was NOT auto-retried. Surfaced in the log line so a+ * "why didn't my task come back?" question is answerable from the journal alone.+ */+export const RETRY_SKIP_REASONS = {+ GONE: 'gone',+ NOT_BLOCKED: 'not-blocked',+ BLOCK_NOT_AUTO_RETRYABLE: 'block-not-auto-retryable',+ BUDGET_EXHAUSTED: 'auto-retry-budget-exhausted',+};++/** Auto-retries a task has already been granted. Survives the markdown round-trip. */+export function autoRetryCount(task) {+ const n = Number(task?.metadata?.autoRetryCount);+ return Number.isInteger(n) && n > 0 ? n : 0;+}++/**+ * Could this task release anything, judged from the task alone? The whole+ * pre-read gate for {@link resolveInvestigationRetryTargets}, so the caller can+ * skip reading both task files for a completion that can't possibly revive+ * something — which is most of them, since every task completion on the install+ * reaches the retry.+ *+ * The `auto-expired` exclusion is the non-obvious one: the reaper flips+ * investigations to `completed` when their origin tasks went away+ * (`sweepResolvedFailureTasks`, up to 50 per sweep), so that completion is a+ * cleanup, not a fix — and without this guard each of those 50 flips would cost+ * a full both-queue read to discover it releases nothing. Pure.+ */+export function couldReleaseBlockedTasks(investigation) {+ return isInvestigationTask(investigation)+ && investigation.status === 'completed'+ && investigation.metadata?.resolution !== 'auto-expired'+ && affectedTaskIds(investigation).length > 0;+}++/**+ * The task ids an investigation names, deduped — later same-fingerprint failures+ * union their id into the surviving investigation, and a repeat there must not+ * double-count a task's auto-retry budget. Pure.+ */+export function affectedTaskIds(investigation) {+ const affected = investigation?.metadata?.affectedTasks;+ return Array.isArray(affected) ? [...new Set(affected)] : [];+}++/**+ * Which tasks does a just-finished investigation release back into the queue?+ *+ * Pure — the caller supplies the investigation and an id→task index. Returns the+ * targets to revive and, separately, every affected task that was deliberately+ * skipped with the reason why. Assumes {@link couldReleaseBlockedTasks} already+ * passed, and re-checks it so a direct caller can't skip the gate.+ *+ * @param {{ investigation: object, tasksById: Map<string, object> }} args+ * @returns {{ targets: object[], skipped: Array<{ taskId: string, reason: string }> }}+ */+export function resolveInvestigationRetryTargets({ investigation, tasksById } = {}) {+ if (!couldReleaseBlockedTasks(investigation)) return { targets: [], skipped: [] };++ const targets = [];+ const skipped = [];+ for (const taskId of affectedTaskIds(investigation)) {+ const task = tasksById?.get(taskId);+ if (!task) {+ skipped.push({ taskId, reason: RETRY_SKIP_REASONS.GONE });+ } else if (task.status !== 'blocked') {+ // Already completed, already running, or already back in the queue —+ // whatever settled it wins over this revive.+ skipped.push({ taskId, reason: RETRY_SKIP_REASONS.NOT_BLOCKED });+ } else if (NON_AUTO_RETRY_BLOCK_CATEGORIES.has(task.metadata?.blockedCategory)) {+ skipped.push({ taskId, reason: RETRY_SKIP_REASONS.BLOCK_NOT_AUTO_RETRYABLE });+ } else if (autoRetryCount(task) >= MAX_AUTO_RETRIES_PER_TASK) {+ skipped.push({ taskId, reason: RETRY_SKIP_REASONS.BUDGET_EXHAUSTED });+ } else {+ targets.push(task);+ }+ }+ return { targets, skipped };+}++/**+ * The metadata patch handed to `reviveBlockedTask` for one auto-retried task.+ * `autoRetryCount` is the budget that survives the revive's own clearing of+ * `failureCount` — see {@link MAX_AUTO_RETRIES_PER_TASK}. Pure.+ */+export function autoRetryMetadata(task, investigationId, now = Date.now()) {+ return {+ autoRetryCount: autoRetryCount(task) + 1,+ autoRetriedByInvestigation: investigationId,+ autoRetriedAt: new Date(now).toISOString(),+ };+}diff --git a/server/lib/investigationTasks.test.js b/server/lib/investigationTasks.test.jsnew file mode 100644index 0000000000..aaa6da06db--- /dev/null+++ b/server/lib/investigationTasks.test.js@@ -0,0 +1,177 @@+import { describe, it, expect } from 'vitest';+import {+ INVESTIGATION_HEADLINE_PREFIX,+ MAX_AUTO_RETRIES_PER_TASK,+ RETRY_SKIP_REASONS,+ autoRetryCount,+ autoRetryMetadata,+ buildInvestigationFingerprint,+ investigationFingerprint,+ isInvestigationTask,+ resolveInvestigationRetryTargets,+} from './investigationTasks.js';+import { AGENT_PAUSED_CATEGORY } from './taskPauseHold.js';++const blocked = (id, metadata = {}) => ({ id, status: 'blocked', metadata: { blockedCategory: 'unknown', ...metadata } });++const investigation = (overrides = {}) => ({+ id: 'sys-inv',+ status: 'completed',+ description: `${INVESTIGATION_HEADLINE_PREFIX} [unknown:task:none]: boom`,+ ...overrides,+ metadata: { isInvestigation: true, affectedTasks: ['task-1'], ...(overrides.metadata || {}) },+});++const index = (...tasks) => new Map(tasks.map(t => [t.id, t]));++describe('isInvestigationTask', () => {+ it('recognizes the durable marker, including the markdown round-trip string', () => {+ expect(isInvestigationTask({ metadata: { isInvestigation: true } })).toBe(true);+ expect(isInvestigationTask({ metadata: { isInvestigation: 'true' } })).toBe(true);+ });++ it('falls back to the legacy headline for investigations that predate the marker', () => {+ expect(isInvestigationTask({ description: ` ${INVESTIGATION_HEADLINE_PREFIX} [x]: boom` })).toBe(true);+ });++ it('is false for ordinary tasks and for a falsy marker string', () => {+ expect(isInvestigationTask({ description: 'Fix the thing' })).toBe(false);+ expect(isInvestigationTask({ metadata: { isInvestigation: 'false' } })).toBe(false);+ expect(isInvestigationTask(null)).toBe(false);+ });+});++describe('buildInvestigationFingerprint', () => {+ it('keys on category, analysisType/taskType, and app — never the free-text message', () => {+ expect(buildInvestigationFingerprint(+ { id: 't', taskType: 'internal', metadata: { analysisType: 'app-improve', app: 'ExampleApp' } },+ { category: 'startup-failure', message: 'raw output line that varies per run' }+ )).toBe('startup-failure:app-improve:ExampleApp');+ });++ it('falls back to taskType, then generic sentinels, when analysisType/app are absent', () => {+ expect(buildInvestigationFingerprint({ id: 't', taskType: 'user', metadata: {} }, { category: 'unknown' })).toBe('unknown:user:none');+ expect(buildInvestigationFingerprint({ id: 't' }, null)).toBe('unknown:task:none');+ });++ it('builds the same three-segment key for producers with no originating task', () => {+ expect(investigationFingerprint({ category: 'auth-error', kind: 'provider-failure', scope: 'Example CLI' }))+ .toBe('auth-error:provider-failure:Example CLI');+ expect(investigationFingerprint({})).toBe('unknown:task:none');+ });+});++describe('resolveInvestigationRetryTargets', () => {+ it('revives a still-blocked affected task', () => {+ const task = blocked('task-1');+ const { targets, skipped } = resolveInvestigationRetryTargets({+ investigation: investigation(), tasksById: index(task)+ });+ expect(targets).toEqual([task]);+ expect(skipped).toEqual([]);+ });++ it('does nothing for a task that is not an investigation', () => {+ const task = blocked('task-1');+ const notAnInvestigation = {+ id: 'sys-x', status: 'completed', description: 'Ordinary work',+ metadata: { affectedTasks: ['task-1'] }+ };+ expect(resolveInvestigationRetryTargets({ investigation: notAnInvestigation, tasksById: index(task) }))+ .toEqual({ targets: [], skipped: [] });+ });++ it('does nothing while the investigation is still open — a diagnosis in flight resolved nothing', () => {+ for (const status of ['pending', 'in_progress', 'blocked', 'challenged']) {+ expect(resolveInvestigationRetryTargets({+ investigation: investigation({ status }), tasksById: index(blocked('task-1'))+ }).targets).toEqual([]);+ }+ });++ it('does nothing for an auto-expired completion — the reaper cleaned up, nobody fixed anything', () => {+ expect(resolveInvestigationRetryTargets({+ investigation: investigation({ metadata: { resolution: 'auto-expired' } }),+ tasksById: index(blocked('task-1'))+ }).targets).toEqual([]);+ });++ it('reports why each affected task was skipped', () => {+ const inv = investigation({+ metadata: { affectedTasks: ['gone', 'running', 'terminated', 'spent'] }+ });+ const { targets, skipped } = resolveInvestigationRetryTargets({+ investigation: inv,+ tasksById: index(+ { id: 'running', status: 'in_progress', metadata: {} },+ blocked('terminated', { blockedCategory: 'user-terminated' }),+ blocked('spent', { autoRetryCount: MAX_AUTO_RETRIES_PER_TASK }),+ )+ });+ expect(targets).toEqual([]);+ expect(skipped).toEqual([+ { taskId: 'gone', reason: RETRY_SKIP_REASONS.GONE },+ { taskId: 'running', reason: RETRY_SKIP_REASONS.NOT_BLOCKED },+ { taskId: 'terminated', reason: RETRY_SKIP_REASONS.BLOCK_NOT_AUTO_RETRYABLE },+ { taskId: 'spent', reason: RETRY_SKIP_REASONS.BUDGET_EXHAUSTED },+ ]);+ });++ // The first draft of this guard hand-wrote a `'user-paused'` category that+ // matches nothing (the real one is `agent-paused`) and omitted+ // `challenge-escalation` entirely — so a task a human paused, or one parked+ // awaiting their arbitration, was revived out from under them. Assert every+ // hands-off category by the constant it actually ships with.+ it.each([+ ['a run the user stopped', 'user-terminated'],+ ['a run the user paused', AGENT_PAUSED_CATEGORY],+ ['a task awaiting the user’s arbitration', 'challenge-escalation'],+ ['a task waiting on an unresolvable app', 'app-unresolved'],+ ['a task waiting on an invalid workspace', 'workspace-invalid'],+ ['a cooldown that revives itself', 'orphan-cooldown'],+ ])('never revives %s', (_label, blockedCategory) => {+ const { targets, skipped } = resolveInvestigationRetryTargets({+ investigation: investigation(),+ tasksById: index(blocked('task-1', { blockedCategory }))+ });+ expect(targets).toEqual([]);+ expect(skipped).toEqual([{ taskId: 'task-1', reason: RETRY_SKIP_REASONS.BLOCK_NOT_AUTO_RETRYABLE }]);+ });++ it('still revives a task that has retries left', () => {+ const task = blocked('task-1', { autoRetryCount: MAX_AUTO_RETRIES_PER_TASK - 1 });+ expect(resolveInvestigationRetryTargets({ investigation: investigation(), tasksById: index(task) }).targets)+ .toEqual([task]);+ });++ it('counts a task named twice only once — same-fingerprint failures union their id in', () => {+ const task = blocked('task-1');+ const inv = investigation({ metadata: { affectedTasks: ['task-1', 'task-1'] } });+ expect(resolveInvestigationRetryTargets({ investigation: inv, tasksById: index(task) }).targets)+ .toEqual([task]);+ });++ it('does nothing when the investigation names no affected task (legacy shape)', () => {+ expect(resolveInvestigationRetryTargets({+ investigation: investigation({ metadata: { affectedTasks: undefined } }),+ tasksById: index(blocked('task-1'))+ })).toEqual({ targets: [], skipped: [] });+ });+});++describe('autoRetryCount / autoRetryMetadata', () => {+ it('reads the count through the markdown round-trip and ignores garbage', () => {+ expect(autoRetryCount({ metadata: { autoRetryCount: 1 } })).toBe(1);+ expect(autoRetryCount({ metadata: { autoRetryCount: '2' } })).toBe(2);+ expect(autoRetryCount({ metadata: { autoRetryCount: 'nope' } })).toBe(0);+ expect(autoRetryCount({})).toBe(0);+ });++ it('increments the budget that survives the revive clearing failureCount', () => {+ expect(autoRetryMetadata(blocked('t', { autoRetryCount: 1 }), 'sys-inv', 1_700_000_000_000)).toEqual({+ autoRetryCount: 2,+ autoRetriedByInvestigation: 'sys-inv',+ autoRetriedAt: new Date(1_700_000_000_000).toISOString(),+ });+ });+});diff --git a/server/lib/taskBlockCategories.js b/server/lib/taskBlockCategories.jsnew file mode 100644index 0000000000..5ed651d6a8--- /dev/null+++ b/server/lib/taskBlockCategories.js@@ -0,0 +1,61 @@+/**+ * `blockedCategory` vocabulary — which blocks are the system's to clear, and+ * which are a person's.+ *+ * A blocked task carries a `blockedCategory` naming WHY it stopped, and three+ * separate automations have to answer "may I move this?" from that one value:+ * the pause logic (does this block keep a resume pointer?), the failure reaper+ * (may I auto-expire this at 14 days?), and the investigation auto-retry (may I+ * put this back in the queue?). Each used to keep its own hand-written literal+ * set, which is how the retry's first draft shipped a `'user-paused'` that+ * matches nothing — the real category is `agent-paused` — and silently missed+ * `challenge-escalation` entirely.+ *+ * Pure and dependency-free (beyond the pause category it shares with+ * `taskPauseHold.js`) so all three read ONE vocabulary.+ */++import { AGENT_PAUSED_CATEGORY } from './taskPauseHold.js';++/**+ * "Paused until something outside the task changes", not "finished with". A+ * pause keeps the resume pointer (see `updateTask`) and is never auto-expired by+ * the failure reaper — the task is expected to run again once the cooldown+ * lapses or the user fixes the config.+ */+export const PAUSED_BLOCKED_CATEGORIES = new Set([+ 'orphan-cooldown', // timed cooldown; unblockExpiredOrphanCooldowns revives it+ 'app-unresolved', // the task's app has no usable Repository Path+ 'workspace-invalid' // the resolved workspace isn't a usable directory+]);++/**+ * Blocks that encode USER INTENT or an OPEN user decision, not a stale failure+ * artifact — the reaper leaves these alone. Everything else with a+ * `blockedCategory` is a failure-path block and therefore reapable.+ *+ * The workspace blocks are an open user decision, not a stale failure: the task+ * is waiting for the app's Repository Path to be fixed, and auto-completing it+ * at 14 days would silently retire work nobody decided to drop. (The third pause+ * category, `orphan-cooldown`, stays reapable — it revives itself in ~30+ * minutes, so one still sitting there after 14 days IS stale.)+ */+export const USER_DECISION_BLOCKED_CATEGORIES = new Set([+ 'user-terminated', // user explicitly stopped the agent+ AGENT_PAUSED_CATEGORY, // user paused; resumable on demand+ 'challenge-escalation', // parked awaiting the user's arbitration+ 'app-unresolved',+ 'workspace-invalid'+]);++/**+ * Blocks a completed investigation must NOT auto-retry. The union of the two+ * sets above, expressed as a union rather than re-listed so it cannot drift from+ * them: a standing user decision is not ours to override, and a self-reviving+ * pause (`orphan-cooldown`) already has an owner that revives it on schedule —+ * retrying it here would just double-drive that timer.+ */+export const NON_AUTO_RETRY_BLOCK_CATEGORIES = new Set([+ ...USER_DECISION_BLOCKED_CATEGORIES,+ ...PAUSED_BLOCKED_CATEGORIES+]);diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 32581689f9..fac7d333dd 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -6,13 +6,22 @@*/import { emitLog } from './cosEvents.js';-import { addTask, updateTask, getAllTasks } from './cos.js';+import { addTask, updateTask } from './cos.js';import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { redactOutput } from '../lib/commandSecurity.js';import { stripAnsi } from '../lib/ansiStrip.js';import { retryHoldMetadata } from '../lib/taskRetryHold.js';-import { isTruthyMeta } from './agentState.js';+import {+ INVESTIGATION_CIRCUIT_MAX_CREATIONS,+ INVESTIGATION_HEADLINE_PREFIX,+ LOOP_REASON_PROSE,+ MAX_AUTO_RETRIES_PER_TASK,+ buildInvestigationFingerprint,+ isInvestigationTask,+ resolveInvestigationApproval,+} from '../lib/investigationTasks.js';+import { investigationCircuitOpen, noteInvestigationFiled, readAllTasksFlat, recentInvestigationCreations } from './investigationTaskProducer.js';import { PRIMARY_CHECKOUT_MUTATED_CATEGORY, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';// Max retries before blocking a task@@ -901,73 +910,13 @@ export function analyzeAgentFailure(output, task, model, options = {}) {// fresh task is only allowed once the prior cause was actually dealt with.const OPEN_INVESTIGATION_STATUSES = new Set(['pending', 'in_progress', 'challenged', 'blocked']);-// Rolling circuit breaker across ALL fingerprints, mirroring autoFixer.js's-// tripCircuit: at most INVESTIGATION_CIRCUIT_MAX_CREATIONS investigation tasks-// per rolling window. A systemic failure storm (provider outage, broken spawn-// path) fails MANY distinct tasks at once, each minting a distinct fingerprint —-// the per-fingerprint dedup alone can't stop that fan-out. The window is rolling:-// stamps older than the window are pruned on every check, so the circuit-// auto-closes once creations age out (no manual reset needed).-export const INVESTIGATION_CIRCUIT_WINDOW_MS = 60 * 60 * 1000; // 1 hour-export const INVESTIGATION_CIRCUIT_MAX_CREATIONS = 3;-let investigationCreationStamps = []; // ms timestamps, newest-last--/**- * How many investigation creations are still inside the rolling circuit window.- * Prunes aged-out stamps as a side effect, so the circuit auto-closes without a- * manual reset. The count (not just a boolean "open?") is what the caller needs:- * at the cap it suppresses the task entirely, and below the cap a non-zero count- * is the `failure-storm` loop signal that holds the task for a human.- */-function recentInvestigationCreations(now) {- investigationCreationStamps = investigationCreationStamps.filter(t => now - t < INVESTIGATION_CIRCUIT_WINDOW_MS);- return investigationCreationStamps.length;-}--// Test hook — the stamp list is module state, so suites reset it between cases.-export function __resetInvestigationCircuit() {- investigationCreationStamps = [];-}--/**- * Durable dedup key for investigation tasks: same failure category against the- * same kind of task in the same app is the same cause. Deliberately NOT keyed- * on the free-text failure message — for `unknown`-category failures that is a- * raw agent-output line that varies per run, which is exactly the dedup hole- * that let near-identical investigations pile up (#2615).- */-export function buildInvestigationFingerprint(originalTask, analysis) {- const category = analysis?.category || 'unknown';- const kind = originalTask?.metadata?.analysisType- || originalTask?.metadata?.selfImprovementType- || originalTask?.taskType- || 'task';- const app = originalTask?.metadata?.app || 'none';- return `${category}:${kind}:${app}`;-}--// Stable headline every investigation task ever created starts with — the one-// signal that exists on BOTH new tasks and pre-#2615 tasks (and on tasks synced-// from not-yet-upgraded federated peers, which a local migration couldn't fix).-const INVESTIGATION_HEADLINE_PREFIX = '[Auto] Investigate agent failure';--/**- * Is this task an investigation task? Prefers the durable metadata marker;- * falls back to the legacy headline shape so investigations persisted before- * the marker existed still never spawn meta-investigations.- */-export function isInvestigationTask(task) {- if (isTruthyMeta(task?.metadata?.isInvestigation)) return true;- return typeof task?.description === 'string'- && task.description.trimStart().startsWith(INVESTIGATION_HEADLINE_PREFIX);-}--// Every task across both queues, flattened. One read serves both the-// fingerprint dedup scan and the failure-loop detection below.-async function readAllTasksFlat() {- const { user, cos } = await getAllTasks();- return [...(user?.tasks || []), ...(cos?.tasks || [])];-}+// The rolling circuit breaker, the creation counter, and the flat backlog read+// live in `investigationTaskProducer.js` — shared with the provider / crash /+// orphan producers so "how many investigations this hour" is ONE number rather+// than one per producer. Re-exported here at the address the suites and callers+// already use.+export { INVESTIGATION_CIRCUIT_WINDOW_MS, INVESTIGATION_CIRCUIT_MAX_CREATIONS } from '../lib/investigationTasks.js';+export { __resetInvestigationCircuit } from './investigationTaskProducer.js';// Find an existing investigation task (user or internal queue) still tracking// this fingerprint in a non-terminal status. Pure.@@ -978,100 +927,6 @@ function findOpenInvestigationIn(tasks, fingerprint) {) || null;}-// ===== Failure-loop detection / approval policy (#3714) =====--// How recently a PRIOR investigation of the same cause must have finished for a-// fresh failure to count as a LOOP rather than an unrelated recurrence. The-// same fingerprint tripping again months later is new work (fingerprints are-// coarse — `category:kind:app`, deliberately not keyed on the message); the same-// fingerprint tripping again the day after we investigated it means the last-// investigation did not hold, and burning another unattended agent on it just-// spins. Wider than the circuit window on purpose: the circuit measures a storm-// in progress, this measures "we already tried and it came back".-export const INVESTIGATION_LOOP_WINDOW_MS = 24 * 60 * 60 * 1000; // 24 hours--// How many investigations already filed inside the circuit window make the NEXT-// one a storm rather than ordinary traffic. Derived from the circuit cap, not a-// magic number: the last slot before the circuit stops filing tasks at all is-// the one worth a human. A couple of unrelated agent failures in an hour is-// normal on a busy install and must stay unattended — otherwise this gate-// re-creates the stall it exists to remove.-// The `max(1, …)` floor keeps a hypothetical cap of 1 from making the threshold-// 0, which would hold EVERY investigation — the exact inversion of this policy.-export const INVESTIGATION_STORM_HOLD_THRESHOLD = Math.max(1, INVESTIGATION_CIRCUIT_MAX_CREATIONS - 1);--/**- * Did a genuine investigation of this fingerprint already finish inside the loop- * window? `auto-expired` completions don't count — the reaper flips those to- * `completed` because their origin tasks went away (cosTaskStore's- * `sweepResolvedFailureTasks`), so nothing was ever actually attempted and- * holding the next one for a human would punish a cleanup, not a loop. Pure.- */-function priorInvestigationSettledRecently(tasks, fingerprint, now) {- return tasks.some((t) => {- if (t.status !== 'completed') return false;- if (t.metadata?.investigationFingerprint !== fingerprint) return false;- if (t.metadata?.resolution === 'auto-expired') return false;- const settledAt = Date.parse(t.metadata?.updatedAt);- // An undated completion can't be proved recent — treat it as old, so the- // default stays "auto-approve" rather than silently gating on a legacy task.- if (!Number.isFinite(settledAt)) return false;- return now - settledAt < INVESTIGATION_LOOP_WINDOW_MS;- });-}--/**- * Approval policy for a new investigation task.- *- * An agent failure is ordinary, expected traffic: the whole point of an- * investigation task is that CoS diagnoses its own failures without a human in- * the loop, so the DEFAULT is auto-approved and unattended. Human approval is- * reserved for a failure LOOP — the two shapes where letting another agent run- * unattended would just repeat what already didn't work:- *- * - `repeat-fingerprint` — we investigated this exact cause within the last- * {@link INVESTIGATION_LOOP_WINDOW_MS} and it is back.- * - `failure-storm` — the circuit window is already at- * {@link INVESTIGATION_STORM_HOLD_THRESHOLD} investigations, i.e. failures- * are cascading rather than isolated. (One slot later the circuit stops- * filing tasks at all; this is the last one before that ceiling.)- *- * Pure — every input is injected so the branching is unit-testable.- *- * @param {{ fingerprint: string, tasks: object[], recentCreations?: number, now?: number }} args- * @returns {{ approvalRequired: boolean, loopReason: 'repeat-fingerprint'|'failure-storm'|null }}- */-export function resolveInvestigationApproval({- fingerprint,- tasks = [],- recentCreations = 0,- now = Date.now()-} = {}) {- if (priorInvestigationSettledRecently(tasks, fingerprint, now)) {- return { approvalRequired: true, loopReason: 'repeat-fingerprint' };- }- if (recentCreations >= INVESTIGATION_STORM_HOLD_THRESHOLD) {- return { approvalRequired: true, loopReason: 'failure-storm' };- }- return { approvalRequired: false, loopReason: null };-}--// Namespace for the loop reason when it is stamped as the task's generic-// `metadata.approvalReason` — the shared "why is this waiting on me?" key that-// any approval-required producer can write (cosTaskGenerator already computes-// the same concept for its safety-kind / confidence holds). Prefixing keeps this-// producer's vocabulary from colliding with theirs in one flat namespace.-const INVESTIGATION_APPROVAL_REASON_PREFIX = 'investigation-loop:';--// Human-facing prose for each loop reason, rendered into the task body so the-// user reading the queue knows WHY this one stopped for them when the previous-// investigation did not. Counts are interpolated from the constants above so the-// prose can't drift from the thresholds it describes.-const LOOP_REASON_PROSE = {- 'repeat-fingerprint': `This exact failure cause was already investigated within the last ${INVESTIGATION_LOOP_WINDOW_MS / (60 * 60 * 1000)} hours and it has come back — the previous fix did not hold, so this one is held for you instead of spawning another unattended agent that would repeat it.`,- 'failure-storm': `${INVESTIGATION_STORM_HOLD_THRESHOLD} other agent failure(s) were already filed for investigation this hour, one slot short of the circuit breaker suppressing them entirely — failures are cascading rather than isolated, so this one is held for you rather than spending another unattended agent on a symptom.`-};-/*** Create an investigation task in COS-TASKS.md for a failed agent.*@@ -1122,10 +977,9 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {return existing;}- // Rolling circuit breaker: cap creations per window across all fingerprints.+ // Rolling circuit breaker: cap creations per window across all producers.const now = Date.now();- const recentCreations = recentInvestigationCreations(now);- if (recentCreations >= INVESTIGATION_CIRCUIT_MAX_CREATIONS) {+ if (investigationCircuitOpen(now)) {emitLog('warn', `🔌 Investigation circuit OPEN — ${INVESTIGATION_CIRCUIT_MAX_CREATIONS} investigations created within the last hour; suppressing task for ${fingerprint}`, {agentId, taskId: originalTask.id, fingerprint});@@ -1133,9 +987,11 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {}// Auto-approved unless this failure is a LOOP (#3714) — an isolated agent- // failure is exactly the work CoS is meant to diagnose for itself.- const { approvalRequired, loopReason } = resolveInvestigationApproval({- fingerprint, tasks: allTasks, recentCreations, now+ // failure is exactly the work CoS is meant to diagnose for itself. The pure+ // policy is called directly (rather than via `resolveAutoInvestigationApproval`)+ // so the backlog already read for the dedup scan above serves both.+ const { approvalRequired, loopReason, approvalReason } = resolveInvestigationApproval({+ fingerprint, tasks: allTasks, recentCreations: recentInvestigationCreations(now), now});// Every interpolated free-text field is redacted before it lands in the body —@@ -1162,9 +1018,11 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {`## What to approve\n${remedy}`,`## Why this is held for you\n${LOOP_REASON_PROSE[loopReason]}`].join('\n\n')- : `## What to do\nNo approval needed — this investigation runs unattended. Diagnose the failure above, apply the fix, and leave the task's findings in your summary.\n\n${remedy}`;+ : `## What to do\nNo approval needed — this investigation runs unattended. Diagnose the failure above, apply the fix, and leave the task's findings in your summary. Do NOT un-block the original task by hand; completing this one does it.\n\n${remedy}`;- const unblocks = `${approvalRequired ? 'Approving and applying' : 'Applying'} the fix lets the original task \`${originalTask.id}\` be retried; it will resume: ${originalDesc}.`;+ // Completing this task revives every blocked task in `affectedTasks`+ // automatically (investigationRetry.js), so nobody has to go find them.+ const unblocks = `${approvalRequired ? 'Approving and applying' : 'Applying'} the fix and completing this task automatically retries the original task \`${originalTask.id}\`; it will resume: ${originalDesc}. If the same cause blocks it again after ${MAX_AUTO_RETRIES_PER_TASK} automatic retries, it stays blocked for you.`;// The fingerprint rides in the headline so addTask's first-line dedup —// which sees no `metadata.app` on investigation tasks — tracks fingerprint@@ -1195,13 +1053,13 @@ ${unblocks}`;investigationFingerprint: fingerprint,// Durable record of WHY this stopped for a human (null when it ran// unattended) — readable from the queue without re-deriving the verdict.- approvalReason: loopReason && `${INVESTIGATION_APPROVAL_REASON_PREFIX}${loopReason}`,+ approvalReason,affectedTasks: [originalTask.id] // later same-fingerprint failures union in}, 'internal');// Count only genuine creations against the circuit — addTask's own// description-level dedup returning an existing task is not a new creation.- if (!investigationTask.duplicate) investigationCreationStamps.push(now);+ if (!investigationTask.duplicate) noteInvestigationFiled(now);emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId} — ${loopReason ? `held for approval (${loopReason})` : 'auto-approved'}`, {agentId,diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex 57d6dfb2bc..7effae5bfe 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -14,18 +14,21 @@ import {resolveTypeFailureSignal,maybeCreateInvestigationTask,createInvestigationTask,- buildInvestigationFingerprint,redactFailureSnippet,endsAwaitingUserInput,AWAITING_INPUT_TAIL_CHARS,MAX_TASK_RETRIES,INVESTIGATION_CIRCUIT_WINDOW_MS,INVESTIGATION_CIRCUIT_MAX_CREATIONS,+ __resetInvestigationCircuit+} from './agentErrorAnalysis.js';+// The pure policy + fingerprint moved to the shared leaf so every failure-driven+// producer reads one definition; the create path here still applies it.+import {INVESTIGATION_LOOP_WINDOW_MS,INVESTIGATION_STORM_HOLD_THRESHOLD,resolveInvestigationApproval,- __resetInvestigationCircuit-} from './agentErrorAnalysis.js';+} from '../lib/investigationTasks.js';import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';import { API_ACCESS_ERROR_CATEGORIES } from './agentErrorAnalysis.js';import { ENVIRONMENTAL_ERROR_CATEGORIES } from './taskLearning/metrics.js';@@ -492,20 +495,8 @@ describe('maybeCreateInvestigationTask', () => {});});-describe('buildInvestigationFingerprint', () => {- it('keys on category, analysisType/taskType, and app — never the free-text message', () => {- const fp = buildInvestigationFingerprint(- { id: 't', taskType: 'internal', metadata: { analysisType: 'app-improve', app: 'ExampleApp' } },- { category: 'startup-failure', message: 'raw output line that varies per run' }- );- expect(fp).toBe('startup-failure:app-improve:ExampleApp');- });-- it('falls back to taskType, then generic sentinels, when analysisType/app are absent', () => {- expect(buildInvestigationFingerprint({ id: 't', taskType: 'user', metadata: {} }, { category: 'unknown' })).toBe('unknown:user:none');- expect(buildInvestigationFingerprint({ id: 't' }, null)).toBe('unknown:task:none');- });-});+// `buildInvestigationFingerprint` itself is covered in+// `lib/investigationTasks.test.js` alongside the rest of the pure leaf.describe('createInvestigationTask guards (#2615)', () => {const failedTask = { id: 'task-1', description: 'do the thing', taskType: 'user', metadata: {} };@@ -676,13 +667,13 @@ describe('resolveInvestigationApproval (failure-loop policy, #3714)', () => {it('auto-approves an isolated failure — the default, so CoS diagnoses itself unattended', () => {expect(resolveInvestigationApproval({ fingerprint: FP, tasks: [], now: NOW }))- .toEqual({ approvalRequired: false, loopReason: null });+ .toMatchObject({ approvalRequired: false, loopReason: null, approvalReason: null });});it('holds for a human when the same cause was already investigated inside the loop window', () => {const tasks = [settled(INVESTIGATION_LOOP_WINDOW_MS - 1000)];expect(resolveInvestigationApproval({ fingerprint: FP, tasks, now: NOW }))- .toEqual({ approvalRequired: true, loopReason: 'repeat-fingerprint' });+ .toMatchObject({ approvalRequired: true, loopReason: 'repeat-fingerprint', approvalReason: 'investigation-loop:repeat-fingerprint' });});it('auto-approves again once the prior investigation ages out of the loop window', () => {@@ -708,7 +699,7 @@ describe('resolveInvestigationApproval (failure-loop policy, #3714)', () => {it('holds for a human once the circuit window is at the storm threshold', () => {expect(resolveInvestigationApproval({fingerprint: FP, tasks: [], recentCreations: INVESTIGATION_STORM_HOLD_THRESHOLD, now: NOW- })).toEqual({ approvalRequired: true, loopReason: 'failure-storm' });+ })).toMatchObject({ approvalRequired: true, loopReason: 'failure-storm', approvalReason: 'investigation-loop:failure-storm' });});it('leaves ordinary traffic below the storm threshold unattended', () => {diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex deb15d5099..ae857d0bec 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -32,6 +32,8 @@ import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';import { completeAgentRun } from './agentRunTracking.js';import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';+import { fileInvestigationTask } from './investigationTaskProducer.js';+import { buildInvestigationFingerprint } from '../lib/investigationTasks.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { readHostShutdownMarker, clearHostShutdownMarker, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { killProcessTree } from '../lib/bufferedSpawn.js';@@ -1316,18 +1318,21 @@ This task has been blocked after ${totalSpawns} total agent spawns. Investigate:3. Look for resource constraints (memory, CPU)4. Check for network/connection issues between services-Once the issue is resolved, reset the original task to pending.`;+Once the issue is resolved, task \`${taskId}\` is retried automatically — completing this task revives it.`;- await addTask({+ // Filed through the shared producer so this participates in the same+ // loop-aware approval policy, storm counter, and fingerprint dedup as every+ // other investigation (#3714), and so `affectedTasks` closes the loop: the+ // orphaned task comes back on its own when this one completes. Hardcoding+ // `approvalRequired: true` here is what turned one repeatedly-orphaned task+ // into a queue of approvals nobody asked for.+ await fileInvestigationTask({description,priority: 'HIGH',context: `Auto-generated from repeated orphan failures for task ${taskId}`,- // Requires approval, matching every other error-driven task creator- // (autoFixer.js, agentErrorAnalysis.js) — repeated orphaning is an- // infra/process-flakiness signal, not a diagnosed code bug, so an- // unsupervised agent shouldn't be turned loose on the codebase from it.- approvalRequired: true- }, 'internal').catch(err => {+ fingerprint: buildInvestigationFingerprint(task, { category: 'max-retries' }),+ affectedTasks: [taskId]+ }).catch(err => {emitLog('error', `Failed to create investigation task: ${err.message}`, { taskId, error: err.message });});}diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex ac64b36f69..b4e5c5568e 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -110,7 +110,7 @@ import { getAgents, updateAgent, getAgentRecord, completeAgent as markAgentComplimport { updateRun, getProject } from './creativeDirector/local.js';import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';-import { updateTask, addTask, getTaskById, reviveBlockedTask } from './cos.js';+import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask } from './cos.js';import { pauseAgentViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';@@ -272,7 +272,7 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {expect(addTask).not.toHaveBeenCalled();});- it('requires approval on the investigation task once orphan retries are exhausted', async () => {+ it('files the investigation unattended and links it back to the orphaned task for auto-retry', async () => {// orphanRetryCount: 2 -> retryCount 3 hits MAX_ORPHAN_RETRIES, tripping the// "else" branch that blocks the task and spawns an investigation task.const exhaustedTask = {@@ -283,14 +283,54 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {metadata: { orphanRetryCount: 2, totalSpawnCount: 2 }};const getTaskById = vi.fn().mockResolvedValue(exhaustedTask);+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });await handleOrphanedTask('task-foo', 'agent-orphaned', getTaskById);expect(addTask).toHaveBeenCalledTimes(1);expect(addTask.mock.calls[0][0]).toMatchObject({description: expect.stringContaining('[Auto-Fix] Investigate repeated agent orphaning'),+ approvalRequired: false,+ // The link the auto-retry reads: completing this investigation revives+ // `task-foo` instead of leaving it blocked for a human.+ isInvestigation: true,+ affectedTasks: ['task-foo'],+ // And the key the loop policy reads — without it stamped here, a repeat of+ // this same cause could never be recognized as a loop.+ investigationFingerprint: 'max-retries:user:none',+ });+ });++ it('holds the orphan investigation for a human when the same cause was already investigated today', async () => {+ const exhaustedTask = {+ id: 'task-foo',+ status: 'in_progress',+ taskType: 'user',+ description: 'Original work',+ metadata: { orphanRetryCount: 2, totalSpawnCount: 2 }+ };+ getAllTasks.mockResolvedValue({+ user: { tasks: [] },+ cos: {+ tasks: [{+ id: 'sys-prior',+ status: 'completed',+ metadata: {+ isInvestigation: true,+ investigationFingerprint: 'max-retries:user:none',+ updatedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ }+ }]+ }+ });++ await handleOrphanedTask('task-foo', 'agent-orphaned', vi.fn().mockResolvedValue(exhaustedTask));++ expect(addTask.mock.calls[0][0]).toMatchObject({approvalRequired: true,+ approvalReason: 'investigation-loop:repeat-fingerprint',});+ expect(addTask.mock.calls[0][0].description).toContain('Why this is held for you');});});diff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex 2562342c91..23e4e16416 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -5,7 +5,9 @@* Integrates with error handler and CoS task system*/-import { addTask, isRunning } from './cos.js';+import { isRunning } from './cos.js';+import { fileInvestigationTask, __resetInvestigationCircuit } from './investigationTaskProducer.js';+import { investigationFingerprint } from '../lib/investigationTasks.js';import { errorEvents } from '../lib/errorHandler.js';import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';@@ -439,6 +441,11 @@ export function _resetAutoFixerForTests() {failureTimestamps.clear();escalatedKeys.clear();pendingAutoFixTasks.length = 0;+ // This module's task-creation path now goes through the SHARED investigation+ // circuit (investigationTaskProducer.js), so a reset that stopped at the local+ // maps would leave earlier cases' creations counted against later ones — every+ // test past the storm threshold would then assert against a held task.+ __resetInvestigationCircuit();}/**@@ -537,12 +544,28 @@ async function createAIProviderInvestigationTask(error) {// resolve to a repo path, so every provider investigation was filed and// then rejected. Absent `app` resolves to that same PortOS root, and// matches the other two task producers in this file.- approvalRequired: true // Require user approval before investigating};- // If CoS is running, create the task immediately+ // If CoS is running, create the task immediately. The approval verdict is+ // resolved INSIDE this branch: on the other path the task is only queued for+ // later pickup, so a verdict computed now would be read against a backlog that+ // is stale by the time it is filed — and the read (both task files) buys+ // nothing.if (isRunning()) {- const task = await addTask(taskData, 'internal');+ // Unattended by default, matching every other investigation producer (#3714):+ // a provider failure is exactly the diagnosis CoS exists to do for itself, and+ // gating it behind an approval only meant the queue filled with approvals while+ // the provider stayed broken. The loop guards are unchanged and still upstream+ // of here — `isDuplicateError` collapses a repeat inside the dedupe window and+ // `tripCircuit` suppresses the task entirely past CIRCUIT_MAX_FAILURES.+ const { task } = await fileInvestigationTask({+ ...taskData,+ fingerprint: investigationFingerprint({+ category: diagnostics.category,+ kind: 'provider-failure',+ scope: ctx.provider+ })+ });console.log(`✅ AI provider investigation task created: ${task.id} [tier ${diagnostics.tier}: ${diagnostics.fixStrategy}]`);return task;}@@ -677,8 +700,8 @@ function buildAIProviderErrorContext(error, diagnostics) {*/async function createAutoFixTask(error) {// Structured diagnostics (issue #2328): a bare crash usually has no recognized- // category, so it classifies to Tier 4 (escalate) — which is exactly right for- // an unsupervised fix task that still requires human approval below.+ // category, so it classifies to Tier 4 (escalate) — an investigation rather+ // than a deterministic correction.const diagnostics = buildFixDiagnostics({triggerEvent: error.code,target: error.code,@@ -691,18 +714,22 @@ async function createAutoFixTask(error) {// Build context for the agentconst context = buildErrorContext(error);- // Create task in CoS system tasks. Requires approval, matching every other- // error-driven task creator in this file — a crash alone isn't enough- // signal to let an agent edit code unsupervised.- const taskData = {+ // Unattended by default, matching every other error-driven task creator in this+ // file. `shouldAutoFix` has already applied the dedupe + circuit breaker before+ // we get here, so this only fires for a genuinely new critical error, and the+ // shared policy still holds it for a human when the same cause is looping or+ // failures are cascading.+ const { task } = await fileInvestigationTask({description: `Fix critical error: ${error.message}`,priority: 'HIGH',context,diagnostics,- approvalRequired: true- };-- const task = await addTask(taskData, 'internal');+ fingerprint: investigationFingerprint({+ category: diagnostics.category,+ kind: 'critical-error',+ scope: error.code+ })+ });console.log(`✅ Auto-fix task created: ${task.id}`);return task;@@ -758,14 +785,17 @@ function buildErrorContext(error) {export async function handleErrorRecovery(errorCode, context) {console.log(`🔧 Manual error recovery requested: ${errorCode}`);- const taskData = {+ // No standing approval gate: the user clicking "investigate this error" IS the+ // approval, and asking them to approve their own request a second time is the+ // friction this whole path exists to remove. The shared loop policy can still+ // hold it — if they ask again about a cause we investigated hours ago, another+ // unattended agent would just repeat that run.+ const { task } = await fileInvestigationTask({description: `Investigate and fix error: ${errorCode}`,priority: 'MEDIUM',context: context || `User requested investigation of error code: ${errorCode}`,- approvalRequired: true // Manual recovery requires approval- };-- const task = await addTask(taskData, 'internal');+ fingerprint: investigationFingerprint({ kind: 'manual-recovery', scope: errorCode })+ });console.log(`✅ Recovery task created: ${task.id}`);return task;diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.jsindex fd50d0898d..e642372e9d 100644--- a/server/services/autoFixer.test.js+++ b/server/services/autoFixer.test.js@@ -1,12 +1,16 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// cos.js drags in a giant dependency graph (PM2, fs, sockets…) — mock it-// so autoFixer's defer/cancel behavior can be tested in isolation. Both-// exports the SUT touches are stubbed: `addTask` records what would be-// queued, `isRunning` toggles the running/not-running branches.+// so autoFixer's defer/cancel behavior can be tested in isolation. `addTask`+// records what would be queued, `isRunning` toggles the running/not-running+// branches, and `getAllTasks` feeds the shared investigation-approval policy+// (reached via agentErrorAnalysis) an empty backlog — no prior investigation and+// no storm, i.e. the ordinary unattended case.vi.mock('./cos.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'task-1' }),isRunning: vi.fn().mockReturnValue(true),+ updateTask: vi.fn().mockResolvedValue(true),+ getAllTasks: vi.fn().mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } }),}));const cos = await import('./cos.js');@@ -298,14 +302,15 @@ describe('autoFixer — generic critical-error auto-fix path', () => {_resetAutoFixerForTests();});- it('requires approval — a bare crash is too thin a signal for an unsupervised agent to patch code', async () => {+ it('files the fix task unattended — an isolated crash is what CoS diagnoses for itself', async () => {emitCriticalError({ message: 'Cannot read properties of undefined', stack: 'Error: boom\n at foo (file.js:1:1)' });await vi.advanceTimersByTimeAsync(0);expect(cos.addTask).toHaveBeenCalledTimes(1);expect(cos.addTask.mock.calls[0][0]).toMatchObject({description: 'Fix critical error: Cannot read properties of undefined',- approvalRequired: true,+ approvalRequired: false,+ approvalReason: null,});});@@ -314,7 +319,47 @@ describe('autoFixer — generic critical-error auto-fix path', () => {await vi.advanceTimersByTimeAsync(0);expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({ approvalRequired: true });+ expect(cos.addTask.mock.calls[0][0]).toMatchObject({ approvalRequired: false });+ });++ it('stamps the fingerprint the loop policy reads, so a repeat of the same cause is recognizable', async () => {+ emitCriticalError({ code: 'SOME_ERROR', message: 'first time', severity: 'error' });+ await vi.advanceTimersByTimeAsync(0);++ expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ isInvestigation: true,+ investigationFingerprint: 'unknown:critical-error:SOME_ERROR',+ });+ });++ it('holds the fix task for a human when the same cause was already investigated today', async () => {+ // A prior investigation carrying the fingerprint the production path above+ // actually writes, settled an hour ago — the fix did not hold, so another+ // unattended agent would just repeat it.+ cos.getAllTasks.mockResolvedValueOnce({+ user: { tasks: [] },+ cos: {+ tasks: [{+ id: 'sys-prior',+ status: 'completed',+ metadata: {+ isInvestigation: true,+ investigationFingerprint: 'unknown:critical-error:SOME_ERROR',+ updatedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ }+ }]+ }+ });++ emitCriticalError({ code: 'SOME_ERROR', message: 'the same failure, again', severity: 'error' });+ await vi.advanceTimersByTimeAsync(0);++ expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ approvalRequired: true,+ approvalReason: 'investigation-loop:repeat-fingerprint',+ });+ expect(cos.addTask.mock.calls[0][0].description).toContain('Why this is held for you');});it('does not fire for a non-critical error that is not marked auto-fixable', async () => {diff --git a/server/services/cos.js b/server/services/cos.jsindex 887c959017..3b97f9a217 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -78,6 +78,7 @@ import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getexport { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };import { ensureInstanceId } from './instances.js';import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';+import { retryTasksResolvedByInvestigation } from './investigationRetry.js';const AGENT_ARCHIVE_RETENTION_DAYS = 90;const RESUME_DEQUEUE_DELAY_MS = 500;@@ -1451,6 +1452,9 @@ export async function init() {// - 'requeued': an in_progress task flipped back to pending — a failed run's// retry released from its cleanup hold (#3373) or an orphan sweep requeue.// Newly spawnable, and long after the completion dequeue ran — re-run dequeue.+ // - a transition INTO `completed` (any action): if the finished task is an+ // INVESTIGATION, revive the failure-blocked task(s) it was diagnosing instead+ // of leaving them for a human to un-block by hand.cosEvents.on('tasks:changed', (data) => {if (!isDaemonRunning() || !data?.action) return;if (data.action === 'added') {@@ -1463,6 +1467,17 @@ export async function init() {if (data.type === 'user' && data.task) setImmediate(() => tryImmediateSpawn(data.task));} else if (data.action === 'approved' || data.action === 'unblocked' || data.action === 'requeued') {setImmediate(() => dequeueNextTask());+ } else if (data.task?.status === 'completed' && data.previousStatus !== 'completed') {+ // A finished investigation releases the task(s) its failure was blocking+ // (see investigationRetry.js). Keyed on the completion rather than on who+ // wrote it, so it covers BOTH an investigation agent finishing its run and+ // a human ticking the task off after fixing the cause by hand — and on the+ // TRANSITION, not the level, so a later edit to an already-completed+ // investigation can't spend a second auto-retry on a task that re-blocked.+ // The service no-ops for every other completed task, and each revive emits+ // its own `unblocked` above, which is what re-runs the dequeue.+ setImmediate(() => retryTasksResolvedByInvestigation(data.task)+ .catch(err => console.error(`❌ Auto-retry after investigation ${data.task?.id} failed: ${err.message}`)));}});diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 19efae9df3..e97ff41c75 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1141,6 +1141,17 @@ describe('cos.js source — priority + capacity invariants', () => {const handler = COS_SRC.slice(onIdx, COS_SRC.indexOf('});', onIdx) + 3);expect(handler).toMatch(/data\.action\s*===\s*'requeued'/);});++ // A finished investigation is what releases the failure-blocked task(s) it was+ // diagnosing. Without this branch the fix lands and the work it unblocked never+ // runs — the task sits `blocked` until a human notices or the 14-day reaper+ // quietly auto-expires it.+ it('tasks:changed listener hands a completed task to the investigation auto-retry', () => {+ const onIdx = COS_SRC.indexOf("cosEvents.on('tasks:changed'");+ const handler = COS_SRC.slice(onIdx, COS_SRC.indexOf('});', onIdx) + 3);+ expect(handler).toMatch(/data\.task\?\.status\s*===\s*'completed'/);+ expect(handler).toMatch(/retryTasksResolvedByInvestigation\(data\.task\)/);+ });});// A failed run's retry is held non-spawnable (`in_progress` + marker) while itsdiff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 5c59cd658f..b0885fb664 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -22,6 +22,8 @@ import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, isAgentPausedTask, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';+import { isInvestigationTask } from '../lib/investigationTasks.js';+import { PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';import { loadState, withStateLock, ROOT_DIR } from './cosState.js';import { cosEvents } from './cosEvents.js';import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';@@ -29,7 +31,6 @@ import { mergeTaskLists } from './cosTaskMerge.js';import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { runLocalCodeReview, getCodeReviewDefaults } from './codeReview.js';-import { isTruthyMeta } from './agentState.js';// First non-empty line of a string. Used by addTask dedup: stored descriptions// are flattened to a single line by generateTasksMarkdown, so the comparison@@ -46,16 +47,12 @@ export const PRIORITY_VALUES = {const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);-// Blocked categories that mean "paused until something outside the task-// changes", not "this task is finished with". A pause keeps the resume pointer-// (see updateTask) and is never auto-expired by the failure reaper (see-// NON_REAPABLE_BLOCKED_CATEGORIES, which includes these) — the task is expected-// to run again once the cooldown lapses or the user fixes the config.-export const PAUSED_BLOCKED_CATEGORIES = new Set([- 'orphan-cooldown', // timed cooldown; unblockExpiredOrphanCooldowns revives it- 'app-unresolved', // the task's app has no usable Repository Path- 'workspace-invalid' // the resolved workspace isn't a usable directory-]);+// The `blockedCategory` vocabulary lives in `lib/taskBlockCategories.js` — the+// pause logic, the failure reaper below, and the investigation auto-retry all+// have to answer "may I move this task?" from that one value, and each keeping+// its own literal set is how they drifted. Re-exported at the address callers+// already use.+export { PAUSED_BLOCKED_CATEGORIES };// A task is terminal once it is completed or blocked — the same set cosTaskMerge's// release-on-transition uses. Consumed by the LI cross-peer verdict consume (#2779) to@@ -731,7 +728,13 @@ async function writeTaskUpdate(taskId, updates, taskType, { now }) {const action = updatedTask.status === 'pending' && previousStatus === 'blocked'? 'unblocked': (updatedTask.status === 'pending' && previousStatus === 'in_progress' ? 'requeued' : 'updated');- cosEvents.emit('tasks:changed', { type: taskType, action, task: updatedTask });+ // `previousStatus` rides along so consumers can key on the TRANSITION rather+ // than re-deriving one from the level. `updateTask` on an already-terminal task+ // re-emits `updated` with the same status — an edit to a completed task's+ // description is enough — so a consumer that reacts to "reached completed"+ // (the investigation auto-retry; the voice completion line) needs the edge, not+ // `status === 'completed'`, which is true on every later write too.+ cosEvents.emit('tasks:changed', { type: taskType, action, task: updatedTask, previousStatus });return updatedTask;});}@@ -885,30 +888,11 @@ export const DEFAULT_FAILURE_TASK_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000; // 14 d// out an unbounded burst of writes/`tasks:changed` events after a large storm.export const DEFAULT_REAP_LIMIT = 50;-// Blocked categories that encode USER INTENT or an OPEN user decision, not a-// stale failure artifact — the reaper leaves these alone. Everything else with a-// `blockedCategory` is a failure-path block and therefore reapable.-const NON_REAPABLE_BLOCKED_CATEGORIES = new Set([- 'user-terminated', // user explicitly stopped the agent- AGENT_PAUSED_CATEGORY, // user paused; resumable on demand- 'challenge-escalation', // parked awaiting the user's arbitration- // The workspace blocks are an OPEN user decision, not a stale failure: the task- // is waiting for the app's Repository Path to be fixed, and auto-completing it- // at 14 days would silently retire work nobody decided to drop. (The third- // pause category, `orphan-cooldown`, stays reapable — it revives itself in- // ~30 minutes, so one still sitting there after 14 days IS stale.)- 'app-unresolved',- 'workspace-invalid'-]);--// Durable marker + legacy-headline fallback for an investigation task. Kept-// local (not imported from agentErrorAnalysis.js) to avoid a cosTaskStore ↔-// cos.js ↔ agentErrorAnalysis import cycle; the headline prefix is the one-// signal present on BOTH new and pre-#2615 investigation tasks.-const INVESTIGATION_HEADLINE_PREFIX = '[Auto] Investigate agent failure';-const isInvestigationTaskLocal = (task) =>- isTruthyMeta(task?.metadata?.isInvestigation) ||- (typeof task?.description === 'string' && task.description.trimStart().startsWith(INVESTIGATION_HEADLINE_PREFIX));+// Blocks that encode USER INTENT or an OPEN user decision are the reaper's+// exemption (`USER_DECISION_BLOCKED_CATEGORIES`, lib/taskBlockCategories.js).+// Everything else with a `blockedCategory` is a failure-path block and therefore+// reapable — including `orphan-cooldown`, which revives itself in ~30 minutes, so+// one still sitting there after 14 days IS stale./*** Age (ms) of a failure-blocked task, read from the most specific timestamp it@@ -919,7 +903,7 @@ const isInvestigationTaskLocal = (task) =>export function blockedFailureAgeMs(task, now = Date.now()) {if (task?.status !== 'blocked') return null;const category = task.metadata?.blockedCategory;- if (!category || NON_REAPABLE_BLOCKED_CATEGORIES.has(category)) return null;+ if (!category || USER_DECISION_BLOCKED_CATEGORIES.has(category)) return null;const stampedAt = task.metadata?.blockedAt|| task.metadata?.lastFailureAt|| task.metadata?.updatedAt;@@ -945,7 +929,7 @@ export function isReapableBlockedFailure(task, { now = Date.now(), maxAgeMs = DE* @param {Map} tasksById id → task across BOTH queues*/export function isReapableInvestigation(task, tasksById) {- if (!isInvestigationTaskLocal(task)) return false;+ if (!isInvestigationTask(task)) return false;if (task.status === 'completed') return false; // already terminalconst affected = Array.isArray(task.metadata?.affectedTasks) ? task.metadata.affectedTasks : [];if (affected.length === 0) return false;diff --git a/server/services/investigationRetry.js b/server/services/investigationRetry.jsnew file mode 100644index 0000000000..f57c2fe049--- /dev/null+++ b/server/services/investigationRetry.js@@ -0,0 +1,129 @@+/**+ * Investigation retry — put a failure-blocked task back in the queue as soon as+ * the investigation that diagnosed it finishes.+ *+ * The failure loop used to be open at both ends. #3714 closed the first half:+ * an agent failure files an investigation task that runs UNATTENDED, so nobody+ * has to approve the diagnosis. But the original task stayed `blocked` forever+ * after the fix landed — the only ways out were a human unblocking it by hand or+ * the 14-day reaper quietly auto-expiring it as stale. So the fix shipped and+ * the work it unblocked never ran.+ *+ * This module closes the second half: when an investigation task completes, the+ * tasks it named in `metadata.affectedTasks` are revived automatically. Bounded+ * by `MAX_AUTO_RETRIES_PER_TASK` so an unresolvable cause can't spin+ * investigate → retry → fail → investigate forever — past the budget the task+ * stays blocked, saying so, and the next same-cause investigation trips the+ * `repeat-fingerprint` hold, which IS the point where a human is the right+ * answer.+ *+ * Imports `cosTaskStore` directly rather than the `cos.js` facade: `cos.js`+ * subscribes to this module's entry point, so going back through the facade+ * would close a load-time cycle.+ */++import { getAllTasks, reviveBlockedTask, updateTask } from './cosTaskStore.js';+import { emitLog } from './cosEvents.js';+import {+ MAX_AUTO_RETRIES_PER_TASK,+ RETRY_SKIP_REASONS,+ affectedTaskIds,+ autoRetryMetadata,+ couldReleaseBlockedTasks,+ resolveInvestigationRetryTargets,+} from '../lib/investigationTasks.js';++// What a task's `blockedReason` becomes once the auto-retry loop gives up on it,+// so the queue says "the loop stopped trying" rather than still showing whatever+// failure blocked it two retries ago. Every other retry budget in CoS stamps its+// exhaustion onto the task; this one would otherwise report only to the journal,+// which is the one place the user won't look.+const RETRY_EXHAUSTED_CATEGORY = 'auto-retry-exhausted';++/**+ * Revive every still-blocked task the just-completed `investigation` was+ * tracking. A no-op (returning zero retried) for anything that is not a+ * genuinely-finished investigation, so the caller can hand it every completed+ * task without pre-filtering.+ *+ * Never throws: it runs off an event listener, outside the request lifecycle.+ *+ * @param {object} investigation the task that just reached `completed`+ * @returns {Promise<{ retried: string[], skipped: Array<{ taskId: string, reason: string }> }>}+ */+export async function retryTasksResolvedByInvestigation(investigation, { now = Date.now() } = {}) {+ // Answered from the task in hand, before any I/O — every task completion on the+ // install reaches this, and the reaper alone flips up to 50 investigations to+ // `completed` per sweep that release nothing (see couldReleaseBlockedTasks).+ if (!couldReleaseBlockedTasks(investigation)) return { retried: [], skipped: [] };++ // Index ONLY the ids this investigation names — usually one — rather than+ // cloning both whole queues to look them up. `getAllTasks` returns each queue's+ // raw tasks without a `taskType`, but the revive has to write back to the file+ // the task actually lives in, so stamp it from the queue it came out of.+ const wanted = new Set(affectedTaskIds(investigation));+ const { user, cos } = await getAllTasks();+ const tasksById = new Map();+ for (const [taskType, list] of [['user', user?.tasks || []], ['internal', cos?.tasks || []]]) {+ for (const task of list) if (wanted.has(task.id)) tasksById.set(task.id, { ...task, taskType });+ }++ const { targets, skipped } = resolveInvestigationRetryTargets({ investigation, tasksById });++ const retried = [];+ for (const task of targets) {+ // `reviveBlockedTask` clears the block + failure/spawn budgets and emits+ // `tasks:changed` action `unblocked`, which wakes the dequeue — so the retry+ // starts on its own without a second signal from here.+ const result = await reviveBlockedTask(+ task.id,+ { metadata: autoRetryMetadata(task, investigation.id, now) },+ task.taskType+ ).catch((err) => ({ error: err.message }));++ if (result?.error) {+ emitLog('warn', `⚠️ Auto-retry of task ${task.id} after investigation ${investigation.id} failed: ${result.error}`, {+ taskId: task.id, investigationTaskId: investigation.id+ });+ continue;+ }+ retried.push(task.id);+ }++ await markExhaustedTasks(skipped, tasksById, investigation.id, now);++ if (retried.length > 0) {+ emitLog('info', `🔁 Investigation ${investigation.id} resolved — auto-retrying ${retried.length} blocked task(s): ${retried.join(', ')}`, {+ taskId: investigation.id, retried: retried.length, skipped: skipped.length+ });+ } else if (skipped.length > 0) {+ emitLog('debug', `⏭️ Investigation ${investigation.id} revived nothing: ${skipped.map(s => `${s.taskId} (${s.reason})`).join(', ')}`, {+ taskId: investigation.id, skipped: skipped.length+ });+ }+ return { retried, skipped };+}++/**+ * Re-label the tasks whose auto-retry budget just ran out, so the task list says+ * the loop gave up instead of still showing the original failure. Idempotent —+ * a task already carrying the category is left alone, so a second investigation+ * naming it doesn't rewrite the same reason. Best-effort: a failed re-label must+ * not lose the retries that did land.+ */+async function markExhaustedTasks(skipped, tasksById, investigationId, now) {+ for (const { taskId, reason } of skipped) {+ if (reason !== RETRY_SKIP_REASONS.BUDGET_EXHAUSTED) continue;+ const task = tasksById.get(taskId);+ if (task?.metadata?.blockedCategory === RETRY_EXHAUSTED_CATEGORY) continue;+ await updateTask(taskId, {+ metadata: {+ blockedReason: `Auto-retry gave up after ${MAX_AUTO_RETRIES_PER_TASK} attempts — the same cause keeps blocking this task`,+ blockedCategory: RETRY_EXHAUSTED_CATEGORY,+ autoRetryExhaustedAt: new Date(now).toISOString(),+ }+ }, task?.taskType || 'internal').catch((err) => {+ emitLog('warn', `⚠️ Could not mark task ${taskId} auto-retry-exhausted after investigation ${investigationId}: ${err.message}`, { taskId });+ });+ }+}diff --git a/server/services/investigationRetry.test.js b/server/services/investigationRetry.test.jsnew file mode 100644index 0000000000..31a4397eac--- /dev/null+++ b/server/services/investigationRetry.test.js@@ -0,0 +1,146 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./cosTaskStore.js', () => ({+ getAllTasks: vi.fn(),+ reviveBlockedTask: vi.fn().mockResolvedValue({ id: 'ok' }),+ updateTask: vi.fn().mockResolvedValue({ id: 'ok' }),+}));+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));++const { getAllTasks, reviveBlockedTask, updateTask } = await import('./cosTaskStore.js');+const { retryTasksResolvedByInvestigation } = await import('./investigationRetry.js');++const investigation = (metadata = {}) => ({+ id: 'sys-inv',+ status: 'completed',+ metadata: { isInvestigation: true, affectedTasks: ['task-1'], ...metadata },+});++const queues = ({ user = [], cos = [] } = {}) => ({ user: { tasks: user }, cos: { tasks: cos } });++describe('retryTasksResolvedByInvestigation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ reviveBlockedTask.mockResolvedValue({ id: 'ok' });+ updateTask.mockResolvedValue({ id: 'ok' });+ });++ it('revives the blocked task the investigation was diagnosing, stamping the auto-retry budget', async () => {+ getAllTasks.mockResolvedValue(queues({+ user: [{ id: 'task-1', status: 'blocked', metadata: { blockedCategory: 'test-failure' } }]+ }));++ const result = await retryTasksResolvedByInvestigation(investigation(), { now: 1_700_000_000_000 });++ expect(result.retried).toEqual(['task-1']);+ expect(reviveBlockedTask).toHaveBeenCalledWith(+ 'task-1',+ {+ metadata: {+ autoRetryCount: 1,+ autoRetriedByInvestigation: 'sys-inv',+ autoRetriedAt: new Date(1_700_000_000_000).toISOString(),+ }+ },+ // Written back to the queue the task actually lives in — `getAllTasks`+ // returns raw tasks with no `taskType`, so this must come from the queue.+ 'user'+ );+ });++ it('routes an internal-queue task back to the internal file', async () => {+ getAllTasks.mockResolvedValue(queues({+ cos: [{ id: 'task-1', status: 'blocked', metadata: {} }]+ }));++ await retryTasksResolvedByInvestigation(investigation());++ expect(reviveBlockedTask.mock.calls[0][2]).toBe('internal');+ });++ it('is a no-op for a completed task that is not an investigation — no task file is even read', async () => {+ const result = await retryTasksResolvedByInvestigation({+ id: 'task-9', status: 'completed', description: 'Ordinary work', metadata: {}+ });++ expect(result).toEqual({ retried: [], skipped: [] });+ expect(getAllTasks).not.toHaveBeenCalled();+ expect(reviveBlockedTask).not.toHaveBeenCalled();+ });++ it('is a no-op for an investigation that has not completed', async () => {+ await retryTasksResolvedByInvestigation({ ...investigation(), status: 'in_progress' });+ expect(getAllTasks).not.toHaveBeenCalled();+ });++ // The reaper flips up to 50 investigations to `completed` per sweep with this+ // marker; each one reaching the file read would cost 100 discarded reads and+ // parses on the same tick the reaper is writing those very files.+ it('skips the file read entirely for an auto-expired completion', async () => {+ await retryTasksResolvedByInvestigation(investigation({ resolution: 'auto-expired' }));+ expect(getAllTasks).not.toHaveBeenCalled();+ });++ it('skips the file read entirely for an investigation that names no affected task', async () => {+ await retryTasksResolvedByInvestigation(investigation({ affectedTasks: [] }));+ expect(getAllTasks).not.toHaveBeenCalled();+ });++ it('says so on the task when the auto-retry budget runs out, rather than only in the log', async () => {+ getAllTasks.mockResolvedValue(queues({+ user: [{ id: 'task-1', status: 'blocked', metadata: { autoRetryCount: 2 } }]+ }));++ const result = await retryTasksResolvedByInvestigation(investigation());++ expect(result.retried).toEqual([]);+ expect(result.skipped).toEqual([{ taskId: 'task-1', reason: 'auto-retry-budget-exhausted' }]);+ expect(reviveBlockedTask).not.toHaveBeenCalled();+ // The task list would otherwise still show whatever failure blocked it two+ // retries ago, with nothing saying the loop gave up.+ expect(updateTask).toHaveBeenCalledWith(+ 'task-1',+ { metadata: expect.objectContaining({ blockedCategory: 'auto-retry-exhausted' }) },+ 'user'+ );+ });++ it('does not re-stamp a task already marked auto-retry-exhausted', async () => {+ getAllTasks.mockResolvedValue(queues({+ user: [{ id: 'task-1', status: 'blocked', metadata: { autoRetryCount: 2, blockedCategory: 'auto-retry-exhausted' } }]+ }));++ await retryTasksResolvedByInvestigation(investigation());++ expect(updateTask).not.toHaveBeenCalled();+ });++ it('keeps going when one revive fails — the other affected tasks still come back', async () => {+ getAllTasks.mockResolvedValue(queues({+ user: [+ { id: 'task-1', status: 'blocked', metadata: {} },+ { id: 'task-2', status: 'blocked', metadata: {} },+ ]+ }));+ reviveBlockedTask+ .mockResolvedValueOnce({ error: 'Task file not found' })+ .mockResolvedValueOnce({ id: 'task-2' });++ const result = await retryTasksResolvedByInvestigation(+ investigation({ affectedTasks: ['task-1', 'task-2'] })+ );++ expect(result.retried).toEqual(['task-2']);+ });++ it('does not throw when a revive rejects — it runs off an event listener', async () => {+ getAllTasks.mockResolvedValue(queues({+ user: [{ id: 'task-1', status: 'blocked', metadata: {} }]+ }));+ reviveBlockedTask.mockRejectedValue(new Error('disk on fire'));++ await expect(retryTasksResolvedByInvestigation(investigation())).resolves.toEqual({+ retried: [], skipped: []+ });+ });+});diff --git a/server/services/investigationTaskProducer.js b/server/services/investigationTaskProducer.jsnew file mode 100644index 0000000000..bd98b16257--- /dev/null+++ b/server/services/investigationTaskProducer.js@@ -0,0 +1,138 @@+/**+ * Investigation-task producer — the one place a failure-driven task is filed.+ *+ * Four producers file "something broke, go find out why" tasks: an agent failure+ * (`agentErrorAnalysis.js`), an AI-provider failure and an uncaught crash+ * (`autoFixer.js`), and repeated agent orphaning (`agentManagement.js`). They all+ * have to agree on the same three things, and when each hand-assembled them they+ * did not:+ *+ * - the APPROVAL verdict — unattended by default, held only on a failure loop;+ * - the MARKERS (`isInvestigation`, `investigationFingerprint`, `affectedTasks`,+ * `approvalReason`) that the dedup scan, the reaper, the meta-cascade guard,+ * and the auto-retry all read;+ * - the STORM COUNTER, which is only a real signal if every producer both reads+ * it and contributes to it.+ *+ * Before this module, three of the four wrote no fingerprint at all — so+ * `repeat-fingerprint` could never fire for them — and only one pushed a+ * creation stamp, so `failure-storm` counted a quarter of the storm.+ *+ * Goes through the `cos.js` facade for its task I/O, matching the producers it+ * was extracted from — every one of them already imports `cos.js`, so this adds+ * no module edge, and `cos.js` imports nothing from here. (The RETRY side,+ * `investigationRetry.js`, must use `cosTaskStore` directly instead: `cos.js`+ * subscribes to it, so the facade would close a load-time cycle there.)+ */++import { addTask, getAllTasks } from './cos.js';+import {+ INVESTIGATION_CIRCUIT_MAX_CREATIONS,+ INVESTIGATION_CIRCUIT_WINDOW_MS,+ UNATTENDED_APPROVAL_VERDICT,+ resolveInvestigationApproval,+} from '../lib/investigationTasks.js';++let investigationCreationStamps = []; // ms timestamps, newest-last++/**+ * How many investigation creations are still inside the rolling circuit window.+ * Prunes aged-out stamps as a side effect, so the circuit auto-closes without a+ * manual reset. The count (not just a boolean "open?") is what callers need: at+ * the cap the task is suppressed entirely, and below the cap a non-zero count is+ * the `failure-storm` loop signal that holds it for a human.+ */+export function recentInvestigationCreations(now = Date.now()) {+ investigationCreationStamps = investigationCreationStamps.filter(t => now - t < INVESTIGATION_CIRCUIT_WINDOW_MS);+ return investigationCreationStamps.length;+}++/** Is the circuit OPEN — i.e. should this producer suppress the task entirely? */+export function investigationCircuitOpen(now = Date.now()) {+ return recentInvestigationCreations(now) >= INVESTIGATION_CIRCUIT_MAX_CREATIONS;+}++/**+ * Record a genuine creation against the shared circuit. Producers call this after+ * `addTask` actually mints a task — a description-level dedup returning an+ * existing task is not a new creation and must not count.+ */+export function noteInvestigationFiled(now = Date.now()) {+ investigationCreationStamps.push(now);+}++/** Test hook — the stamp list is module state, so suites reset it between cases. */+export function __resetInvestigationCircuit() {+ investigationCreationStamps = [];+}++/** Every task across both queues, flattened. */+export async function readAllTasksFlat() {+ const { user, cos } = await getAllTasks();+ return [...(user?.tasks || []), ...(cos?.tasks || [])];+}++/**+ * The approval verdict for a new investigation, read against the live backlog.+ * The async half of the pure `resolveInvestigationApproval`.+ *+ * FAILS OPEN: a policy read that throws must not put the diagnosis back behind a+ * human — that is the stall this whole mechanism exists to remove. Callers get+ * the unattended verdict and file the task.+ *+ * @param {string} fingerprint the failure's `category:kind:scope` dedup key+ * @param {{ now?: number, tasks?: object[] }} [opts] `tasks` lets a caller that+ * already read the backlog (the agent-failure producer does, for its dedup+ * scan) skip a second read of both task files.+ */+export async function resolveAutoInvestigationApproval(fingerprint, { now = Date.now(), tasks } = {}) {+ const backlog = tasks || await readAllTasksFlat().catch(() => null);+ if (!backlog) return UNATTENDED_APPROVAL_VERDICT;+ return resolveInvestigationApproval({+ fingerprint,+ tasks: backlog,+ recentCreations: recentInvestigationCreations(now),+ now+ });+}++/**+ * File an investigation task with the shared verdict + markers, and record it+ * against the circuit.+ *+ * For the producers whose failure has no per-task dedup of its own (the provider,+ * crash, and orphan paths — each already guarded upstream by its own dedupe and+ * circuit breaker). The agent-failure producer keeps its own creation path: it+ * carries a durable fingerprint dedup that must union a repeat failure into the+ * SURVIVING investigation rather than file a new one, plus a serialization tail+ * closing the TOCTOU between the scan and the write.+ *+ * A held task gets the "why this is held for you" prose appended as a section, so+ * the user reading the queue does not have to infer why this one stopped for them.+ *+ * @param {{ fingerprint: string, description: string, affectedTasks?: string[] }} args+ * plus any further `addTask` fields (priority, context, diagnostics)+ * @returns {Promise<{ task: object|null, approvalRequired: boolean, loopReason: string|null }>}+ */+export async function fileInvestigationTask({ fingerprint, description, affectedTasks = [], ...extra } = {}, { now = Date.now() } = {}) {+ const verdict = await resolveAutoInvestigationApproval(fingerprint, { now });+ const body = verdict.loopProse+ ? `${description}\n\n## Why this is held for you\n${verdict.loopProse}`+ : description;++ const task = await addTask({+ ...extra,+ description: body,+ approvalRequired: verdict.approvalRequired,+ approvalReason: verdict.approvalReason,+ // The markers the shared machinery reads: the dedup scan and the loop policy+ // (fingerprint), the meta-cascade guard and the reaper (isInvestigation), and+ // the auto-retry that revives the blocked work (affectedTasks).+ isInvestigation: true,+ investigationFingerprint: fingerprint,+ ...(affectedTasks.length > 0 && { affectedTasks })+ }, 'internal');++ if (!task?.duplicate) noteInvestigationFiled(now);+ return { task, approvalRequired: verdict.approvalRequired, loopReason: verdict.loopReason };+}diff --git a/server/services/investigationTaskProducer.test.js b/server/services/investigationTaskProducer.test.jsnew file mode 100644index 0000000000..32ee4b439d--- /dev/null+++ b/server/services/investigationTaskProducer.test.js@@ -0,0 +1,123 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./cos.js', () => ({+ addTask: vi.fn().mockResolvedValue({ id: 'sys-1' }),+ getAllTasks: vi.fn().mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } }),+}));++const { addTask, getAllTasks } = await import('./cos.js');+const {+ fileInvestigationTask,+ investigationCircuitOpen,+ recentInvestigationCreations,+ resolveAutoInvestigationApproval,+ __resetInvestigationCircuit,+} = await import('./investigationTaskProducer.js');+const { INVESTIGATION_CIRCUIT_MAX_CREATIONS, INVESTIGATION_CIRCUIT_WINDOW_MS } = await import('../lib/investigationTasks.js');++const emptyBacklog = () => getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });++const settledInvestigation = (fingerprint, agoMs = 60 * 60 * 1000) => ({+ id: 'sys-prior',+ status: 'completed',+ metadata: {+ isInvestigation: true,+ investigationFingerprint: fingerprint,+ updatedAt: new Date(Date.now() - agoMs).toISOString(),+ }+});++describe('fileInvestigationTask', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ addTask.mockResolvedValue({ id: 'sys-1' });+ emptyBacklog();+ __resetInvestigationCircuit();+ });++ it('files unattended by default, with every marker the shared machinery reads', async () => {+ await fileInvestigationTask({+ fingerprint: 'auth-error:provider-failure:Example CLI',+ description: 'Investigate AI provider failure',+ priority: 'MEDIUM',+ affectedTasks: ['task-7'],+ });++ expect(addTask).toHaveBeenCalledWith({+ description: 'Investigate AI provider failure',+ priority: 'MEDIUM',+ approvalRequired: false,+ approvalReason: null,+ isInvestigation: true,+ investigationFingerprint: 'auth-error:provider-failure:Example CLI',+ affectedTasks: ['task-7'],+ }, 'internal');+ });++ it('omits affectedTasks entirely when the failure has no originating task', async () => {+ await fileInvestigationTask({ fingerprint: 'unknown:critical-error:BOOM', description: 'Fix critical error' });+ expect(addTask.mock.calls[0][0]).not.toHaveProperty('affectedTasks');+ });++ it('holds for a human — and says why in the body — when the same cause is looping', async () => {+ getAllTasks.mockResolvedValue({+ user: { tasks: [] },+ cos: { tasks: [settledInvestigation('unknown:critical-error:BOOM')] }+ });++ const { approvalRequired, loopReason } = await fileInvestigationTask({+ fingerprint: 'unknown:critical-error:BOOM',+ description: 'Fix critical error',+ });++ expect({ approvalRequired, loopReason }).toEqual({ approvalRequired: true, loopReason: 'repeat-fingerprint' });+ expect(addTask.mock.calls[0][0]).toMatchObject({ approvalReason: 'investigation-loop:repeat-fingerprint' });+ expect(addTask.mock.calls[0][0].description).toContain('## Why this is held for you');+ });++ it('counts every producer against ONE storm counter', async () => {+ for (let i = 0; i < INVESTIGATION_CIRCUIT_MAX_CREATIONS; i++) {+ await fileInvestigationTask({ fingerprint: `unknown:critical-error:E${i}`, description: `Fix ${i}` });+ }+ expect(recentInvestigationCreations()).toBe(INVESTIGATION_CIRCUIT_MAX_CREATIONS);+ expect(investigationCircuitOpen()).toBe(true);+ });++ it('does not count a description-level duplicate as a new creation', async () => {+ addTask.mockResolvedValue({ id: 'sys-existing', duplicate: true });+ await fileInvestigationTask({ fingerprint: 'unknown:critical-error:BOOM', description: 'Fix critical error' });+ expect(recentInvestigationCreations()).toBe(0);+ });++ it('lets the circuit auto-close as creations age out of the window', async () => {+ await fileInvestigationTask({ fingerprint: 'unknown:critical-error:BOOM', description: 'Fix' });+ expect(recentInvestigationCreations()).toBe(1);+ expect(recentInvestigationCreations(Date.now() + INVESTIGATION_CIRCUIT_WINDOW_MS + 1)).toBe(0);+ });+});++describe('resolveAutoInvestigationApproval', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ __resetInvestigationCircuit();+ });++ it('fails OPEN to unattended when the backlog cannot be read', async () => {+ // A policy read that throws must never put the diagnosis back behind a human —+ // that stall is the whole thing this mechanism exists to remove.+ getAllTasks.mockRejectedValue(new Error('task file unreadable'));++ await expect(resolveAutoInvestigationApproval('unknown:task:none')).resolves.toMatchObject({+ approvalRequired: false, loopReason: null, approvalReason: null+ });+ });++ it('reuses a backlog the caller already read instead of reading it again', async () => {+ const verdict = await resolveAutoInvestigationApproval('unknown:critical-error:BOOM', {+ tasks: [settledInvestigation('unknown:critical-error:BOOM')]+ });++ expect(verdict.loopReason).toBe('repeat-fingerprint');+ expect(getAllTasks).not.toHaveBeenCalled();+ });+});