Skip to content

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

gate quota-burn and maintenance-run continuation handoffs on resumedTaskId, not bare resumed (#7469)

[._.]/ Adam Eivy9a40eaa6aab7
diff --git a/server/lib/README.md b/server/lib/README.md
index fb1d4d5c0c..8ade13c372 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(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. Also carries `agentHandoffReason(agent)` — `metadata.pauseReason` when a continuation was queued, else `result.error`, so an abandoned run is not captioned as a deliberate provider swap. `client/src/lib/agentOutcome.js` re-exports this file rather than copying it. |
+| `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. Also carries `agentHandoffReason(agent)` — `metadata.pauseReason` when a continuation was queued, else `result.error`, so an abandoned run is not captioned as a deliberate provider swap — and `isQueuedContinuation(agent)`, the narrower check for a caller about to SKIP its own completion handling because it expects a continuation run to fire it instead: `isAgentHandoff` alone is not proof a continuation exists (a stranded pause retirement also stamps `resumed: true` with nothing requeued), so use this one there. `client/src/lib/agentOutcome.js` re-exports this file rather than copying it. |
| `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.js
index c6c5769151..f331bffac8 100644
--- a/server/lib/agentOutcome.js
+++ b/server/lib/agentOutcome.js
@@ -42,6 +42,30 @@ export function isAgentHandoff(agent) {
return agent?.result?.resumed === true;
}
+/**
+ * True only when a handoff record proves a continuation was actually QUEUED —
+ * `resumedTaskId` is the field `resumeAgent`/`relaunchAgent` stamp when they
+ * requeue the same task. `isAgentHandoff` alone is not proof: it also reads
+ * true for `retireStrandedPausedAgents` (`server/services/agentManagement.js`),
+ * which stamps `resumed: true` on a pause whose task is gone or moved on,
+ * with nothing requeued.
+ *
+ * Use this — not the bare predicate — anywhere the caller is about to SKIP its
+ * own completion handling because it believes a continuation run will fire the
+ * completion instead. Skipping on the bare predicate strands the chain when
+ * the retirement was actually terminal (#7469: a quota-burn family's
+ * continuation cycle, and a maintenance run's step evaluation, both stalled
+ * this way until the next scheduled tick).
+ *
+ * Consumers that only ask "was this a genuine success/failure" (reports,
+ * productivity stats, task learning) should keep using `isAgentHandoff` — a
+ * stranded retirement isn't a genuine outcome either, so folding it in there
+ * is correct.
+ */
+export function isQueuedContinuation(agent) {
+ return isAgentHandoff(agent) && !!agent?.result?.resumedTaskId;
+}
+
/**
* The one line a handoff card should show: WHAT THE USER CHANGED.
*
diff --git a/server/lib/agentOutcome.test.js b/server/lib/agentOutcome.test.js
index b7e4cc4060..b560873ca1 100644
--- a/server/lib/agentOutcome.test.js
+++ b/server/lib/agentOutcome.test.js
@@ -9,7 +9,7 @@
*/
import { describe, it, expect } from 'vitest';
-import { isAgentHandoff, agentHandoffReason } from './agentOutcome.js';
+import { isAgentHandoff, isQueuedContinuation, agentHandoffReason } 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
@@ -47,6 +47,28 @@ describe('isAgentHandoff', () => {
});
});
+describe('isQueuedContinuation', () => {
+ it('is true for a relaunch retirement that actually queued a continuation', () => {
+ expect(isQueuedContinuation(HANDOFF)).toBe(true);
+ });
+
+ // The regression this predicate exists for (#7469): `retireStrandedPausedAgents`
+ // stamps `resumed: true` on a pause whose task is gone, with NO `resumedTaskId`
+ // — nothing was requeued. A caller that skipped its own completion handling on
+ // the bare `isAgentHandoff` here would wait forever for a continuation that
+ // never fires.
+ it('is false for a stranded pause retirement with no queued continuation', () => {
+ expect(isQueuedContinuation({
+ status: 'completed',
+ result: { success: false, resumed: true, error: 'Pause retired — its task task-9 no longer exists' },
+ })).toBe(false);
+ });
+
+ it('is false for a genuine outcome', () => {
+ expect(isQueuedContinuation({ status: 'completed', result: { success: true } })).toBe(false);
+ });
+});
+
describe('agentHandoffReason', () => {
it('prefers the pause reason when a continuation was actually queued', () => {
// `result.error` there is `resumeAgent`'s summary — "task … requeued on
diff --git a/server/services/featureAgents.js b/server/services/featureAgents.js
index 74859ee095..6587e2edbb 100644
--- a/server/services/featureAgents.js
+++ b/server/services/featureAgents.js
@@ -14,7 +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 { isQueuedContinuation } from '../lib/agentOutcome.js';
import { getAppById } from './apps.js';
const DATA_DIR = PATHS.cos;
const FA_FILE = join(DATA_DIR, 'feature-agents.json');
@@ -622,16 +622,17 @@ cosEvents.on('agent:completed', async (agentData) => {
// without this hand-back the pointer stays on a dead agent and the
// continuation's output never reaches the feature-agent view.
//
- // Gated on `resumedTaskId`, which is what proves a continuation was actually
- // QUEUED. `resumed: true` alone does not: `retireStrandedPausedAgents` stamps
- // it on a pause whose task is gone or has moved on, with no `resumedTaskId` and
- // nothing requeued. Handing back there — to `agentData.taskId`, a task that no
- // longer exists — parks a pointer no `agent:spawned` can ever clear, and both
- // `triggerFeatureAgent` and `getDueFeatureAgents` refuse to run a feature agent
- // that holds one. The agent would never run again, by schedule or by hand,
- // recoverable only by Stop and re-activate. Those retirements fall through to
+ // Gated on `isQueuedContinuation`, which is what proves a continuation was
+ // actually QUEUED. The bare `isAgentHandoff` (`resumed: true`) alone does not:
+ // `retireStrandedPausedAgents` stamps it on a pause whose task is gone or has
+ // moved on, with no `resumedTaskId` and nothing requeued. Handing back there
+ // — to `agentData.taskId`, a task that no longer exists — parks a pointer no
+ // `agent:spawned` can ever clear, and both `triggerFeatureAgent` and
+ // `getDueFeatureAgents` refuse to run a feature agent that holds one. The
+ // agent would never run again, by schedule or by hand, recoverable only by
+ // Stop and re-activate. Those retirements fall through to
// `recordRunCompletion` below, which clears the pointer as it always did.
- const continuationTaskId = isAgentHandoff(agentData) ? agentData.result?.resumedTaskId : null;
+ const continuationTaskId = isQueuedContinuation(agentData) ? agentData.result.resumedTaskId : null;
if (continuationTaskId) {
// Compare-and-set against the retired agent's id, because this races the
// spawn of the very continuation it points at: `requeuePausedTask` runs
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index 337a624104..e3f9e5bf37 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -55,7 +55,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 { isQueuedContinuation } from '../lib/agentOutcome.js';
import { cosEvents } from './cosEvents.js';
import { getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';
import { ACTIVE_TASK_STATUSES, probeSequenceDrain, sequenceStepShapeReason } from './quotaBurnSequence.js';
@@ -363,7 +363,12 @@ function onMaintenanceAgentCompleted(agent) {
// 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;
+ //
+ // Gated on `isQueuedContinuation`, not the bare `isAgentHandoff`: a stranded
+ // pause retirement also stamps `resumed: true` with nothing requeued, so
+ // there is no continuation completion coming to advance this run — returning
+ // `null` here left the step (and the whole run) stuck on hold (#7469).
+ if (isQueuedContinuation(agent)) return null;
const stepId = agent.metadata?.taskQuotaBurnStepId;
const success = agent.result?.success === true;
return getMaintenanceRun(id)
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index 39b8a2b609..5be493dc12 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -179,6 +179,26 @@ describe('manual maintenance run', () => {
expect(state.invoked).toHaveLength(1);
});
+ it('re-evaluates the run immediately when a stranded pause is retired with no continuation queued (#7469)', async () => {
+ // `retireStrandedPausedAgents` (server/services/agentManagement.js) also
+ // stamps `resumed: true` — on a pause whose task is gone or moved on — but
+ // with NO `resumedTaskId`, because nothing was requeued. Reading that as a
+ // handoff the same way a relaunch is read made this listener return `null`
+ // and wait forever for a continuation that will never complete; the run
+ // advanced only once the `retryMaintenanceRuns` backstop eventually swept
+ // it. The step's underlying task is gone (not merely blocked), so a correct
+ // fix re-evaluates now and re-dispatches the step immediately.
+ const { run } = await start();
+ const stranded = {
+ ...agentFor(run, 0, false),
+ result: { success: false, resumed: true, error: 'Pause retired — its task task-0 no longer exists' },
+ };
+
+ await __onMaintenanceAgentCompleted(stranded);
+
+ expect(state.invoked).toHaveLength(2);
+ });
+
it('stops without recalling work, resumes from its ledger, and refuses a second run for the same app', async () => {
const { run } = await start();
await expect(start()).rejects.toMatchObject({ status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index f87538e274..34d98b63fd 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -50,7 +50,7 @@ import { getQuotaBurnDispatches, evaluateFamilies, PLAN_COMPLETE_SKIP_REASON, re
import { reconcileQuotaBurnReservations, reserveQuotaBurnDispatch } from './quotaBurnAcceptance.js';
import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';
-import { isAgentHandoff } from '../lib/agentOutcome.js';
+import { isQueuedContinuation } 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';
@@ -688,7 +688,13 @@ function onBurnAgentCompleted(agent) {
// 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;
+ //
+ // Gated on `isQueuedContinuation`, not the bare `isAgentHandoff`: a stranded
+ // pause retirement (`retireStrandedPausedAgents`) also stamps `resumed: true`
+ // but queues nothing, so there is no continuation run to emit that later
+ // `agent:completed` — returning `null` here stalled the family until the next
+ // `checkIntervalMinutes` tick (#7469).
+ if (isQueuedContinuation(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.js
index c1e6f00911..baa65076bb 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -663,6 +663,28 @@ describe('completion continuation', () => {
expect(state.runs).toEqual([]);
});
+ it('settles the ledger and walks the plan when a stranded pause is retired with no continuation queued (#7469)', async () => {
+ // `retireStrandedPausedAgents` (server/services/agentManagement.js) stamps
+ // `resumed: true` on a pause whose task was deleted or moved on — but with
+ // no `resumedTaskId`, because nothing was requeued. Reading that as a
+ // handoff (the bare `isAgentHandoff`) made `onBurnAgentCompleted` return
+ // `null`: the denial ledger never ran and the next job in the plan never
+ // dispatched, stalling the family until the 12-hour scheduled tick instead
+ // of advancing immediately like any other completion.
+ state.invokePending = { first: { count: 1 }, second: { count: 1 } };
+ await runQuotaBurnCycle({ trigger: 'manual' });
+ const stranded = {
+ taskId: 'burn-1',
+ metadata: { taskQuotaBurnFamily: 'grok', taskQuotaBurnStepId: 'first' },
+ result: { success: false, resumed: true, error: 'Pause retired — its task task-9 no longer exists' },
+ };
+
+ await __onBurnAgentCompleted(stranded);
+
+ expect(state.settled).toEqual(['grok']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['first', 'second']);
+ });
+
it('ignores an agent that was not a quota burn', async () => {
state.invokePending = { first: { count: 1 } };
await __onBurnAgentCompleted({ metadata: { taskType: 'user' } });