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
collapse the handoff rule to one predicate, one result line, one week filter
[._.]/ Adam Eivy51452d21e7c9
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsxnew file mode 100644index 0000000000..1b702e10cd--- /dev/null+++ b/client/src/components/cos/AgentResultLine.jsx@@ -0,0 +1,34 @@+import { CheckCircle, AlertCircle, RotateCcw } from 'lucide-react';+import { isAgentHandoff, agentHandoffReason } from '../../lib/agentOutcome';++/**+ * The one-line verdict on a finished agent run — 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. Rendering that red said the+ * run failed, for something the user did on purpose.+ *+ * Shared by the run card and the Resume dialog. They had the same two-way ternary+ * copy-pasted, so going from two states to three meant editing both — and the+ * copies had already drifted on the fallback text. One component instead, so the+ * next state costs one edit and the two surfaces cannot disagree about what the+ * same record says.+ */+export default function AgentResultLine({ agent, className = '' }) {+ if (!agent?.result) return null;+ const handoff = isAgentHandoff(agent);+ const tone = handoff ? 'text-port-accent' : agent.result.success ? 'text-port-success' : 'text-port-error';++ return (+ <div className={`text-sm flex items-center gap-2 ${tone} ${className}`.trim()}>+ {handoff ? (+ <><RotateCcw size={14} aria-hidden="true" /> {agentHandoffReason(agent)}</>+ ) : agent.result.success ? (+ <><CheckCircle size={14} aria-hidden="true" /> Completed successfully</>+ ) : (+ <><AlertCircle size={14} aria-hidden="true" /> {agent.result.error || 'Failed'}</>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 8a145ff492..8b20816a01 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -4,7 +4,6 @@ import {Cpu,Trash2,CheckCircle,- AlertCircle,AlertTriangle,RotateCcw,Loader2,@@ -33,6 +32,7 @@ import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';import { extractCosTaskType } from '../../../lib/cosTaskType';import { isAgentHandoff } from '../../../lib/agentOutcome';+import AgentResultLine from '../AgentResultLine';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';import { formatBytes, formatDurationMs, formatDateTime, formatTimeOfDay } from '../../../utils/formatters';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';@@ -256,10 +256,6 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,// 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@@ -925,22 +921,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,{agent.result && (<div className="flex items-center gap-4 flex-wrap">- {/* 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'}</>- )}- </div>+ <AgentResultLine agent={agent} />{/* Cleanup warnings */}{agent.result.warnings?.length > 0 && (<div className="text-sm text-port-warning flex items-start gap-2">diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsxindex 8b4dca532b..f3a8c0ddf1 100644--- a/client/src/components/cos/tabs/ResumeAgentModal.jsx+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx@@ -1,5 +1,5 @@import { useState, useRef } from 'react';-import { X, CheckCircle, AlertCircle, RotateCcw, Image, Loader2 } from 'lucide-react';+import { X, RotateCcw, Image, Loader2 } from 'lucide-react';import { processScreenshotUploads } from '../../../services/apiMedia';import toast from '../../ui/Toast';import Modal from '../../ui/Modal';@@ -7,7 +7,8 @@ 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';+import { isAgentHandoff, agentHandoffReason } from '../../../lib/agentOutcome';+import AgentResultLine from '../AgentResultLine';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@@ -21,13 +22,9 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,// 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- ? (handoff- ? `Previous run: Handed off - ${handoffReason}`+ ? (isAgentHandoff(agent)+ ? `Previous run: Handed off - ${agentHandoffReason(agent)}`: agent.result.success ? 'Previous run: Completed successfully' : `Previous run: Failed - ${agent.result.error || 'Unknown error'}`): '';const pauseInfo = isPaused@@ -157,19 +154,7 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,This requeues the same task on the worktree the paused run left behind — no second agent, and nothing to clean up afterward.</div>)}- {agent.result && (- <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'}</>- )}- </div>- )}+ <AgentResultLine agent={agent} className="mt-2" /></div><form onSubmit={handleSubmit} className="space-y-4">diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b61f9ebbd3..da1614c7f8 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -119,6 +119,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. Also the shared predicate every app-global key handler consults: `shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? })` — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open `aria-modal` dialog), used by `useKeyboardShortcuts`, `useKeyCapture` AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: `isEditableTarget(el)`, `isButtonActivation(event)` (true when Space would natively activate the focused button) and `isPressKey(event)` (Enter or Space by either `key` or `code`). Also `isFocusEscapeKey(event)` — the shared "leave this widget" gesture (Shift+Tab backtab) that a key-capturing widget must release to the browser; the Shell terminal's `attachCustomKeyEventHandler` consults it so focus can escape the xterm trap. Plus `noPointerFocusSurfaceProps` — spread on the ROOT of a surface that owns a key globally (a Space-scored drill, the Morse keyer, RapidReader, the OpenWorld HUD); one capture-phase handler stops a mouse click anywhere inside from parking focus on a button and taking that key over via native activation, covering controls added later too. |+| `agentOutcome.js` | Mirror of `server/lib/agentOutcome.js` (pinned by its `agentOutcome.parity.test.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. Cards reading `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. Adds `agentHandoffReason(agent)` (client-only): `metadata.pauseReason` before `result.error`, because on a Relaunch the pause reason names what the USER changed while `result.error` holds the resume summary, which says where the TASK went. Mirrored rather than imported so the browser bundle never pulls the server closure in for one predicate. || `agentResumeOutcome.js` | `agentResumeMessage(result, messages, fallback)` — the toast wording for a CoS agent resume/relaunch result. The server answers with a `mode` (what it did to the task) plus `spawned`/`spawnHold` (whether it also STARTED it — a resumed task is force-spawned when a slot is free, and `spawnHold` names the refusal when it isn't). `messages` is keyed by mode as `{ queued, running? }`; a mode with no `running` variant is one that deliberately queues nothing, so it can never be reported as started. Shared by the Resume dialog (`cos/tabs/AgentsTab.jsx`) and `cos/tabs/RelaunchAgentModal.jsx` so neither can say "queued" for a run that already started, or omit the reason it didn't. || `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app. Re-exported from `server/lib/appIdentity.js`; dependency-free so a module reachable from a server test can import it. || `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |@@ -140,7 +141,6 @@ 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.jsindex 8092549ae0..87770b33b0 100644--- a/client/src/lib/agentOutcome.js+++ b/client/src/lib/agentOutcome.js@@ -1,33 +1,39 @@/*** 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.+ * Client mirror of `server/lib/agentOutcome.js` — same contract, same key, and+ * pinned to it by `server/lib/agentOutcome.parity.test.js`. 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. Surfaces 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.+ * browser bundle and into every suite that renders one of these cards).*//*** True when this record was retired to hand its task to a continuation run* (Resume / Relaunch) rather than because the run reached a verdict.+ *+ * STRICT equality on purpose — see the server copy for why.*/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;+/**+ * The one line a handoff card should show: WHAT THE USER CHANGED.+ *+ * `metadata.pauseReason` first, because on a Relaunch that is the sentence the+ * user is looking for ("Relaunched by user on codex / gpt-5"), while+ * `result.error` holds `resumeAgent`'s summary — which says where the TASK went,+ * not why this run stopped. Client-only: nothing server-side renders it, and+ * keeping it out of the mirrored half is what keeps the parity test a one-line+ * contract.+ */+export function agentHandoffReason(agent) {+ return agent?.metadata?.pauseReason || agent?.result?.error || 'Handed off to a new run';}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 0f5783e4e2..0ce379afda 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -89,6 +89,7 @@ export * from './goalFeatureMap.js';// === Generic UI / collection utilities ===export * from './a11yKeyboard.js';+export * from './agentOutcome.js';export * from './agentResumeOutcome.js';export * from './appIdentity.js';export * from './applyManuscriptEdits.js';@@ -102,7 +103,6 @@ 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 9a9808408c..e8a2ca23cc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -51,7 +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`. |+| `agentOutcome.js` | Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? `isAgentHandoff(agent)` — `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. 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. Reads only `result`, so `completeAgent`'s stats writer can ask it before the record exists. Keyed on a field `resumeAgent` has always written, so archived relaunches reclassify retroactively with no migration. Mirrored at `client/src/lib/agentOutcome.js`, pinned by `agentOutcome.parity.test.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.jsindex ccb89352b0..a9eefc0d94 100644--- a/server/lib/agentOutcome.js+++ b/server/lib/agentOutcome.js@@ -4,13 +4,13 @@* `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+ * because the work failed. Every consumer that read `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+ * The rule task-learning already applied (`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.@@ -18,7 +18,8 @@* 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`.+ * upgrades. Mirrored, with the same contract, at `client/src/lib/agentOutcome.js`+ * and pinned to it by `agentOutcome.parity.test.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@@ -28,17 +29,15 @@/*** True when this record was retired to hand its task to a continuation run* (resume / relaunch) rather than because the run reached a verdict.+ *+ * Takes the whole record, but reads only `result`, so the stats writer inside+ * `completeAgent` — which has the result in hand before any record exists — can+ * ask the same question with `isAgentHandoff({ result })`.+ *+ * STRICT equality on purpose. A truthy check would also swallow a future+ * `resumed: 'partial'` or a round-tripped string, silently dropping a real+ * outcome from every count that now filters on this.*/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.parity.test.js b/server/lib/agentOutcome.parity.test.jsnew file mode 100644index 0000000000..37ecf59646--- /dev/null+++ b/server/lib/agentOutcome.parity.test.js@@ -0,0 +1,71 @@+/**+ * The handoff predicate, and cross-package parity for its client mirror.+ *+ * `server/lib/agentOutcome.js` is the source of truth; `client/src/lib/agentOutcome.js`+ * is a hand-maintained copy, because the client must not import out of the server+ * tree. Both are pure, so ONE table runs against BOTH and a copy that drifts fails+ * here instead of quietly letting the run card disagree with the daily report about+ * whether a provider swap was a failure.+ *+ * It lives server-side, like the repo's other parity suites, because the server+ * runner can load the pure client module but not the reverse.+ */++import { describe, it, expect } from 'vitest';+import { isAgentHandoff as serverIsAgentHandoff } from './agentOutcome.js';+import { isAgentHandoff as clientIsAgentHandoff, agentHandoffReason } from '../../client/src/lib/agentOutcome.js';++const IMPLEMENTATIONS = [['server', serverIsAgentHandoff], ['client', clientIsAgentHandoff]];++// 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 CASES = [+ ['a relaunch retirement', HANDOFF, true],+ // The bypass probe. A predicate that answered `false` for everything would pass+ // the case above while silently emptying the failure bucket of every report,+ // digest, and success rate that now filters on it.+ ['a genuine failure', { status: 'completed', result: { success: false, error: 'exit code 1' } }, false],+ ['a successful run', { status: 'completed', result: { success: true } }, false],+ // `resumed` is the field that makes 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 drop a+ // real outcome from every count.+ ['a string "true" in the resumed slot', { result: { success: false, resumed: 'true' } }, false],+ ['a 1 in the resumed slot', { result: { success: false, resumed: 1 } }, false],+ // A running agent has no result yet, and must not read as a handoff to a caller+ // deciding whether to advance a chain.+ ['a running agent', { status: 'running' }, false],+ ['an empty record', {}, false],+ ['null', null, false],+ ['undefined', undefined, false],+];++describe.each(IMPLEMENTATIONS)('isAgentHandoff (%s)', (_side, isAgentHandoff) => {+ it.each(CASES)('reads %s as %s', (_label, record, expected) => {+ expect(isAgentHandoff(record)).toBe(expected);+ });+});++describe('agentHandoffReason (client-only)', () => {+ it('prefers the pause reason, which names what the USER changed', () => {+ // `result.error` is `resumeAgent`'s summary — "task … requeued on <branch>" —+ // which answers a question nobody asked while looking at the run they just+ // relaunched.+ expect(agentHandoffReason({+ metadata: { pauseReason: 'Relaunched by user on codex / gpt-5' },+ result: { error: 'Resumed agent agent-1 — task task-1 requeued on cos/task-1/agent-1' },+ })).toBe('Relaunched by user on codex / gpt-5');+ });++ it('falls back to the resume summary, then to a generic line', () => {+ expect(agentHandoffReason({ result: { error: 'Resumed agent agent-1' } })).toBe('Resumed agent agent-1');+ expect(agentHandoffReason({ result: { resumed: true } })).toBe('Handed off to a new run');+ });+});diff --git a/server/lib/agentOutcome.test.js b/server/lib/agentOutcome.test.jsdeleted file mode 100644index 63c745a787..0000000000--- a/server/lib/agentOutcome.test.js+++ /dev/null@@ -1,56 +0,0 @@-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/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 5aa675c213..72e766984c 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -21,6 +21,7 @@ import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';import { recordDomainUsage } from './domainUsage.js';import { repairCodexTaskSummary } from './codexSummaryRepair.js';import { loadAgentIndex, saveAgentIndex, getAgentDir } from './cosAgentIndex.js';+import { isAgentHandoff } from '../lib/agentOutcome.js';export async function registerAgent(agentId, taskId, metadata = {}) {return withStateLock(async () => {@@ -186,11 +187,15 @@ export async function completeAgent(agentId, result = {}) {if (result.success) {state.stats.tasksCompleted++;- } else if (!result.resumed) {+ } else if (!isAgentHandoff({ result })) {// `resumed` records are retired by `resumeAgent`, not failed: the user paused// the run and its task is already requeued, so the continuation will land in// one of these two counters itself. Counting it here reports an error the user// caused deliberately and never saw.+ //+ // Asked of the bare `result` because the record does not exist yet — this is+ // the same predicate every downstream reader uses (`lib/agentOutcome.js`),+ // not a second spelling of it.state.stats.errors = (state.stats.errors || 0) + 1;}diff --git a/server/services/cosReports.js b/server/services/cosReports.jsindex 73bf98f021..0710c4cc4c 100644--- a/server/services/cosReports.js+++ b/server/services/cosReports.js@@ -33,8 +33,12 @@ import { isAgentHandoff } from '../lib/agentOutcome.js';// 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) {+ // One predicate, both sources. The live and archived arms are the same+ // question asked of two stores, and writing it twice (once negated) is how+ // they drift — the handoff exclusion below had to be added to each.+ const keep = (agent) => !!agent.completedAt && !isAgentHandoff(agent) && accept(agent);const liveIds = new Set(Object.keys(state.agents));- const collected = Object.values(state.agents).filter(a => a.completedAt && !isAgentHandoff(a) && accept(a));+ const collected = Object.values(state.agents).filter(keep);const idsByDate = await getAgentIdsForDates(dates);// Iterating the Map (not `dates`) keeps a repeated date from reading its bucket twice.@@ -43,7 +47,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 || isAgentHandoff(agent) || !accept(agent)) continue;+ if (!keep(agent)) continue;collected.push(agent);}}@@ -318,7 +322,14 @@ export async function getRecentTasks(limit = 10) {const state = await loadState();const completedAgents = Object.values(state.agents)- .filter(a => a.status === 'completed' && a.completedAt)+ // Same exclusion the date-bucket collector above applies, for the same+ // reason: this returns a succeeded/failed split, and a record `resumeAgent`+ // retired to requeue its own task reached no verdict. It reads live state+ // directly rather than through that collector (no date window to gate on),+ // so the rule has to be stated here too — which is why it is the one place+ // that still showed a provider swap as a failed task after the rest of the+ // file stopped.+ .filter(a => a.status === 'completed' && a.completedAt && !isAgentHandoff(a)).sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt)).slice(0, limit);diff --git a/server/services/cosReports.test.js b/server/services/cosReports.test.jsindex 20443287f5..863cf57dcb 100644--- a/server/services/cosReports.test.js+++ b/server/services/cosReports.test.js@@ -30,7 +30,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => ({import { getAgentsByDate } from './cosAgentIndex.js';import { atomicWrite } from '../lib/fileUtils.js';-import { generateReport, getTodayActivity, getWhileAwayActivity } from './cosReports.js';+import { generateReport, getRecentTasks, getTodayActivity, getWhileAwayActivity } from './cosReports.js';// Build a completed agent record at a fixed completedAt offset (ms before now).const agentAt = (id, { msAgo, success = true, desc = 'did a thing', taskType = 'review', app = null } = {}) => {@@ -332,3 +332,41 @@ describe('getTodayActivity (#3501 date-bucket sourcing)', () => {expect(getAgentsByDate).not.toHaveBeenCalled();});});++describe('getRecentTasks', () => {+ beforeEach(() => {+ mock.daemonRunning = true;+ mock.agentsByDate = {};+ mock.state = stateWith([]);+ });++ afterEach(() => vi.clearAllMocks());++ it('leaves a relaunched run out of the recent-task success split', async () => {+ // This reader has its own door into live state — it has no date window to+ // gate on, so it does not go through `collectCompletedAgents`. That made it+ // the last place still reporting a provider swap as a failed task after the+ // rest of the file stopped, on the /api/cos/insights recent-tasks panel.+ mock.state = stateWith([+ agentAt('ok', { msAgo: 10 * 60000, success: true }),+ { ...agentAt('swapped', { msAgo: 20 * 60000, success: false }),+ result: { success: false, duration: 60000, resumed: true, error: 'Relaunched by user on codex' } },+ ]);++ const result = await getRecentTasks();++ expect(result.tasks.map(t => t.id)).toEqual(['ok']);+ expect(result.summary).toMatchObject({ total: 1, succeeded: 1, failed: 0, successRate: 100 });+ });++ it('still reports a genuine failure', async () => {+ mock.state = stateWith([+ agentAt('ok', { msAgo: 10 * 60000, success: true }),+ agentAt('broke', { msAgo: 20 * 60000, success: false }),+ ]);++ const result = await getRecentTasks();++ expect(result.summary).toMatchObject({ total: 2, succeeded: 1, failed: 1 });+ });+});diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex 833b6130bb..084db1c3f9 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -613,10 +613,11 @@ cosEvents.on('agent:completed', async (agentData) => {// 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}`);- });+ if (continuationTaskId) {+ 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;diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.jsindex 3c9280044e..f2f9060bce 100644--- a/server/services/weeklyDigest.js+++ b/server/services/weeklyDigest.js@@ -18,6 +18,19 @@ import { isAgentHandoff } from '../lib/agentOutcome.js';const DIGESTS_DIR = PATHS.digests;+// The agents one ISO week's stats are built from. Shared by the finished digest+// and the in-progress "current week" view, which must agree on the set or the+// week's numbers change the moment it closes.+//+// HANDOFFS are excluded here, once, so every stat derived downstream — totals,+// success rate, per-type breakdown, accomplishments, and the recurring-issue+// patterns keyed on `result.error` — sees the same set. A record `resumeAgent`+// retired to requeue its own task reached no verdict; without this, the top+// "recurring issue" of a week with a few provider swaps is literally+// "Relaunched by user on <provider>".+const agentsCompletedInWeek = (agents, weekId) => agents.filter(a =>+ a.completedAt && !isAgentHandoff(a) && getWeekId(new Date(a.completedAt)) === weekId);+/*** Get the start of a week (Monday) for a given date*/@@ -96,16 +109,7 @@ 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 || isAgentHandoff(a)) return false;- const completedWeek = getWeekId(new Date(a.completedAt));- return completedWeek === targetWeekId;- });+ const weekAgents = agentsCompletedInWeek(allAgents, targetWeekId);// Calculate basic statsconst totalTasks = weekAgents.length;@@ -428,12 +432,7 @@ export async function getCurrentWeekProgress() {// Get all agentsconst agents = await getAgents();- // Filter agents completed this week- const weekAgents = agents.filter(a => {- if (!a.completedAt || isAgentHandoff(a)) return false;- const completedWeek = getWeekId(new Date(a.completedAt));- return completedWeek === weekId;- });+ const weekAgents = agentsCompletedInWeek(agents, weekId);// Currently running agentsconst runningAgents = agents.filter(a => a.status === 'running');