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
stop recording a provider relaunch as a failed agent run
[._.]/ Adam Eivy2ab30feefcf6
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 71bac22a0f..8a145ff492 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -32,6 +32,7 @@ import CollapsibleText from '../../ui/CollapsibleText';import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';import { extractCosTaskType } from '../../../lib/cosTaskType';+import { isAgentHandoff } from '../../../lib/agentOutcome';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';import { formatBytes, formatDurationMs, formatDateTime, formatTimeOfDay } from '../../../utils/formatters';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';@@ -252,6 +253,13 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,// Only agents from a manually-filled task form ask for a rating —// scheduled/autopilot runs are already auto-evaluated by task-learning.const isManualUserAgent = agent.metadata?.taskType === 'user';+ // Retired by Resume/Relaunch: this run handed its task to a continuation+ // instead of reaching a verdict, so it is neither a success nor a failure.+ const handoff = isAgentHandoff(agent);+ // `pauseReason` first: on a Relaunch it is the line the user is actually looking+ // for ("Relaunched by user on codex / gpt-5"), while `result.error` holds the+ // resume summary, which says where the TASK went rather than why this run stopped.+ const handoffReason = agent.metadata?.pauseReason || agent.result?.error || 'Handed off to a new run';const inactive = completed || paused;// Handle feedback submission@@ -588,6 +596,19 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,{isSystemAgent && (<span className="px-1.5 py-0.5 text-xs bg-gray-500/20 text-gray-400 rounded shrink-0">SYS</span>)}+ {/* This run took over a paused/relaunched one. The predecessor's card+ says it handed off; this is the other half of that pair. */}+ {agent.metadata?.resumedFromAgentId && (+ <Link+ to={`/cos/agents/${agent.metadata.resumedFromAgentId}`}+ onClick={(event) => event.stopPropagation()}+ className="px-1.5 py-0.5 text-xs bg-port-accent/20 text-port-accent rounded shrink-0 inline-flex items-center gap-1 hover:bg-port-accent/30 transition-colors"+ title={`Continues agent ${agent.metadata.resumedFromAgentId}`}+ >+ <RotateCcw size={11} aria-hidden="true" />+ Continues {agent.metadata.resumedFromAgentId.slice(0, 8)}+ </Link>+ )}{agent.metadata?.model && (<span className={`px-2 py-0.5 text-xs rounded min-w-0 max-w-full break-words ${['heavy', 'ultra'].includes(agent.metadata.modelTier) ? 'bg-purple-500/20 text-purple-400' :@@ -904,8 +925,17 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,{agent.result && (<div className="flex items-center gap-4 flex-wrap">- <div className={`text-sm flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>- {agent.result.success ? (+ {/* Three outcomes, not two. A run retired by Resume/Relaunch carries+ `success: false` because it never reached a verdict — its task was+ handed to a continuation, usually because the user swapped providers+ after hitting a usage limit. Painting that red said the run failed,+ for something the user did on purpose. */}+ <div className={`text-sm flex items-center gap-2 ${+ handoff ? 'text-port-accent' : agent.result.success ? 'text-port-success' : 'text-port-error'+ }`}>+ {handoff ? (+ <><RotateCcw size={14} aria-hidden="true" /> {handoffReason}</>+ ) : agent.result.success ? (<><CheckCircle size={14} aria-hidden="true" /> Completed successfully</>) : (<><AlertCircle size={14} aria-hidden="true" /> {agent.result.error || 'Failed'}</>@@ -965,8 +995,10 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,</div>)}- {/* Feedback section - shown for completed, manually-run, non-system local agents */}- {completed && !isSystemAgent && isManualUserAgent && !remote && (+ {/* Feedback section - shown for completed, manually-run, non-system local+ agents. A handoff is excluded: there is no result to rate, and the+ continuation run asks for the rating that covers this work. */}+ {completed && !isSystemAgent && isManualUserAgent && !remote && !handoff && (<div className="mt-2 pt-1 border-t border-port-border/50"><div className="flex items-center gap-3 flex-wrap"><span className="text-xs text-gray-500">Was this helpful?</span>diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex 2f0c8c60e3..616582a88d 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -167,6 +167,101 @@ describe('AgentCard runtime presentation', () => {});});+describe('AgentCard relaunch handoff', () => {+ // What Relaunch leaves behind. The pause/requeue path reuses the completion+ // shape, so the retired record carries `success: false` with the swap summary+ // in `error` — which the card used to paint red as a failed run, for something+ // the user did deliberately when a provider hit its usage limit.+ const handoffAgent = {+ ...agent,+ result: {+ success: false,+ duration: 3600000,+ resumed: true,+ resumedTaskId: 'task-example',+ error: 'Relaunched by user on codex / gpt-5',+ },+ };++ it('presents a relaunched run as a handoff rather than a failure', () => {+ render(+ <MemoryRouter>+ <AgentCard agent={handoffAgent} completed />+ </MemoryRouter>+ );++ const summary = screen.getByText('Relaunched by user on codex / gpt-5');+ expect(summary).toBeInTheDocument();+ // The color is the message here: red says the run broke.+ expect(summary.closest('div').className).toContain('text-port-accent');+ expect(summary.closest('div').className).not.toContain('text-port-error');+ });++ it('names what the user changed, not where the task went', () => {+ // `result.error` on these records is the RESUME summary ("task … requeued on+ // <branch>"), which answers a question nobody asked while looking at the run+ // they just relaunched. The pause reason is the one that says "on codex".+ render(+ <MemoryRouter>+ <AgentCard+ agent={{+ ...handoffAgent,+ metadata: { ...handoffAgent.metadata, pauseReason: 'Relaunched by user on codex / gpt-5' },+ result: { ...handoffAgent.result, error: 'Resumed agent agent-example — task task-example requeued on cos/task-example/agent-example' },+ }}+ completed+ />+ </MemoryRouter>+ );++ expect(screen.getByText('Relaunched by user on codex / gpt-5')).toBeInTheDocument();+ });++ it('does not ask for a rating on a run that never reached a result', () => {+ render(+ <MemoryRouter>+ <AgentCard agent={handoffAgent} completed />+ </MemoryRouter>+ );++ expect(screen.queryByText('Was this helpful?')).not.toBeInTheDocument();+ });++ it('still shows a genuine failure in red, with its rating buttons', () => {+ // The bypass probe: a card that softened EVERY unsuccessful run would pass+ // both assertions above while hiding real failures.+ const failed = { ...agent, result: { success: false, duration: 3600000, error: 'exit code 1' } };++ render(+ <MemoryRouter>+ <AgentCard agent={failed} completed />+ </MemoryRouter>+ );++ expect(screen.getByText('exit code 1').closest('div').className).toContain('text-port-error');+ expect(screen.getByText('Was this helpful?')).toBeInTheDocument();+ });++ it('links a continuation back to the run it took over', () => {+ // The other half of the pair. Without it the two cards read as one run that+ // mysteriously stopped and a second that appeared from nowhere.+ const continuation = {+ ...agent,+ id: 'agent-continuation',+ metadata: { ...agent.metadata, resumedFromAgentId: 'agent-example' },+ };++ render(+ <MemoryRouter>+ <AgentCard agent={continuation} completed />+ </MemoryRouter>+ );++ const link = screen.getByTitle('Continues agent agent-example');+ expect(link).toHaveAttribute('href', '/cos/agents/agent-example');+ });+});+describe('AgentCard feedback', () => {it('hides the rating UI for a completed scheduled/autopilot agent (taskType internal)', () => {const internalAgent = {diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsxindex 40256b19f7..9f7a72f087 100644--- a/client/src/components/cos/tabs/AgentsTab.jsx+++ b/client/src/components/cos/tabs/AgentsTab.jsx@@ -9,6 +9,7 @@ import RelaunchAgentModal from './RelaunchAgentModal';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';import { agentResumeMessage } from '../../../lib/agentResumeOutcome';+import { isAgentHandoff } from '../../../lib/agentOutcome';// What each `resumeAgent` outcome actually did (server modes, agentManagement.js).// `already-active` and `superseded` deliberately queue NOTHING — the task is already@@ -33,10 +34,14 @@ const RESUME_MESSAGES = {// Only agents from a manually-filled task form ask for a rating — scheduled/// autopilot runs (taskType 'internal') are already auto-evaluated by// task-learning's success/failure tracking. See cosAgentFeedback.js.+// A run retired by Resume/Relaunch is excluded too — it has no result to rate,+// and the continuation it handed the task to is the run that asks for the rating.+// Without this, every provider swap left a permanent entry in the needs-feedback+// count that nothing the user does can clear (AgentCard hides the buttons).const needsAgentFeedback = (agent) => {const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');const isManualUserAgent = agent.metadata?.taskType === 'user';- return !isSystemAgent && isManualUserAgent && !agent.feedback?.rating;+ return !isSystemAgent && isManualUserAgent && !isAgentHandoff(agent) && !agent.feedback?.rating;};export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsxindex d56802876b..8b4dca532b 100644--- a/client/src/components/cos/tabs/ResumeAgentModal.jsx+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx@@ -7,6 +7,7 @@ import FilePickerButton from '../../ui/FilePickerButton';import { FormField } from '../../ui/FormField';import EffortSelect from '../EffortSelect';import { effectiveModelFor, effortAwareModelOptions, effortSurvivingModel, seedModelEffort } from '../../../utils/providers';+import { isAgentHandoff } from '../../../lib/agentOutcome';export default function ResumeAgentModal({ agent, taskType = 'user', providers, providersLoaded = true, apps, onSubmit, onClose }) {// A paused agent resumes IN PLACE: its own task is requeued on the worktree its@@ -17,8 +18,17 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,const outputSummary = agent.output?.length > 0? agent.output.slice(-20).map(o => o.line).join('\n'): '';+ // A run retired by Resume/Relaunch never reached a verdict. This string is+ // pasted into the NEW run's context, so calling it a failure would tell the+ // agent its predecessor broke when the user simply moved it to another provider.+ const handoff = isAgentHandoff(agent);+ // `pauseReason` first, for the same reason as the card: on a Relaunch it names+ // what the user changed, while `result.error` holds the resume summary.+ const handoffReason = agent.metadata?.pauseReason || agent.result?.error || 'relaunched on a different provider';const resultInfo = agent.result- ? (agent.result.success ? 'Previous run: Completed successfully' : `Previous run: Failed - ${agent.result.error || 'Unknown error'}`)+ ? (handoff+ ? `Previous run: Handed off - ${handoffReason}`+ : agent.result.success ? 'Previous run: Completed successfully' : `Previous run: Failed - ${agent.result.error || 'Unknown error'}`): '';const pauseInfo = isPaused? `Previous run: Paused${agent.metadata?.pauseReason ? ` - ${agent.metadata.pauseReason}` : ''}`@@ -148,8 +158,12 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,</div>)}{agent.result && (- <div className={`text-sm mt-2 flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>- {agent.result.success ? (+ <div className={`text-sm mt-2 flex items-center gap-2 ${+ handoff ? 'text-port-accent' : agent.result.success ? 'text-port-success' : 'text-port-error'+ }`}>+ {handoff ? (+ <><RotateCcw size={14} /> {handoffReason}</>+ ) : agent.result.success ? (<><CheckCircle size={14} /> Completed successfully</>) : (<><AlertCircle size={14} /> {agent.result.error || 'Failed'}</>diff --git a/client/src/hooks/useAgentFeedbackToast.jsx b/client/src/hooks/useAgentFeedbackToast.jsxindex cf7f9fca23..2b0460c70a 100644--- a/client/src/hooks/useAgentFeedbackToast.jsx+++ b/client/src/hooks/useAgentFeedbackToast.jsx@@ -4,6 +4,7 @@ import { ThumbsUp, ThumbsDown, Loader2, AlertTriangle } from 'lucide-react';import socket from '../services/socket';import * as api from '../services/api';import OutputBlocks from '../components/cos/OutputBlocks';+import { isAgentHandoff } from '../lib/agentOutcome';const AUTO_DISMISS_MS = 15000;@@ -170,7 +171,11 @@ export function useAgentFeedbackToast() {const agentId = data?.id || data?.agentId;const isSystem = data?.taskId?.startsWith('sys-') || agentId?.startsWith('sys-');- if (!agentId || isSystem || shownFeedbackFor.current.has(agentId)) {+ // A record Resume/Relaunch retired is a handoff, not a completion: pressing+ // Relaunch popped "✗ Agent completed — rate the result" in the corner for a+ // run the user had just moved to another provider, and the run it handed the+ // task to raises this toast itself when it actually finishes.+ if (!agentId || isSystem || isAgentHandoff(data) || shownFeedbackFor.current.has(agentId)) {return;}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 346a61fb2d..b61f9ebbd3 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -140,6 +140,7 @@ grep -i "what you want to do" client/src/lib/README.md| `falVideoHandoff.js` | `buildFalH3MaxPrompt(prompt, negativePrompt)` composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; `FAL_H3_MAX_FREE_URL` and `FAL_H3_MAX_FREE_ALLOWANCE_NOTE` carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API. || `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. || `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |+| `agentOutcome.js` | Mirror of `server/lib/agentOutcome.js`: `isAgentHandoff(agent)` (`result.resumed === true`) tells a record retired to hand its task to a continuation — a Resume or a provider Relaunch — from one that reached a verdict, with `isAgentOutcome` / `isAgentFailure` derived from it. Agent cards that read `result.success` alone rendered a red "Failed" run for a swap the user made deliberately, and the needs-feedback filter asked them to rate it. Mirrored rather than imported so the client bundle never pulls the server closure in for one predicate. || `cosTaskType.js` | CoS task-learning bucket resolver for ETA surfaces: `extractCosTaskType(task)` mirrors the server's metadata-first `extractTaskType` handling for live tasks and archived-agent projections, so `self-improve:*`, `user-task`, and fallback estimates use the same history bucket that recorded the run. || `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). || `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. |diff --git a/client/src/lib/agentOutcome.js b/client/src/lib/agentOutcome.jsnew file mode 100644index 0000000000..8092549ae0--- /dev/null+++ b/client/src/lib/agentOutcome.js@@ -0,0 +1,33 @@+/**+ * Is a completed agent record an OUTCOME, or a handoff to its own continuation?+ *+ * Client mirror of `server/lib/agentOutcome.js` — same contract, same key. Read+ * that file for why the rule exists; the short version is that Relaunch (and+ * Resume) retire the old record with `success: false` and requeue the SAME task,+ * usually because the user swapped providers after a CLI hit a usage limit. Cards+ * that render `result.success` alone therefore showed a red "Failed" run for a+ * swap the user made deliberately, and the feedback prompt asked them to rate it.+ *+ * Mirrored rather than imported: `client/src/lib` must not reach into the server+ * tree (a client-side import of a server module pulls its whole closure into the+ * browser bundle and into every suite that renders one of these cards). Keep the+ * two in step — `agentOutcome.test.js` on each side pins the shared contract.+ */++/**+ * True when this record was retired to hand its task to a continuation run+ * (Resume / Relaunch) rather than because the run reached a verdict.+ */+export function isAgentHandoff(agent) {+ return agent?.result?.resumed === true;+}++/** True when the run reached a real verdict — the only records worth counting. */+export function isAgentOutcome(agent) {+ return !!agent?.result && !isAgentHandoff(agent);+}++/** True when the run genuinely failed: a verdict was reached and it was negative. */+export function isAgentFailure(agent) {+ return isAgentOutcome(agent) && agent.result.success !== true;+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex faa21de5d1..0f5783e4e2 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -102,6 +102,7 @@ export * from './buildStamp.js';export * from './chipContrast.js';export * from './clientErrorReporter.js';export * from './clinicianReport.js';+export * from './agentOutcome.js';export * from './clipboard.js';export * from './effortCostEstimate.js';export * from './compareHelpers.js';diff --git a/server/lib/README.md b/server/lib/README.mdindex 1eba26b983..9a9808408c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -51,6 +51,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `spriteChromaKey.js` | Chroma-key selection color math (`CHROMA_KEYS`, `CHROMA_KEY_HEXES`, `DEFAULT_CHROMA_KEY`, hue-distance picking). Pure color math, no image I/O — that lives in `services/sprites/normalize.js`. || `spriteAnimationTracks.js` | The animation-track registry (`ANIMATION_TRACKS`, `WALK_TRACK`, `TRACK_BOUND_TRIPLES`, `AUTHORED_TRACK_FIELDS`) — a zero-import table of per-track frame/fps bounds. || `spriteAnimationTrackStore.js` | The EFFECTIVE track table — compiled built-ins plus the user-defined store read from one small JSON config, so sprite schemas stay module-load constants rather than lazily-built. |+| `agentOutcome.js` | Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? `isAgentHandoff` (`result.resumed === true` — what `resumeAgent`/`relaunchAgent` stamps when it retires a record and requeues the SAME task, typically because the user swapped providers after a usage limit), plus `isAgentOutcome` / `isAgentFailure` derived from it. Every consumer that read `result.success` as the verdict booked a phantom failure per swap — a red history card, a failed task in the daily report and weekly digest, a dented success rate, a quota-burn denial recorded against "Relaunched by user", a feature agent flipped to `error` — so the rule task-learning already applied lives here once. Keyed on a field `resumeAgent` has always written, so archived relaunches reclassify retroactively with no migration. Mirrored at `client/src/lib/agentOutcome.js`. || `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. || `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |diff --git a/server/lib/agentOutcome.js b/server/lib/agentOutcome.jsnew file mode 100644index 0000000000..ccb89352b0--- /dev/null+++ b/server/lib/agentOutcome.js@@ -0,0 +1,44 @@+/**+ * Is a completed agent record an OUTCOME, or a handoff to its own continuation?+ *+ * `resumeAgent` (and `relaunchAgent`, which composes a pause with a resume)+ * retires the old record with `success: false` and requeues the SAME task — most+ * often because the user swapped providers after a CLI hit a usage limit, not+ * because the work failed. Every consumer that reads `result.success` as the+ * verdict therefore booked a phantom failure per swap: a red "Failed" card in the+ * history, a failed task in the daily report and the weekly digest, a dented+ * success rate, a quota-burn denial recorded against "Relaunched by user", a+ * feature agent flipped to `error`.+ *+ * The rule task-learning already applies (`initTaskLearning`, #4540: "a record+ * retired by resumeAgent is a CONTINUATION, not an outcome") belongs to all of+ * them, so it lives here once instead of being restated — or forgotten — per+ * consumer.+ *+ * Keyed on `result.resumed`, which `resumeAgent` has always stamped, so ALREADY+ * ARCHIVED relaunches are reclassified retroactively: no migration, and an+ * install's existing history stops reporting swaps as failures the moment it+ * upgrades. Mirrored, with the same contract, at `client/src/lib/agentOutcome.js`.+ *+ * Pure and dependency-free — read from report builders, event listeners, and the+ * learning writer alike, none of which should drag in the agent-state graph for+ * one predicate.+ */++/**+ * True when this record was retired to hand its task to a continuation run+ * (resume / relaunch) rather than because the run reached a verdict.+ */+export function isAgentHandoff(agent) {+ return agent?.result?.resumed === true;+}++/** True when the run reached a real verdict — the only records worth counting. */+export function isAgentOutcome(agent) {+ return !!agent?.result && !isAgentHandoff(agent);+}++/** True when the run genuinely failed: a verdict was reached and it was negative. */+export function isAgentFailure(agent) {+ return isAgentOutcome(agent) && agent.result.success !== true;+}diff --git a/server/lib/agentOutcome.test.js b/server/lib/agentOutcome.test.jsnew file mode 100644index 0000000000..63c745a787--- /dev/null+++ b/server/lib/agentOutcome.test.js@@ -0,0 +1,56 @@+import { describe, it, expect } from 'vitest';+import { isAgentHandoff, isAgentOutcome, isAgentFailure } from './agentOutcome.js';++// The record `resumeAgent` retires when Relaunch swaps providers mid-run: it+// carries `success: false` and a summary in `error`, because the pause/requeue+// path reuses the completion shape. Every consumer that read `success` alone+// booked that as a failure.+const handoff = {+ status: 'completed',+ result: { success: false, resumed: true, resumedTaskId: 'task-1', error: 'Relaunched by user on codex / gpt-5' },+};+const failure = { status: 'completed', result: { success: false, error: 'exit code 1' } };+const win = { status: 'completed', result: { success: true } };++describe('agentOutcome', () => {+ it('reads a relaunch retirement as a handoff, not a failure', () => {+ expect(isAgentHandoff(handoff)).toBe(true);+ expect(isAgentOutcome(handoff)).toBe(false);+ expect(isAgentFailure(handoff)).toBe(false);+ });++ // The bypass probe. A predicate that classified EVERYTHING as "not a failure"+ // would pass the assertion above while silently emptying the failure bucket of+ // every report, digest, and success rate that now filters on it.+ it('still reads a genuine failure as a failure', () => {+ expect(isAgentHandoff(failure)).toBe(false);+ expect(isAgentOutcome(failure)).toBe(true);+ expect(isAgentFailure(failure)).toBe(true);+ });++ it('reads a successful run as an outcome that did not fail', () => {+ expect(isAgentHandoff(win)).toBe(false);+ expect(isAgentOutcome(win)).toBe(true);+ expect(isAgentFailure(win)).toBe(false);+ });++ // `resumed` is the field `resumeAgent` has always stamped, which is what makes+ // already-archived relaunches reclassify without a migration — but only under a+ // STRICT read. A truthy check would also catch a future `resumed: 'partial'`+ // or a COS-TASKS.md round-trip's string, and quietly drop a real outcome from+ // every count.+ it('demands the boolean, so a nearby truthy value is not mistaken for a handoff', () => {+ expect(isAgentHandoff({ result: { success: false, resumed: 'true' } })).toBe(false);+ expect(isAgentHandoff({ result: { success: false, resumed: 1 } })).toBe(false);+ });++ // A running agent has no `result` yet. It is not an outcome (nothing to count)+ // and must not be reported as a failure by a caller that only asks "did it fail".+ it('treats a record with no result as neither an outcome nor a failure', () => {+ for (const record of [{ status: 'running' }, {}, null, undefined]) {+ expect(isAgentOutcome(record)).toBe(false);+ expect(isAgentFailure(record)).toBe(false);+ expect(isAgentHandoff(record)).toBe(false);+ }+ });+});diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 43fe744057..cdfe72c0bc 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -154,6 +154,14 @@ export function buildAgentRegistration({// recipe, so without this the card is indistinguishable from an agent// whose PTY failed to attach.publicReviewPosture,+ // The run this one TOOK OVER, stamped on the task by `resolveTaskResumePatch`+ // when a Resume or a provider Relaunch requeues a paused task in place. Same+ // hand-picked-projection reason as the keys around it: the predecessor is+ // retired as a HANDOFF rather than a failure (`lib/agentOutcome.js`), and+ // without this the card that took over its worktree has no way to say what it+ // is continuing — leaving the pair looking like two unrelated runs, one of+ // which mysteriously stopped.+ resumedFromAgentId: task.metadata?.resumedFromAgentId || null,// Preserve privacy after the task becomes an archived agent.machineLocal: isTruthyMetaFn(task.metadata?.machineLocal),taskAnalysisType: task.metadata?.analysisType || null,diff --git a/server/lib/agentRegistrationRecord.test.js b/server/lib/agentRegistrationRecord.test.jsnew file mode 100644index 0000000000..258c44fc5d--- /dev/null+++ b/server/lib/agentRegistrationRecord.test.js@@ -0,0 +1,48 @@+import { describe, it, expect } from 'vitest';+import { buildAgentRegistration } from './agentRegistrationRecord.js';++// `agent.metadata` is a hand-picked projection of `task.metadata`, never a spread,+// so a field nobody lists simply does not survive the spawn — the failure mode the+// module header records (`quotaBurnStepId`, #6406). These pin the one field whose+// absence is invisible at spawn time and only shows up as a missing link in the UI.+const args = (taskMetadata) => ({+ task: { id: 'task-1', description: 'do the thing', taskType: 'user', priority: 'normal', metadata: taskMetadata },+ provider: { id: 'claude', command: 'claude' },+ instanceId: 'instance-1',+ workspacePath: '/tmp/ws',+ sourceWorkspace: null,+ primaryCheckoutBaseline: null,+ worktreeInfo: null,+ explicitWorktree: false,+ jiraBranchName: null,+ providerEndpoint: null,+ localPromptBudget: null,+ leanMode: false,+ prOpenedBy: 'portos',+ claimFlowTask: false,+ selectedModel: 'opus',+ modelSelection: { tier: 'heavy', reason: 'pinned' },+ runId: 'run-1',+ dispatchUseRunner: false,+ executionMode: 'direct',+ publicReviewPosture: null,+ resolvedAppName: null,+ isTruthyMetaFn: (v) => v === true || v === 'true',+});++describe('buildAgentRegistration — resume provenance', () => {+ it('projects the predecessor this run took over from', () => {+ // Stamped on the task by `resolveTaskResumePatch` when Resume/Relaunch+ // requeues a paused task in place. The predecessor is retired as a HANDOFF+ // rather than a failure (lib/agentOutcome.js); without this projection the+ // card that inherited its worktree cannot say what it is continuing.+ const record = buildAgentRegistration(args({ resumedFromAgentId: 'agent-predecessor' }));+ expect(record.resumedFromAgentId).toBe('agent-predecessor');+ });++ it('projects an explicit null for an ordinary first run', () => {+ // Not `undefined`: the key has to exist so a reader can tell "no predecessor"+ // from "record written before this field shipped".+ expect(buildAgentRegistration(args({})).resumedFromAgentId).toBeNull();+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 7ed00a9f5b..5abac56258 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -304,6 +304,7 @@ export * from './zipWriter.js';// === Process execution ===export * from './agentGuard/index.js';+export * from './agentOutcome.js';export * from './agentOutputMarkers.js';export * from './agentRunEvents.js';export * from './agentRunReconcile.js';diff --git a/server/services/cosAgentFeedback.js b/server/services/cosAgentFeedback.jsindex 3b4fe110ee..a370f1a716 100644--- a/server/services/cosAgentFeedback.js+++ b/server/services/cosAgentFeedback.js@@ -16,6 +16,7 @@ import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { loadAgentIndex, getAgentDir } from './cosAgentIndex.js';import { ServerError } from '../lib/errorHandler.js';import { recordUserAction } from './userActions.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';const isSystemAgent = (agent) =>agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');@@ -71,6 +72,11 @@ export async function getPendingAgentFeedbackCount() {agent.status === 'completed' &&!isSystemAgent(agent) &&isManualUserAgent(agent) &&+ // A record Resume/Relaunch retired has no result to rate — the continuation+ // it handed the task to is the run that gets rated. Counting it banners a+ // review item the Agents queue then refuses to show rating buttons for, so+ // the banner never clears.+ !isAgentHandoff(agent) &&!agent.feedback?.rating).length;}diff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.jsindex fd3981085f..24fe851f76 100644--- a/server/services/cosAgentFeedback.test.js+++ b/server/services/cosAgentFeedback.test.js@@ -82,6 +82,22 @@ describe('getPendingAgentFeedbackCount', () => {await expect(getPendingAgentFeedbackCount()).resolves.toBe(1);});+ it('excludes a run retired by Relaunch, which has no result to rate', async () => {+ // A permanent banner otherwise: the count included the record Relaunch+ // retires, but AgentCard shows no rating buttons for it, so nothing the user+ // could do would ever clear "1 completed run needs feedback".+ mockCosState.state.agents = {+ 'agent-relaunched': {+ id: 'agent-relaunched', status: 'completed', completedAt: '2026-08-01T10:00:00.000Z',+ metadata: { taskType: 'user' },+ result: { success: false, resumed: true, error: 'Relaunched by user on codex' }+ },+ 'agent-manual': { id: 'agent-manual', status: 'completed', metadata: { taskType: 'user' }, result: { success: true } }+ };++ await expect(getPendingAgentFeedbackCount()).resolves.toBe(1);+ });+it('returns 0 when nothing is awaiting a rating', async () => {await expect(getPendingAgentFeedbackCount()).resolves.toBe(0);});diff --git a/server/services/cosReports.js b/server/services/cosReports.jsindex c3f367f857..73bf98f021 100644--- a/server/services/cosReports.js+++ b/server/services/cosReports.js@@ -11,6 +11,7 @@ import { join } from 'path';import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './cosState.js';import { getAgentIdsForDates, getAgentsByDate } from './cosAgentIndex.js';import { formatDuration, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';// Completed-agent records for a set of UTC date buckets (YYYY-MM-DD), merged// from live in-memory state and the on-disk date-bucket archive. `accept(agent)`@@ -24,9 +25,16 @@ import { formatDuration, safeJSONParse, atomicWrite } from '../lib/fileUtils.js'// swept out of state.json by `archiveStaleAgents` resolves from disk instead of// reading as empty (issue #3501: reports for past dates came back all-zero, and// every dashboard refresh linearly rescanned the whole agent history).+//+// HANDOFF records are dropped from both sources. Every caller here is building+// outcome statistics — succeeded vs failed, accomplishments vs incidents — and a+// record `resumeAgent` retired to requeue its own task has no outcome yet: the+// continuation it handed the task to records that. Counting it booked one failed+// task per provider swap in the daily report and the "While You Were Away"+// briefing, which is the failure a user sees for pressing Relaunch.async function collectCompletedAgents(dates, state, accept) {const liveIds = new Set(Object.keys(state.agents));- const collected = Object.values(state.agents).filter(a => a.completedAt && accept(a));+ const collected = Object.values(state.agents).filter(a => a.completedAt && !isAgentHandoff(a) && accept(a));const idsByDate = await getAgentIdsForDates(dates);// Iterating the Map (not `dates`) keeps a repeated date from reading its bucket twice.@@ -35,7 +43,7 @@ async function collectCompletedAgents(dates, state, accept) {if (missing.size === 0) continue;for (const agent of await getAgentsByDate(date)) {if (!missing.has(agent.id)) continue; // live copy wins, and non-indexed strays stay out- if (!agent.completedAt || !accept(agent)) continue;+ if (!agent.completedAt || isAgentHandoff(agent) || !accept(agent)) continue;collected.push(agent);}}diff --git a/server/services/cosReports.test.js b/server/services/cosReports.test.jsindex bbfa6df9c5..20443287f5 100644--- a/server/services/cosReports.test.js+++ b/server/services/cosReports.test.js@@ -90,6 +90,19 @@ describe('getWhileAwayActivity', () => {expect(result.incidents.map(a => a.id)).toEqual(['bad1']);});+ it('keeps a relaunched run out of the incidents list', async () => {+ // The "While You Were Away" briefing is where a phantom failure is loudest:+ // it presents the failed bucket as incidents the user should look at.+ const relaunched = agentAt('swapped', { msAgo: 30 * 60000, success: false });+ relaunched.result = { ...relaunched.result, resumed: true, error: 'Relaunched by user on codex' };+ mock.state = stateWith([agentAt('ok', { msAgo: 10 * 60000, success: true }), relaunched]);++ const result = await getWhileAwayActivity(new Date(Date.now() - 3600000).toISOString());++ expect(result.stats).toMatchObject({ completed: 1, succeeded: 1, failed: 0, successRate: 100 });+ expect(result.incidents).toHaveLength(0);+ });+it('merges archived agents from date buckets the window spans', async () => {const liveAgent = agentAt('live', { msAgo: 30 * 60000 });mock.state = stateWith([liveAgent]);@@ -195,6 +208,14 @@ const agentOnDate = (id, dateStr, { success = true, desc = 'did a thing' } = {})metadata: { taskDescription: desc, taskType: 'review' }});+// What Relaunch leaves behind: `resumeAgent` retires the running record with+// `success: false` and requeues the SAME task on the new provider. It never+// reached a verdict, so no report may count it as a failed task.+const handoffOnDate = (id, dateStr) => ({+ ...agentOnDate(id, dateStr, { success: false, desc: 'swapped providers mid-run' }),+ result: { success: false, duration: 3600000, resumed: true, resumedTaskId: `task-${id}`, error: 'Relaunched by user on codex' }+});+const todayStr = () => new Date().toISOString().slice(0, 10);describe('generateReport (#3501 date-bucket sourcing)', () => {@@ -235,6 +256,34 @@ describe('generateReport (#3501 date-bucket sourcing)', () => {expect(getAgentsByDate).not.toHaveBeenCalled();});+ it('does not count a relaunched run as a failed task', async () => {+ const date = '2026-01-19';+ mock.state = stateWith([+ agentOnDate('ok', date, { success: true }),+ handoffOnDate('swapped', date),+ ]);++ const report = await generateReport(date);++ // Not 1 failed + 3 total: the relaunch is neither, and it stays out of the+ // per-agent list so nothing downstream re-derives a verdict from it.+ expect(report.summary).toMatchObject({ tasksCompleted: 1, tasksFailed: 0, totalAgents: 1 });+ expect(report.agents.map(a => a.id)).toEqual(['ok']);+ });++ it('excludes an ARCHIVED relaunch too, not just a live one', async () => {+ // The archive is the half that outlives state.json, so a per-source filter+ // that only covered live records would put every past swap back in the+ // failure column as soon as retention swept it.+ const date = '2026-01-20';+ mock.agentsByDate[date] = [handoffOnDate('archived-swap', date), agentOnDate('archived-ok', date, { success: true })];++ const report = await generateReport(date);++ expect(report.summary).toMatchObject({ tasksCompleted: 1, tasksFailed: 0, totalAgents: 1 });+ expect(report.agents.map(a => a.id)).toEqual(['archived-ok']);+ });+it('ignores agents completed on other dates', async () => {mock.state = stateWith([agentOnDate('other', '2026-01-17')]);mock.agentsByDate['2026-01-18'] = [agentOnDate('wanted', '2026-01-18')];diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex f4809646cc..833b6130bb 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -14,6 +14,7 @@ import { cosEvents } from './cosEvents.js';import { ensureDir, PATHS, readJSONFile, atomicWrite, rmGuarded } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { isPlainObject } from '../lib/objects.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';import { getAppById } from './apps.js';const DATA_DIR = PATHS.cos;const FA_FILE = join(DATA_DIR, 'feature-agents.json');@@ -598,6 +599,26 @@ cosEvents.on('agent:spawned', async (agentData) => {cosEvents.on('agent:completed', async (agentData) => {const featureAgentId = agentData?.metadata?.featureAgentId;if (!agentData?.metadata?.featureAgentRun || !featureAgentId) return;+ // A relaunch retires this record and requeues the SAME task on a new provider,+ // so the run is still in flight. Recording it would flip the feature agent to+ // `error`, bump its run count, and write a run-history entry reading+ // "Relaunched by user" — for work that has not finished.+ //+ // Instead, follow the task. `currentAgentId` holds the retired agent's id,+ // and the `agent:spawned` listener above re-binds it only for a feature agent+ // still pointing at the TASK — so without this hand-back the pointer stays on a+ // dead agent and the continuation's output never reaches the feature-agent view.+ if (isAgentHandoff(agentData)) {+ // `resumedTaskId` — not `taskId` — because a resume that could not reuse the+ // paused task queues a REPLACEMENT (which inherits this feature agent's+ // metadata), and pointing at the retired task id would never re-bind.+ const continuationTaskId = agentData.result?.resumedTaskId || agentData.taskId;+ if (!continuationTaskId) return;+ await setCurrentAgent(featureAgentId, continuationTaskId).catch(err => {+ console.log(`⚠️ Failed to hand feature agent ${featureAgentId} back to its relaunched task: ${err.message}`);+ });+ return;+ }const success = agentData.result?.success === true;await recordRunCompletion(featureAgentId, {status: success ? 'working' : 'error',diff --git a/server/services/featureAgents.trigger.test.js b/server/services/featureAgents.trigger.test.jsindex feacb1844c..da753ea060 100644--- a/server/services/featureAgents.trigger.test.js+++ b/server/services/featureAgents.trigger.test.js@@ -84,6 +84,67 @@ describe('triggerFeatureAgent', () => {expect(saved.agents[0].currentAgentId).toBeNull();});+ it('follows a relaunched run to its continuation instead of recording an error', async () => {+ // Relaunch retires the CoS agent with `success: false` and requeues the same+ // task on a new provider. Treating that as a completion flipped the feature+ // agent to `error`, banked a run that had not finished, and — because the+ // `agent:spawned` re-bind only matches a feature agent still pointing at the+ // TASK — stranded currentAgentId on the dead agent, so the continuation's+ // output never reached the feature-agent view.+ const result = await triggerFeatureAgent(agent.id);+ cosEvents.emit('agent:spawned', { taskId: result.taskId, id: 'agent-first' });+ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe('agent-first');+ });++ cosEvents.emit('agent:completed', {+ id: 'agent-first',+ taskId: result.taskId,+ metadata: { featureAgentId: agent.id, featureAgentRun: true },+ result: { success: false, resumed: true, resumedTaskId: result.taskId, error: 'Relaunched by user on codex' }+ });++ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe(result.taskId);+ });+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].runCount ?? 0).toBe(0);+ expect(saved.agents[0].status).toBe('active');++ // And the pointer it handed back is the one the continuation's spawn re-binds.+ cosEvents.emit('agent:spawned', { taskId: result.taskId, id: 'agent-second' });+ await vi.waitFor(async () => {+ const after = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(after.agents[0].currentAgentId).toBe('agent-second');+ });+ });++ it('points at the REPLACEMENT task when a resume could not reuse the paused one', async () => {+ // `resumeAgent`'s new-task mode queues a fresh task (inheriting this feature+ // agent's metadata) and reports it as `resumedTaskId`. Handing back the+ // retired `taskId` would leave a pointer nothing will ever spawn.+ const result = await triggerFeatureAgent(agent.id);+ cosEvents.emit('agent:spawned', { taskId: result.taskId, id: 'agent-first' });+ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe('agent-first');+ });++ cosEvents.emit('agent:completed', {+ id: 'agent-first',+ taskId: result.taskId,+ metadata: { featureAgentId: agent.id, featureAgentRun: true },+ result: { success: false, resumed: true, resumedTaskId: 'task-replacement', error: 'Relaunched by user' }+ });++ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe('task-replacement');+ });+ });+it('clears the active pointer and records the run after CoS completion', async () => {const result = await triggerFeatureAgent(agent.id);diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.jsindex 31d9d31e44..85c8880603 100644--- a/server/services/maintenanceRun.js+++ b/server/services/maintenanceRun.js@@ -50,6 +50,7 @@ import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { buildMaintenanceSteps } from '../lib/maintenanceSequence.js';import { familyForProvider } from '../lib/providerFamilies.js';import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';import { cosEvents } from './cosEvents.js';import { getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';import { ACTIVE_TASK_STATUSES, probeSequenceDrain, sequenceStepShapeReason } from './quotaBurnSequence.js';@@ -317,6 +318,11 @@ async function evaluate(id, { ignoreTaskId }) {function onMaintenanceAgentCompleted(agent) {const id = agent?.metadata?.taskQuotaBurnMaintenanceRunId;if (!id) return null;+ // A relaunch hands this step's task to a continuation rather than ending it.+ // Evaluating here would report the step as a hold the user has to retry or+ // dismiss, for a run that is already on its way back out on a new provider.+ // The continuation's own completion is the one that advances the run.+ if (isAgentHandoff(agent)) return null;const stepId = agent.metadata?.taskQuotaBurnStepId;const success = agent.result?.success === true;return getMaintenanceRun(id)diff --git a/server/services/productivity.js b/server/services/productivity.jsindex 1e30ae6484..c7477108ba 100644--- a/server/services/productivity.js+++ b/server/services/productivity.js@@ -9,6 +9,7 @@ import { cosEvents } from './cosEvents.js';import { getAgents } from './cosAgentLifecycle.js';import { ensureDir, getDateString, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { getWeekId } from '../lib/isoWeek.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';const DATA_DIR = PATHS.cos;const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');@@ -74,7 +75,11 @@ export async function recalculateProductivity() {console.log('📊 Productivity: Recalculating from agent history');const agents = await getAgents();- const completedAgents = agents.filter(a => a.completedAt && a.status === 'completed');+ // A relaunch retires its record with `success: false` and requeues the same+ // task, so counting it would score one failure per provider swap against the+ // hour and weekday the user happened to press the button — and then score the+ // continuation on top. The continuation is the run that did the work.+ const completedAgents = agents.filter(a => a.completedAt && a.status === 'completed' && !isAgentHandoff(a));// Sort by completion datecompletedAgents.sort((a, b) => new Date(a.completedAt) - new Date(b.completedAt));@@ -242,6 +247,9 @@ export async function getProductivityInsights() {*/export async function onTaskCompleted(agent) {if (!agent?.completedAt) return;+ // Same exclusion as the full recalculation — kept in step so an incremental+ // update can never bank a run the rebuild would drop.+ if (isAgentHandoff(agent)) return;const data = await loadProductivity();const completedAt = new Date(agent.completedAt);diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex 1553833d9b..f87538e274 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -50,6 +50,7 @@ import { getQuotaBurnDispatches, evaluateFamilies, PLAN_COMPLETE_SKIP_REASON, reimport { reconcileQuotaBurnReservations, reserveQuotaBurnDispatch } from './quotaBurnAcceptance.js';import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';import { getQuotaBurnConfig, getQuotaBurnReservations, getQuotaBurnRuns, quotaBurnReservationKey, recordQuotaBurnRun } from './quotaBurnStore.js';import { countQuotaBurnStepPending, getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';import { familyHasRunnableJobs, familyIsConfigured, jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';@@ -679,6 +680,15 @@ async function lastScheduledRunAt() {function onBurnAgentCompleted(agent) {const familyId = agent?.metadata?.taskQuotaBurnFamily;if (!familyId) return null;+ // A relaunch is not a completion, and both halves below would misread it as+ // one. The denial ledger would file "Relaunched by user on <provider>" as an+ // observed provider refusal and block the family on it — the exact opposite of+ // what the user asked for, since swapping providers is usually how they get+ // AROUND a limit. And the plan walk would dispatch the next job while the+ // relaunched task is being re-spawned, breaking the one-agent-at-a-time pacing+ // this chain depends on to stay closed. The continuation run emits its own+ // `agent:completed`; that is the one that settles the family.+ if (isAgentHandoff(agent)) return null;// Returned so tests can await the cycle. The emitter ignores it — this is a// fire-and-forget listener, and the `.catch` is what keeps a rejection from// reaching the emitter as an unhandled one.diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.jsindex bc69f7c4aa..c1e6f00911 100644--- a/server/services/quotaBurnRunner.test.js+++ b/server/services/quotaBurnRunner.test.js@@ -638,6 +638,31 @@ describe('completion continuation', () => {expect(state.invoked.map((entry) => entry.familyId)).toEqual(['claude', 'agy']);});+ it('neither files a denial nor walks the plan when a burn agent is RELAUNCHED', async () => {+ // Relaunch retires the record with `success: false` and requeues the same+ // task on another provider — usually because the user is routing AROUND a+ // usage limit, not hitting one. Read as a completion, both halves misfire:+ // the ledger files "Relaunched by user on <provider>" as an observed refusal+ // and blocks the family on it, and the plan dispatches the next job while the+ // relaunched task is still being re-spawned, putting two burn agents in+ // flight against a chain whose whole safety argument is that it is serial.+ state.invokePending = { first: { count: 1 } };+ const relaunched = {+ taskId: 'burn-1',+ metadata: { taskQuotaBurnFamily: 'grok', taskQuotaBurnStepId: 'first' },+ result: { success: false, resumed: true, resumedTaskId: 'burn-1', error: 'Relaunched by user on codex' },+ };++ // Synchronous null, like the other "not mine" early returns: nothing is+ // even scheduled, so there is no promise to await.+ expect(__onBurnAgentCompleted(relaunched)).toBeNull();++ expect(state.settled).toEqual([]);+ expect(state.invoked).toEqual([]);+ expect(state.completed).toEqual([]);+ expect(state.runs).toEqual([]);+ });+it('ignores an agent that was not a quota burn', async () => {state.invokePending = { first: { count: 1 } };await __onBurnAgentCompleted({ metadata: { taskType: 'user' } });diff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.jsindex a05baefbc3..62d4e28d63 100644--- a/server/services/taskLearning/lifecycle.js+++ b/server/services/taskLearning/lifecycle.js@@ -10,6 +10,7 @@import { cosEvents, emitLog } from './store.js';import { recordTaskCompletion, recalculateModelTierMetrics } from './metrics.js';import { declaresNoCommitCriterion } from '../taskTypeHooks.js';+import { isAgentHandoff } from '../../lib/agentOutcome.js';// A pre-#2696 gh/git coordinator run (branch-reconcile/issue-reconcile/branch-cleanup/// jira-status-report) carries a FOSSIL `result.validationPassed` — a boolean the old@@ -40,7 +41,7 @@ export function initTaskLearning() {// resumed run will record the real verdict. Learning from it would charge the// task type and model tier a phantom failure per pause, and double-count the// task once the continuation finishes.- if (agent?.result?.resumed) return;+ if (isAgentHandoff(agent)) return;// Get task info from agentconst task = {id: agent.taskId,@@ -80,7 +81,11 @@ export async function backfillFromHistory() {let backfilled = 0;for (const agent of agents) {- if (agent.status === 'completed' && agent.result) {+ // Same rule as the live listener above, and the reason it is repeated rather+ // than assumed: the backfill re-reads the ARCHIVE, where every relaunch the+ // live guard skipped is still sitting as a `success: false` record. Without+ // this, one backfill re-imports every phantom failure the listener refused.+ if (agent.status === 'completed' && agent.result && !isAgentHandoff(agent)) {const task = {id: agent.taskId,description: agent.metadata?.taskDescription,diff --git a/server/services/taskLearning/lifecycle.test.js b/server/services/taskLearning/lifecycle.test.jsindex 9df3d7df9b..2992cda4fe 100644--- a/server/services/taskLearning/lifecycle.test.js+++ b/server/services/taskLearning/lifecycle.test.js@@ -96,6 +96,22 @@ describe('backfillFromHistory — stale coordinator verdict (#2696)', () => {expect(recordTaskCompletion.mock.calls[0][0].result.validationPassed).toBe(false);});+ it('skips a record retired by a resume — the live listener already refused it', async () => {+ // The listener below skips these as they happen, but the backfill re-reads the+ // ARCHIVE, where every relaunch it skipped is still sitting as a+ // `success: false` record. One backfill would re-import the whole set of+ // phantom failures the listener spent the install's lifetime refusing.+ agentsStore.list = [+ { status: 'completed', taskId: 't-relaunched',+ result: { success: false, duration: 100, resumed: true, resumedTaskId: 't-relaunched', error: 'Relaunched by user on codex' },+ metadata: { taskType: 'user', taskDescription: 'swapped providers mid-run' } },+ completed('t-real', 'accessibility', true),+ ];+ await backfillFromHistory();+ expect(recordTaskCompletion).toHaveBeenCalledTimes(1);+ expect(recordTaskCompletion.mock.calls[0][0].taskId).toBe('t-real');+ });+it('passes a committing type through UNTOUCHED — its commit verdict is real', async () => {// accessibility genuinely commits; a persisted false is a real miss, not a fossil.agentsStore.list = [completed('t1', 'accessibility', false)];diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.jsindex 7730c424ca..3c9280044e 100644--- a/server/services/weeklyDigest.js+++ b/server/services/weeklyDigest.js@@ -14,6 +14,7 @@ import { getAgents } from './cosAgentLifecycle.js';import { getAgentDates, getAgentsByDate } from './cosAgentIndex.js';import { atomicWrite, ensureDir, readJSONFile, formatDuration, PATHS } from '../lib/fileUtils.js';import { getWeekId, weekStartFromWeekId } from '../lib/isoWeek.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';const DIGESTS_DIR = PATHS.digests;@@ -95,8 +96,13 @@ export async function generateWeeklyDigest(weekId = null) {const dedupedStateAgents = stateAgents.filter(a => !dateAgentIds.has(a.id));const allAgents = [...flatDateAgents, ...dedupedStateAgents];+ // Handoffs are excluded once, here, so every stat derived below — totals,+ // success rate, per-type breakdown, accomplishments, and the recurring-issue+ // patterns keyed on `result.error` — sees the same set. Without it the digest's+ // top "recurring issue" of a week with a few provider swaps is literally+ // "Relaunched by user on <provider>".const weekAgents = allAgents.filter(a => {- if (!a.completedAt) return false;+ if (!a.completedAt || isAgentHandoff(a)) return false;const completedWeek = getWeekId(new Date(a.completedAt));return completedWeek === targetWeekId;});@@ -424,7 +430,7 @@ export async function getCurrentWeekProgress() {// Filter agents completed this weekconst weekAgents = agents.filter(a => {- if (!a.completedAt) return false;+ if (!a.completedAt || isAgentHandoff(a)) return false;const completedWeek = getWeekId(new Date(a.completedAt));return completedWeek === weekId;});