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

refactor: derive writeTaskUpdate's status transition once instead of seven times (#6620)

[._.]/ Adam Eivyaeee56a749db
diff --git a/server/lib/README.md b/server/lib/README.md
index 9b33ae6c4b..d8a25db395 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -412,6 +412,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `taskBlockCategories.js` | The `blockedCategory` vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. `PAUSED_BLOCKED_CATEGORIES` (paused until something outside the task changes — keeps the resume pointer), `USER_DECISION_BLOCKED_CATEGORIES` (user intent / open decision — the reaper's exemption), `NON_AUTO_RETRY_BLOCK_CATEGORIES` (their union — a completed investigation must never revive these), `TIMED_COOLDOWN_BLOCKED_CATEGORIES` (a timer clears these — the cooldown sweeper revives them, so block reporters stay quiet), `PROVIDER_CONFIG_BLOCKED_CATEGORY` (the shared literal the agent-spawn stamp site uses, so the stamp cannot drift from the two sets it belongs to). Pure. |
| `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. |
| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
+| `taskStatusTransition.js` | The CoS task STATUS TRANSITION vocabulary (#6620) — `resolveTaskStatusTransition(previousStatus, nextStatus)` classifies one update's status pair ONCE and returns `{ action, isRevive, isRequeue, entersInProgress, leavesInProgress, leavesBlocked, isTerminal }`, so `writeTaskUpdate`'s blocked/pause clear, resume-pointer drop, retry-hold retire, claim release, requeue stamp and emitted `tasks:changed` action all read one answer instead of re-deriving seven. A falsy `nextStatus` means "this patch carries no status" (a lease-renewal heartbeat) and releases nothing. `isTerminalTaskStatus(status)` is the shared `completed`/`blocked` predicate `cosTaskStore` and `cosTaskMerge` both read. Pure — metadata predicates (is this block a pause?) stay at the application site. |
| `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. |
| `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing. |
| `taskTargetScope.js` | Target scope for a scheduled task type: `INSTALL_WIDE_TASK_TYPES`, `MANAGED_APP_TARGET_TASK_TYPES`, `PROGRAMMATIC_SCHEDULED_TASK_TYPES`, `isProgrammaticScheduledTaskType`, `requiresManagedAppTarget`, `requiresInstallWideTarget`. Declared here (not in `services/taskScheduleRegistry.js`, which re-exports it) so `quotaBurnValidation.js` can reject a burn reference with the wrong target scope without importing upward into services. |
diff --git a/server/lib/index.js b/server/lib/index.js
index b3cbfb755f..5dc5104a77 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -383,6 +383,7 @@ export * from './taskPauseHold.js';
export * from './taskBlockCategories.js';
export * from './taskRequeue.js';
export * from './taskRetryHold.js';
+export * from './taskStatusTransition.js';
export * from './taskTargetBranch.js';
export * from './scheduledTaskTypes.js';
export * from './taskTargetScope.js';
diff --git a/server/lib/taskStatusTransition.js b/server/lib/taskStatusTransition.js
new file mode 100644
index 0000000000..9fe5ba5456
--- /dev/null
+++ b/server/lib/taskStatusTransition.js
@@ -0,0 +1,90 @@
+/**
+ * The CoS task STATUS TRANSITION vocabulary (#6620).
+ *
+ * `writeTaskUpdate` (services/cosTaskStore.js) applies half a dozen lifecycle
+ * rules to a task update — clear the blocked/pause metadata, drop a spent resume
+ * pointer, retire the retry hold, release the federation claim, stamp or clear
+ * the requeue marker, pick the `tasks:changed` action. Each of those used to
+ * re-derive "what transition is this?" from the raw `(previousStatus,
+ * updates.status)` pair at its own site, spread over 130 lines: the retry-hold
+ * clear and the claim release were the IDENTICAL predicate written twice twelve
+ * lines apart, and the requeue stamp and the emitted action independently keyed
+ * on the same `in_progress → pending` edge 52 lines apart while having to agree.
+ *
+ * Every one of those sites arrived in a different feature commit, and getting one
+ * wrong is not cosmetic: a missed pause-key clear made `resumeAgent` read its own
+ * pause as spent and spawn a SECOND agent on a fresh task; a stale claim lease
+ * blocks a legitimate retry by this instance or its peer for a full lease window;
+ * a stale `existingBranch` silently attaches a fresh perpetual run to a
+ * long-merged branch. So the question is asked ONCE, here, and every rule reads
+ * the answer off the descriptor rather than re-deriving one.
+ *
+ * Pure and dependency-free — it answers only "what KIND of transition is this?".
+ * Metadata predicates (is this block a pause? is this branch pointer the resume's?)
+ * are deliberately NOT here: they read the task's metadata, not its status pair,
+ * and belong at the application site.
+ */
+
+/**
+ * A task is terminal once it is `completed` or `blocked` — the point at which a
+ * resume pointer is spent and the federated merge stops advancing it. One
+ * definition for `writeTaskUpdate`'s pointer drop, its stale-failure reaper, and
+ * `cosTaskMerge`'s release-on-transition, which each carried their own copy.
+ */
+export const isTerminalTaskStatus = (status) => status === 'completed' || status === 'blocked';
+
+/**
+ * Classify one `(previousStatus, nextStatus)` pair.
+ *
+ * `nextStatus` is the update patch's `status` field AS PASSED — `undefined` (or
+ * empty) when the write carries no status at all, which is a meaningful case and
+ * not a synonym for "unchanged": a lease-renewal heartbeat passes no status and
+ * must release nothing, while an explicit write to the status the task already
+ * holds does apply the transition rules for that status. Fields that gate a
+ * RELEASE therefore require a status to be present; fields that describe the
+ * task's resulting state fall back to `previousStatus`.
+ *
+ * @param {string|undefined} previousStatus - the task's status before the write
+ * @param {string|undefined} nextStatus - `updates.status`, or undefined/'' when absent
+ * @returns {{
+ * action: 'unblocked'|'requeued'|'updated',
+ * isRevive: boolean, isRequeue: boolean,
+ * entersInProgress: boolean, leavesInProgress: boolean,
+ * leavesBlocked: boolean, isTerminal: boolean
+ * }}
+ */
+export function resolveTaskStatusTransition(previousStatus, nextStatus) {
+ // A falsy `nextStatus` is "no status in this patch": `writeTaskUpdate` spreads
+ // the status onto the task with the same truthiness test, so '' never lands.
+ const setsStatus = Boolean(nextStatus);
+ // The status the task will hold after the write.
+ const resultingStatus = setsStatus ? nextStatus : previousStatus;
+
+ // A revive: the task was parked and is spawnable again. Drives the `unblocked`
+ // action, which is what re-runs cos.init's dequeue (#2614).
+ const isRevive = resultingStatus === 'pending' && previousStatus === 'blocked';
+ // The one BACKWARD step in the lifecycle (#3376) — the orphan sweep and the
+ // retry-hold release both perform it, and the federated merge has to tell it
+ // apart from an ordinary edit landing on a peer's stale `pending` copy.
+ const isRequeue = resultingStatus === 'pending' && previousStatus === 'in_progress';
+
+ return {
+ action: isRevive ? 'unblocked' : (isRequeue ? 'requeued' : 'updated'),
+ isRevive,
+ isRequeue,
+ // A fresh spawn. Retires the requeue stamp: from here on THIS run's
+ // `lastSpawnedAt` is what a future requeue must beat.
+ entersInProgress: nextStatus === 'in_progress',
+ // The write lands a status OTHER than `in_progress` — the edge that retires
+ // every in-flight-only marker (the retry hold, the federation claim/lease).
+ // False for a patch carrying no status, so a heartbeat releases nothing.
+ leavesInProgress: setsStatus && nextStatus !== 'in_progress',
+ // Out of `blocked` by any door — a dedupe revive, an autopilot re-dispatch, a
+ // cooldown expiry, or a human unblocking it from the task list.
+ leavesBlocked: setsStatus && nextStatus !== 'blocked' && previousStatus === 'blocked',
+ // Keyed on the PATCH, not the resulting state: re-editing an already-completed
+ // task is not a fresh arrival at a terminal status and must not re-run the
+ // one-shot terminal cleanups.
+ isTerminal: isTerminalTaskStatus(nextStatus)
+ };
+}
diff --git a/server/lib/taskStatusTransition.test.js b/server/lib/taskStatusTransition.test.js
new file mode 100644
index 0000000000..e0a9715801
--- /dev/null
+++ b/server/lib/taskStatusTransition.test.js
@@ -0,0 +1,90 @@
+/**
+ * Contract for the status-transition descriptor (#6620).
+ *
+ * `writeTaskUpdate`'s own boundary tests (services/cosTaskStore.test.js) are the
+ * behavioral oracle — these pin the classification itself, which now answers for
+ * seven separate lifecycle rules at once. The cases below are distinct transition
+ * CLASSES, not permutations: each one is a different answer the seven rules read.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { resolveTaskStatusTransition, isTerminalTaskStatus } from './taskStatusTransition.js';
+
+describe('isTerminalTaskStatus', () => {
+ it('recognizes exactly completed and blocked', () => {
+ expect(isTerminalTaskStatus('completed')).toBe(true);
+ expect(isTerminalTaskStatus('blocked')).toBe(true);
+ expect(isTerminalTaskStatus('in_progress')).toBe(false);
+ expect(isTerminalTaskStatus('challenged')).toBe(false);
+ expect(isTerminalTaskStatus(undefined)).toBe(false);
+ });
+});
+
+describe('resolveTaskStatusTransition', () => {
+ it('classifies a revive (blocked → pending)', () => {
+ const t = resolveTaskStatusTransition('blocked', 'pending');
+ expect(t.action).toBe('unblocked');
+ expect(t.isRevive).toBe(true);
+ expect(t.leavesBlocked).toBe(true);
+ expect(t.leavesInProgress).toBe(true);
+ expect(t.isTerminal).toBe(false);
+ });
+
+ it('classifies a requeue (in_progress → pending)', () => {
+ const t = resolveTaskStatusTransition('in_progress', 'pending');
+ expect(t.action).toBe('requeued');
+ expect(t.isRequeue).toBe(true);
+ // The requeue releases both in-flight-only subsystems in the same write.
+ expect(t.leavesInProgress).toBe(true);
+ expect(t.leavesBlocked).toBe(false);
+ });
+
+ // A patch with NO status is not a transition. Collapsing absent into "not
+ // in_progress" would make every lease-renewal heartbeat retire the running
+ // task's own retry hold and federation lease.
+ it('treats an absent status as releasing nothing', () => {
+ const t = resolveTaskStatusTransition('in_progress', undefined);
+ expect(t.action).toBe('updated');
+ expect(t.leavesInProgress).toBe(false);
+ expect(t.leavesBlocked).toBe(false);
+ expect(t.entersInProgress).toBe(false);
+ expect(t.isTerminal).toBe(false);
+ // Same for the empty string, which `writeTaskUpdate` also declines to write.
+ expect(resolveTaskStatusTransition('blocked', '').leavesBlocked).toBe(false);
+ });
+
+ // `isTerminal` keys on the PATCH, not the resulting state: editing an
+ // already-completed task's description must not re-run the one-shot terminal
+ // cleanups (the resume-pointer drop) a second time.
+ it('does not report an edit to an already-terminal task as terminal', () => {
+ expect(resolveTaskStatusTransition('completed', undefined).isTerminal).toBe(false);
+ expect(resolveTaskStatusTransition('completed', 'completed').isTerminal).toBe(true);
+ });
+
+ // A spawn is the only write that enters in_progress, and it must NOT read as
+ // leaving it — otherwise the claim it carries is stripped by the same write.
+ it('classifies a spawn (pending → in_progress)', () => {
+ const t = resolveTaskStatusTransition('pending', 'in_progress');
+ expect(t.entersInProgress).toBe(true);
+ expect(t.leavesInProgress).toBe(false);
+ expect(t.action).toBe('updated');
+ });
+
+ // Reaching `pending` from anywhere else is an ordinary edit, not a revive or a
+ // requeue — only those two flips wake the scheduler.
+ it('does not treat pending → pending as a revive or requeue', () => {
+ const t = resolveTaskStatusTransition('pending', 'pending');
+ expect(t.action).toBe('updated');
+ expect(t.isRevive).toBe(false);
+ expect(t.isRequeue).toBe(false);
+ });
+
+ // Blocking a running task leaves in_progress AND is terminal, but is not
+ // "leaving blocked" — the blocked metadata this write is stamping must survive.
+ it('classifies in_progress → blocked without clearing the block it just set', () => {
+ const t = resolveTaskStatusTransition('in_progress', 'blocked');
+ expect(t.isTerminal).toBe(true);
+ expect(t.leavesInProgress).toBe(true);
+ expect(t.leavesBlocked).toBe(false);
+ });
+});
diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.js
index 87d15b8b75..6a0e8ab512 100644
--- a/server/services/cosTaskMerge.js
+++ b/server/services/cosTaskMerge.js
@@ -78,6 +78,7 @@ import { isLeaseLive, getClaimOwner, CLAIM_METADATA_KEYS, parseTimestampMs } fro
// here would form a circular import. taskParser has no cos-module deps.
import { PRIORITY_VALUES } from '../lib/taskParser.js';
import { isPostSpawnRequeue } from '../lib/taskRequeue.js';
+import { isTerminalTaskStatus } from '../lib/taskStatusTransition.js';
// Lifecycle rank — higher wins the content tiebreak (rule 2). Each status has a
// distinct rank so two DIFFERENT statuses never tie (full convergence); the only
@@ -100,7 +101,6 @@ import { isPostSpawnRequeue } from '../lib/taskRequeue.js';
// stale `pending` copy, which must NOT revert a running task.
const STATUS_RANK = Object.freeze({ completed: 5, blocked: 4, challenged: 3, in_progress: 2, pending: 1 });
const statusRank = (status) => STATUS_RANK[status] || 0;
-const isTerminalStatus = (status) => status === 'completed' || status === 'blocked';
// The metadata key carrying a task's content-edit timestamp (#1714). Stamped in
// cosTaskStore's write paths on every content edit and used here as the
@@ -308,7 +308,7 @@ function mergeOne(local, remote, now) {
// linger (mirrors cosTaskStore release-on-transition).
const metadata = { ...(base.metadata || {}) };
for (const key of CLAIM_METADATA_KEYS) delete metadata[key];
- if (claim && !isTerminalStatus(base.status)) Object.assign(metadata, claim);
+ if (claim && !isTerminalTaskStatus(base.status)) Object.assign(metadata, claim);
return { ...base, metadata };
}
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index d6d3dff817..ff9967be83 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -23,6 +23,7 @@ import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';
import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, isAgentPausedTask, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';
import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';
+import { resolveTaskStatusTransition, isTerminalTaskStatus } from '../lib/taskStatusTransition.js';
import { isInvestigationTask } from '../lib/investigationTasks.js';
import { PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';
import { splitTaskPromptFields } from '../lib/cosTaskPrompt.js';
@@ -50,11 +51,12 @@ const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);
// already use.
export { PAUSED_BLOCKED_CATEGORIES };
-// A task is terminal once it is completed or blocked — the same set cosTaskMerge's
-// release-on-transition uses. Consumed by the LI cross-peer verdict consume (#2779) to
-// spot a non-terminal→terminal ADOPTION (a failed hand-off blocks, a clean one completes;
-// both are legitimate execution outcomes worth recording).
-const isTerminalTaskStatus = (status) => status === 'completed' || status === 'blocked';
+// `isTerminalTaskStatus` is imported from lib/taskStatusTransition.js — the same
+// set cosTaskMerge's release-on-transition uses, and the one the LI cross-peer
+// verdict consume (#2779) reads to spot a non-terminal→terminal ADOPTION (a failed
+// hand-off blocks, a clean one completes; both are legitimate execution outcomes
+// worth recording). Three copies of that two-value set is exactly the drift the
+// transition module exists to prevent.
// Fields an `updateTask` patch may carry directly (vs nested under `metadata`);
// they're normalized into `metadata` on write. Listed once so the content-edit
@@ -433,6 +435,76 @@ async function preparePauseRelease(taskId, updates) {
return { agentId, metadata: { ...pointer, ...(updates.metadata || {}) } };
}
+/**
+ * Metadata a status transition RETIRES, as `[transition field, keys]` rows applied
+ * in order by `writeTaskUpdate`. One row per subsystem the transition releases —
+ * adding a lifecycle clear is a row here, not another hand-written predicate in the
+ * middle of the write.
+ *
+ * ORDER IS BEHAVIOR: the `leavesBlocked` row clears `blockedCategory`, and the
+ * resume-pointer drop below the loop reads that same key to decide whether the
+ * block was a PAUSE. A paused task flipped straight to `completed` is therefore no
+ * longer pause-categorized by the time the pointer is evaluated, and its spent
+ * pointer drops — pinned by cosTaskStore.test.js.
+ *
+ * The retry hold and the federation claim are two rows even though both key on
+ * `leavesInProgress`: they release different subsystems (#3373's cleanup handshake
+ * and #1563's cross-peer lease) and are separately documented at their sites. What
+ * they must never do again is drift, so they read the ONE descriptor field rather
+ * than each re-testing `updates.status !== 'in_progress'`.
+ */
+const TRANSITION_METADATA_CLEARS = Object.freeze([
+ // Leaving `blocked` by any door — a dedupe revive, an autopilot re-dispatch, an
+ // orphan-cooldown expiry, or a human unblocking it from the task list. Clearing
+ // only in `resumeAgent` left every one of those paths running a task that still
+ // advertised a live pause: the UI kept showing it parked, and `resumeAgent` on the
+ // still-paused agent record then read its own pause as spent and spawned a SECOND
+ // agent on a fresh task. The failure counters go too, or the revived task
+ // re-blocks on the budget it blocked with.
+ ['leavesBlocked', ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt', ...PAUSE_METADATA_KEYS]],
+ // A retry hold (#3373) only means anything while the task is `in_progress` waiting
+ // on a cleanup to resolve its resume pointer. Any other status the task reaches —
+ // terminal, or a requeue some other path performed — retires it, so drop the marker
+ // rather than leave a stale one for a late cleanup (or the orphan sweep) to act on.
+ ['leavesInProgress', [RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY]],
+ // Release the federation claim/lease (#1563). A claim only protects in-flight work;
+ // once the task completes, fails back to pending, or is blocked, it must become
+ // freely claimable by either peer — a stale lease blocks a legitimate retry (by this
+ // instance or its peer) for a full lease window.
+ ['leavesInProgress', CLAIM_METADATA_KEYS]
+]);
+
+/**
+ * Merge an `updateTask` patch's metadata onto the task's existing metadata, in the
+ * shape the store persists. Purely about the PATCH's shape — it answers nothing
+ * about the status transition, which `resolveTaskStatusTransition` owns.
+ *
+ * Legacy direct fields use ?? not ||, so an intentional clear to "" is preserved
+ * as "" rather than dropped: || maps every falsy value (incl. "") to undefined,
+ * which `writeTaskUpdate`'s cleanup pass then deletes, conflating "cleared" with
+ * "absent" (absent-vs-cleared, AGENTS.md). Only null becomes undefined (→ deleted);
+ * absent fields never enter the loop.
+ *
+ * The orchestration pins are re-normalized after that verbatim copy (#5992) so an
+ * update lands the same persisted shape `addTask` writes: a profile of empty role
+ * objects, or the default `direct` mode, is stored as absent rather than as an
+ * inert override. A null from the route still arrives here as `undefined` and is
+ * deleted by the cleanup pass — an explicit clear.
+ */
+function mergeUpdateMetadata(existingMetadata, updates) {
+ const merged = { ...existingMetadata, ...(updates.metadata || {}) };
+ for (const f of LEGACY_DIRECT_FIELDS) {
+ if (updates[f] !== undefined) merged[f] = updates[f] ?? undefined;
+ }
+ if (merged.orchestrationProfile !== undefined) {
+ merged.orchestrationProfile = normalizeOrchestrationProfile(merged.orchestrationProfile) ?? undefined;
+ }
+ if (merged.orchestrationMode !== undefined) {
+ merged.orchestrationMode = normalizeOrchestrationMode(merged.orchestrationMode) === 'orchestrated' ? 'orchestrated' : undefined;
+ }
+ return merged;
+}
+
async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue = false }) {
return withStateLock(async () => {
const state = await loadState();
@@ -453,45 +525,22 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
return { error: 'Task not found' };
}
- // Build updated metadata - merge existing with any new metadata
- const updatedMetadata = {
- ...tasks[taskIndex].metadata,
- ...(updates.metadata || {})
- };
- // Handle legacy fields that may be passed directly in updates. Use ?? not ||
- // so an intentional clear to "" is preserved as "" rather than dropped: || maps
- // every falsy value (incl. "") to undefined, which the cleanup pass below then
- // deletes, conflating "cleared" with "absent" (absent-vs-cleared, AGENTS.md).
- // Only null becomes undefined (→ deleted); absent fields never enter this loop.
- for (const f of LEGACY_DIRECT_FIELDS) {
- if (updates[f] !== undefined) updatedMetadata[f] = updates[f] ?? undefined;
- }
- // Re-normalize the orchestration pins the loop above just copied in verbatim
- // (#5992), so an update lands the same persisted shape `addTask` writes: a
- // profile of empty role objects, or the default `direct` mode, is stored as
- // absent rather than as an inert override. A null from the route still reaches
- // here as `undefined` and is deleted by the cleanup pass — an explicit clear.
- if (updatedMetadata.orchestrationProfile !== undefined) {
- updatedMetadata.orchestrationProfile = normalizeOrchestrationProfile(updatedMetadata.orchestrationProfile) ?? undefined;
- }
- if (updatedMetadata.orchestrationMode !== undefined) {
- updatedMetadata.orchestrationMode = normalizeOrchestrationMode(updatedMetadata.orchestrationMode) === 'orchestrated' ? 'orchestrated' : undefined;
- }
+ const updatedMetadata = mergeUpdateMetadata(tasks[taskIndex].metadata, updates);
- // Clear blocked/failure metadata when transitioning out of blocked status.
- //
- // The PAUSE keys go with them (`PAUSE_METADATA_KEYS`, lib/taskPauseHold.js).
- // `resumeAgent` is not the only way a paused task runs again — a dedupe revive, an
- // autopilot re-dispatch, an orphan-cooldown expiry, or a human unblocking it from
- // the task list all flip it back to `pending` through here. Clearing only in
- // `resumeAgent` left every one of those paths running a task that still advertised
- // a live pause: the UI kept showing it parked, and `resumeAgent` on the still-paused
- // agent record then read its own pause as spent and spawned a SECOND agent on a
- // fresh task. The clear belongs at the transition, not at one caller.
- if (updates.status && updates.status !== 'blocked' && tasks[taskIndex].status === 'blocked') {
- for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt', ...PAUSE_METADATA_KEYS]) {
- delete updatedMetadata[key];
- }
+ // Ask "what status transition is this?" ONCE. Every lifecycle rule below reads a
+ // field off this descriptor instead of re-deriving an answer from
+ // `(previousStatus, updates.status)` at its own site — which is how the retry-hold
+ // clear and the claim release ended up as the same predicate written twice, and
+ // how the requeue stamp and the emitted action came to key on the same edge from
+ // 52 lines apart while having to agree (#6620).
+ const previousStatus = tasks[taskIndex].status;
+ const transition = resolveTaskStatusTransition(previousStatus, updates.status);
+
+ // Retire the metadata this transition releases. Ordered — see the table's note on
+ // the `blockedCategory` clear feeding the resume-pointer check below.
+ for (const [condition, keys] of TRANSITION_METADATA_CLEARS) {
+ if (!transition[condition]) continue;
+ for (const key of keys) delete updatedMetadata[key];
}
// Drop the resume pointer once the task reaches a terminal state. `existingBranch`
@@ -513,7 +562,7 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
// revives the task. Stripping the pointer in either case means the revived task
// starts clean and abandons the worktree its dead agent left behind — which is
// exactly the recovery this mechanism exists for.
- if (isTerminalTaskStatus(updates.status) && !PAUSED_BLOCKED_CATEGORIES.has(updatedMetadata.blockedCategory)) {
+ if (transition.isTerminal && !PAUSED_BLOCKED_CATEGORIES.has(updatedMetadata.blockedCategory)) {
// The shared predicate identifies only retry-owned `existingBranch` pointers.
// Review-loop follow-ups own `reviewLoopPRBranch`, so their canonical target
// remains intact even when a legacy duplicate is removed here.
@@ -522,30 +571,6 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
delete updatedMetadata.resumeWorktreePath;
}
- // A retry hold (#3373) only means anything while the task is `in_progress`
- // waiting on a cleanup to resolve its resume pointer. Any other status the task
- // reaches — terminal, or a requeue that some other path performed — retires it,
- // so drop the marker rather than leave a stale one for a late cleanup (or the
- // orphan sweep) to act on. The release's own write passes these as undefined,
- // which lands in the same place.
- if (updates.status && updates.status !== 'in_progress') {
- delete updatedMetadata[RETRY_HOLD_KEY];
- delete updatedMetadata[RETRY_HOLD_SINCE_KEY];
- }
-
- // Release the federation claim/lease when a task leaves `in_progress` (issue
- // #1563). A claim only protects in-flight work; once the task completes, fails
- // back to pending, or is blocked, it must become freely claimable by either
- // peer — leaving a stale lease behind would block a legitimate retry (by this
- // instance or its peer) for a full lease window. The spawn's own
- // in_progress update carries `status: 'in_progress'` and is exempt, and a
- // lease-renewal heartbeat passes no `status` at all, so neither is stripped.
- if (updates.status && updates.status !== 'in_progress') {
- for (const key of CLAIM_METADATA_KEYS) {
- delete updatedMetadata[key];
- }
- }
-
// Stamp the moment a RUNNING task is requeued (#3376). `in_progress → pending`
// is the one backward transition in the lifecycle (the orphan sweep and the
// retry-hold release both perform it), and the federated merge has to be able to
@@ -556,13 +581,13 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
// other side's `lastSpawnedAt`, says the requeue came AFTER that spawn. Only the
// real transition sets it, so a later edit carries it forward untouched, and the
// next spawn clears it below.
- if (updates.status === 'pending' && tasks[taskIndex].status === 'in_progress') {
+ if (transition.isRequeue) {
updatedMetadata[REQUEUED_AT_KEY] = new Date(now).toISOString();
}
// A fresh spawn retires the marker — from here on THIS run's `lastSpawnedAt` is
// what a future requeue must beat, and a leftover stamp from the previous cycle
// would let a peer's pre-spawn `pending` copy win on a stale requeue.
- if (updates.status === 'in_progress') delete updatedMetadata[REQUEUED_AT_KEY];
+ if (transition.entersInProgress) delete updatedMetadata[REQUEUED_AT_KEY];
// Bump the content-edit stamp (#1714) on a genuine content change so the peer's
// claim-aware merge can resolve a same-status edit by newest-edit-wins. Compared
@@ -590,7 +615,6 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
metadata: updatedMetadata
};
- const previousStatus = tasks[taskIndex].status;
tasks[taskIndex] = updatedTask;
// Write back to file
@@ -598,26 +622,23 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
const markdown = generateTasksMarkdown(tasks, includeApprovalFlags);
await writeTaskFile(filePath, markdown);
- // A blocked → pending flip is a revive: the task is newly spawnable, exactly
- // like an approval. Emit a distinct action so cos.init's listener re-runs the
- // dequeue (#2614) — the generic 'updated' action doesn't wake the scheduler,
- // which left revived tasks stranded until an unrelated event or timer fired.
- //
- // An in_progress → pending flip is a requeue and needs the same wake (#3373):
- // a failed run's retry is released from its hold by exactly this transition,
- // and by then the `agent:completed` dequeue has long since run — without a
- // signal the retry would idle until the next timer. Same for the orphan sweep's
- // requeue, which previously depended on its caller remembering to evaluate.
- const action = updatedTask.status === 'pending' && previousStatus === 'blocked'
- ? 'unblocked'
- : (updatedTask.status === 'pending' && previousStatus === 'in_progress' ? 'requeued' : 'updated');
+ // `transition.action` distinguishes the two flips that must WAKE the scheduler
+ // from an ordinary edit. A blocked → pending flip is a revive: the task is newly
+ // spawnable, exactly like an approval, and cos.init's listener re-runs the dequeue
+ // on it (#2614) — the generic 'updated' action doesn't, which left revived tasks
+ // stranded until an unrelated event or timer fired. An in_progress → pending flip
+ // is a requeue and needs the same wake (#3373): a failed run's retry is released
+ // from its hold by exactly this transition, and by then the `agent:completed`
+ // dequeue has long since run — without a signal the retry would idle until the
+ // next timer. Same for the orphan sweep's requeue, which previously depended on
+ // its caller remembering to evaluate.
// `previousStatus` rides along so consumers can key on the TRANSITION rather
// than re-deriving one from the level. `updateTask` on an already-terminal task
// re-emits `updated` with the same status — an edit to a completed task's
// description is enough — so a consumer that reacts to "reached completed"
// (the investigation auto-retry; the voice completion line) needs the edge, not
// `status === 'completed'`, which is true on every later write too.
- const change = { type: taskType, action, task: updatedTask, previousStatus };
+ const change = { type: taskType, action: transition.action, task: updatedTask, previousStatus };
if (suppressDequeue) change.suppressDequeue = true;
cosEvents.emit('tasks:changed', change);
return updatedTask;