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

address review (codex): identify a requeue causally, not by recency (#3376)

[._.]/ Adam Eivy23c62670b8fb
diff --git a/server/lib/README.md b/server/lib/README.md
index 6093bc4914..daa817b3bc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -217,6 +217,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). |
| `jsonExtract.js` | Pull JSON blocks out of LLM responses. |
| `taskParser.js` | Parse `TASKS.md` format. |
+| `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. |
| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |
| `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 964f51bc73..f4ea6668b5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -197,6 +197,7 @@ export * from './vectorMath.js';
export * from './htmlToText.js';
export * from './jsonExtract.js';
export * from './taskParser.js';
+export * from './taskRequeue.js';
export * from './taskRetryHold.js';
export * from './taxonomyTally.js';
export * from './xmlEntities.js';
diff --git a/server/lib/taskRequeue.js b/server/lib/taskRequeue.js
new file mode 100644
index 0000000000..e9c6810ed9
--- /dev/null
+++ b/server/lib/taskRequeue.js
@@ -0,0 +1,51 @@
+/**
+ * The REQUEUE stamp (#3376) — pure metadata helpers for the one backward step in
+ * the CoS task lifecycle.
+ *
+ * A task normally advances `pending → in_progress → (challenged) → terminal`, and
+ * the federated merge leans on that (higher status = newer truth). Two paths move
+ * it BACKWARD on purpose: the orphan sweep's requeue (`handleOrphanedTask`) and
+ * the retry-hold release (`releaseRetryHold`, #3373). Both write the resume
+ * pointer telling the retry which branch/worktree to continue from, so a peer's
+ * stale `in_progress` snapshot must not win that merge and discard it.
+ *
+ * Recency alone can't decide it: an ordinary content edit landing on a peer's
+ * stale `pending` copy also carries a newer `updatedAt`, and letting THAT beat a
+ * genuinely running `in_progress` would revert a live task and invite a duplicate
+ * spawn. So the requeue stamps `lastRequeuedAt` and the merge asks a causal
+ * question instead — did the requeue happen AFTER the spawn the other side is
+ * reporting? Only a real transition sets the stamp, and `cosTaskStore` clears it
+ * on the next spawn, so the comparison stays anchored to the current run.
+ */
+
+/** Metadata key stamped by `cosTaskStore.updateTask` on `in_progress → pending`. */
+export const REQUEUED_AT_KEY = 'lastRequeuedAt';
+
+/** Metadata key stamped by `agentLifecycle` when it marks a task `in_progress`. */
+export const LAST_SPAWNED_AT_KEY = 'lastSpawnedAt';
+
+const stampMs = (task, key) => {
+ const ms = Date.parse(task?.metadata?.[key] ?? '');
+ return Number.isNaN(ms) ? null : ms;
+};
+
+/**
+ * Is `pendingTask` the product of requeuing the very run `inProgressTask` is
+ * reporting — i.e. did the requeue happen strictly AFTER that spawn?
+ *
+ * True means the `in_progress` side is a pre-requeue snapshot and the `pending`
+ * side is the newer truth (with the resume pointer, and with its claim already
+ * released by the same write — see #1563). False means we cannot establish that
+ * ordering, which covers an ordinary edit on a stale `pending` copy AND a peer
+ * that predates the stamp; callers fall back to the lifecycle rank there, so an
+ * older peer behaves exactly as it does today.
+ *
+ * Depends only on the pair, so both peers compute the same answer.
+ */
+export function isPostSpawnRequeue(pendingTask, inProgressTask) {
+ if (pendingTask?.status !== 'pending' || inProgressTask?.status !== 'in_progress') return false;
+ const requeuedAt = stampMs(pendingTask, REQUEUED_AT_KEY);
+ const spawnedAt = stampMs(inProgressTask, LAST_SPAWNED_AT_KEY);
+ if (requeuedAt === null || spawnedAt === null) return false;
+ return requeuedAt > spawnedAt;
+}
diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.js
index 7c5133f448..e5fd9ff5e5 100644
--- a/server/services/cosTaskMerge.js
+++ b/server/services/cosTaskMerge.js
@@ -31,8 +31,9 @@
* of holding it `in_progress` forever (a live claim alone can't carry that
* signal — the owner strips the claim when it completes). Two pairings are
* exempt because their transitions run BACKWARD in rank and would otherwise
- * never converge — anything-vs-`challenged` (#2441) and `in_progress`-vs-
- * `pending` (#3376) are decided by newest `updatedAt`; see pickContentBase.
+ * never converge: anything-vs-`challenged` (#2441) is decided by newest
+ * `updatedAt`, and `in_progress`-vs-`pending` (#3376) by whether the pending
+ * side's requeue postdates the other side's spawn. See pickContentBase.
*
* 3. Resolve the CLAIM metadata independently of content via the live lease:
* a side holding an unexpired lease is authoritative (the other peer must
@@ -76,6 +77,7 @@ import { isLeaseLive, getClaimOwner, CLAIM_METADATA_KEYS, parseTimestampMs } fro
// store imports THIS module for mergeTaskLists, so pulling its PRIORITY_VALUES
// 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';
// 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
@@ -91,9 +93,11 @@ import { PRIORITY_VALUES } from '../lib/taskParser.js';
// NOT terminal (the dispute resolves back to pending or forward to blocked), so it
// keeps a live claim the same way in_progress does.
//
-// The `in_progress`/`pending` pair carries the same caveat (#3376): a requeue moves
-// a task backward, so `pickContentBase` resolves that pair by newest `updatedAt`
-// too, falling back to this rank only when the stamps tie.
+// The `in_progress`/`pending` pair carries a narrower version of the same caveat
+// (#3376): a requeue moves a task backward, so `pickContentBase` lets a `pending`
+// side win that pair when its requeue stamp postdates the other side's spawn —
+// falling back to this rank in every other case, including an ordinary edit on a
+// 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';
@@ -133,7 +137,18 @@ function resolveClaim(local, remote, now) {
if (lExp !== rExp) return claimTriple(lExp > rExp ? local : remote);
const lOwner = getClaimOwner(local.metadata) || '';
const rOwner = getClaimOwner(remote.metadata) || '';
- return claimTriple(lOwner <= rOwner ? local : remote);
+ if (lOwner !== rOwner) return claimTriple(lOwner < rOwner ? local : remote);
+ // Same owner AND same expiry — the two sides are the same claim, but their
+ // `claimedAt` can still differ (a re-claim of a task this instance already
+ // held). Returning "whichever is local" would leave each peer with a
+ // different triple forever, so break on the remaining field too: earliest
+ // `claimedAt` wins, which is the claim that actually started this run.
+ const lAt = parseTimestampMs(local.metadata?.claimedAt);
+ const rAt = parseTimestampMs(remote.metadata?.claimedAt);
+ if (lAt === rAt) return claimTriple(local);
+ if (lAt === null) return claimTriple(remote);
+ if (rAt === null) return claimTriple(local);
+ return claimTriple(lAt < rAt ? local : remote);
}
if (localLive) return claimTriple(local);
if (remoteLive) return claimTriple(remote);
@@ -199,20 +214,20 @@ function pickContentBase(local, remote) {
// pointer (`existingBranch` / `resumeWorktreePath`) that write just resolved, so
// the eventual retry restarts from scratch. Two live paths requeue this way:
// the orphan sweep (`handleOrphanedTask`, agentManagement.js) and the retry-hold
- // release (`releaseRetryHold`, agentWorktreeCleanup.js, #3373). So when EXACTLY
- // one side is `in_progress` and the other is `pending`, decide by newest edit —
- // both transitions bump `updatedAt`, so a genuinely newer spawn still wins over
- // an older `pending`. Symmetric (depends only on the pair), so both peers
- // converge. Scoped to this pair only: `completed` (rule 2) is never involved.
- const isRequeuePair = (local.status === 'in_progress' && remote.status === 'pending')
- || (local.status === 'pending' && remote.status === 'in_progress');
- if (isRequeuePair) {
- const lq = updatedAtMs(local);
- const rq = updatedAtMs(remote);
- // Equal/absent stamps (legacy un-stamped peer) fall through to the rank
- // comparison below, preserving today's `in_progress`-wins behavior.
- if (lq !== rq) return rq > lq ? remote : local;
- }
+ // release (`releaseRetryHold`, agentWorktreeCleanup.js, #3373).
+ //
+ // The exemption is CAUSAL, not merely recent. Deciding this pair by `updatedAt`
+ // alone would also hand the win to an ordinary content edit that happens to land
+ // on a peer's stale `pending` copy — reverting a genuinely running task to
+ // `pending` and inviting a second agent onto it, which is worse than the delayed
+ // retry this fixes. So the `pending` side wins only when its requeue stamp is
+ // strictly NEWER than the spawn the `in_progress` side is reporting
+ // (`isPostSpawnRequeue`); anything else falls through to the rank below, which
+ // is exactly today's behavior — including for a peer too old to stamp.
+ // Symmetric (depends only on the pair), so both peers converge. `completed`
+ // (rule 2) is never involved: the test requires this exact status pair.
+ if (isPostSpawnRequeue(local, remote)) return local;
+ if (isPostSpawnRequeue(remote, local)) return remote;
const lr = statusRank(local.status);
const rr = statusRank(remote.status);
if (rr !== lr) return rr > lr ? remote : local;
@@ -272,17 +287,17 @@ function mergeOne(local, remote, now) {
// when content came from the other side — EXCEPT when the winner is a requeue
// (#3376). `cosTaskStore.updateTask` releases the claim in the very write that
// moves a task out of `in_progress` (#1563), precisely so a stale lease can't
- // block the retry for a full lease window. So when a newer `pending` beats the
- // counterpart's stale `in_progress` snapshot, that snapshot's lease is a
- // pre-release leftover: re-applying it would re-impose the lease the requeue
- // just dropped and undo half of what adopting the requeue bought us. Only this
- // exact pairing is excluded — a claim held by the WINNING `pending` side is
- // still honored, because dispatch takes the lease BEFORE flipping the status to
- // `in_progress` (agentLifecycle.js), so `pending` + live claim is a legitimate
- // in-flight shape a peer must keep seeing. Both peers reach the same `base` and
- // counterpart, so this stays symmetric.
+ // block the retry for a full lease window. So when a requeue beats the
+ // counterpart's pre-requeue `in_progress` snapshot, that snapshot's lease
+ // belongs to the run the requeue just retired: re-applying it would re-impose
+ // the lease the requeue dropped and undo half of what adopting it bought us.
+ // Only the counterpart's claim is excluded — a claim held by the WINNING
+ // `pending` side is still honored, because dispatch takes the lease BEFORE
+ // flipping the status to `in_progress` (agentLifecycle.js), so `pending` + live
+ // claim is a legitimate in-flight shape a peer must keep seeing. Both peers
+ // reach the same `base` and counterpart, so this stays symmetric.
const counterpart = base === local ? remote : local;
- const claim = (base.status === 'pending' && counterpart.status === 'in_progress')
+ const claim = isPostSpawnRequeue(base, counterpart)
? (isLeaseLive(base.metadata, now) ? claimTriple(base) : null)
: resolveClaim(local, remote, now);
diff --git a/server/services/cosTaskMerge.test.js b/server/services/cosTaskMerge.test.js
index c930084d71..e44906e7bb 100644
--- a/server/services/cosTaskMerge.test.js
+++ b/server/services/cosTaskMerge.test.js
@@ -298,22 +298,29 @@ describe('mergeTaskLists', () => {
});
describe('in_progress → pending requeue merge (#3376)', () => {
+ // The requeue is identified CAUSALLY, not by recency: `lastRequeuedAt` (stamped
+ // by cosTaskStore on in_progress → pending) must postdate the `lastSpawnedAt`
+ // the other side is reporting. `requeued`/`running` build that pair.
const stamped = (id, status, updatedAt, extra = {}) =>
task(id, status, { metadata: { updatedAt, ...extra } });
+ const requeued = (updatedAt, requeuedAt, extra = {}) =>
+ stamped('task-r', 'pending', updatedAt, { lastRequeuedAt: requeuedAt, ...extra });
+ const running = (updatedAt, spawnedAt, extra = {}) =>
+ stamped('task-r', 'in_progress', updatedAt, { lastSpawnedAt: spawnedAt, ...extra });
- it('a newer requeue survives a peer\'s stale in_progress snapshot, keeping its resume pointer', () => {
+ it('a requeue that postdates the peer\'s spawn survives its stale in_progress snapshot, keeping the resume pointer', () => {
// The orphan sweep (handleOrphanedTask) / retry-hold release (releaseRetryHold)
// move in_progress → pending and stamp the resume pointer they just resolved.
// A pure status-rank merge would let rank-2 `in_progress` revert rank-1
// `pending` and discard that metadata.
- const requeued = [stamped('task-r', 'pending', future(1000), {
+ const local = [requeued(future(1000), future(900), {
existingBranch: 'cos/task-x/agent-y',
resumeWorktreePath: '/data/cos/worktrees/task-x',
})];
- const stale = [stamped('task-r', 'in_progress', past(1000))];
+ const stale = [running(past(1000), past(1000))];
for (const merged of [
- mergeTaskLists(requeued, stale, { now: NOW })[0],
- mergeTaskLists(stale, requeued, { now: NOW })[0],
+ mergeTaskLists(local, stale, { now: NOW })[0],
+ mergeTaskLists(stale, local, { now: NOW })[0],
]) {
expect(merged.status).toBe('pending');
expect(merged.metadata.existingBranch).toBe('cos/task-x/agent-y');
@@ -321,8 +328,34 @@ describe('mergeTaskLists', () => {
}
});
+ it('a NEWER edit on a stale pending copy does NOT revert a running task', () => {
+ // The hole a pure recency rule would open: peer B edits its stale `pending`
+ // copy (priority/description), which bumps `updatedAt` past the running
+ // peer's — but no requeue happened, so `in_progress` must stand. Reverting
+ // here would strip the live lease and invite a second agent onto the task.
+ const edited = [stamped('task-r', 'pending', future(1000), { priority: 'HIGH' })];
+ const live = [running(past(1000), past(1000), { ...liveClaim('peer-A') })];
+ for (const merged of [
+ mergeTaskLists(edited, live, { now: NOW })[0],
+ mergeTaskLists(live, edited, { now: NOW })[0],
+ ]) {
+ expect(merged.status).toBe('in_progress');
+ expect(merged.metadata.claimedBy).toBe('peer-A');
+ }
+ });
+
+ it('a requeue stamp from a PREVIOUS cycle does not beat a later spawn', () => {
+ // Requeued, then re-spawned. A peer still holding the pre-spawn `pending`
+ // copy carries the old `lastRequeuedAt`; it predates this spawn, so the
+ // running record wins. (cosTaskStore also clears the stamp on spawn.)
+ const old = [requeued(future(1000), past(2000))];
+ const respawned = [running(past(1000), past(500))];
+ expect(mergeTaskLists(old, respawned, { now: NOW })[0].status).toBe('in_progress');
+ expect(mergeTaskLists(respawned, old, { now: NOW })[0].status).toBe('in_progress');
+ });
+
it('a genuinely newer in_progress (a peer that just spawned) still wins over an older pending', () => {
- const spawned = [stamped('task-r', 'in_progress', future(1000))];
+ const spawned = [running(future(1000), future(1000))];
const older = [stamped('task-r', 'pending', past(1000))];
expect(mergeTaskLists(older, spawned, { now: NOW })[0].status).toBe('in_progress');
expect(mergeTaskLists(spawned, older, { now: NOW })[0].status).toBe('in_progress');
@@ -331,25 +364,23 @@ describe('mergeTaskLists', () => {
it('completed still wins outright over a newer pending or in_progress', () => {
const completed = [stamped('task-r', 'completed', past(1000))];
for (const newer of [
- [stamped('task-r', 'pending', future(1000))],
- [stamped('task-r', 'in_progress', future(1000))],
+ [requeued(future(1000), future(1000))],
+ [running(future(1000), future(1000))],
]) {
expect(mergeTaskLists(completed, newer, { now: NOW })[0].status).toBe('completed');
expect(mergeTaskLists(newer, completed, { now: NOW })[0].status).toBe('completed');
}
});
- it('does NOT re-impose the stale in_progress side\'s lease on the adopted requeue', () => {
+ it('does NOT re-impose the retired run\'s lease on the adopted requeue', () => {
// The requeue write releases the claim (#1563) so the retry is freely
// claimable; rule 3 would otherwise re-attach the peer's pre-release lease
// and block that retry for a full lease window.
- const requeued = [stamped('task-r', 'pending', future(1000))];
- const stale = [task('task-r', 'in_progress', {
- metadata: { updatedAt: past(1000), ...liveClaim('peer-A') },
- })];
+ const local = [requeued(future(1000), future(900))];
+ const stale = [running(past(1000), past(1000), { ...liveClaim('peer-A') })];
for (const merged of [
- mergeTaskLists(requeued, stale, { now: NOW })[0],
- mergeTaskLists(stale, requeued, { now: NOW })[0],
+ mergeTaskLists(local, stale, { now: NOW })[0],
+ mergeTaskLists(stale, local, { now: NOW })[0],
]) {
expect(merged.status).toBe('pending');
expect(merged.metadata.claimedBy).toBeUndefined();
@@ -360,33 +391,42 @@ describe('mergeTaskLists', () => {
it('keeps a live claim the winning pending side holds (dispatch claims before it flips to in_progress)', () => {
// agentLifecycle takes the lease first and only then writes in_progress, so
// `pending` + live claim is a real in-flight shape the peer must keep seeing.
- const claimed = [task('task-r', 'pending', {
- metadata: { updatedAt: future(1000), ...liveClaim('peer-B') },
- })];
- const stale = [task('task-r', 'in_progress', {
- metadata: { updatedAt: past(1000), ...liveClaim('peer-A') },
- })];
+ const local = [requeued(future(1000), future(900), { ...liveClaim('peer-B') })];
+ const stale = [running(past(1000), past(1000), { ...liveClaim('peer-A') })];
for (const merged of [
- mergeTaskLists(claimed, stale, { now: NOW })[0],
- mergeTaskLists(stale, claimed, { now: NOW })[0],
+ mergeTaskLists(local, stale, { now: NOW })[0],
+ mergeTaskLists(stale, local, { now: NOW })[0],
]) {
expect(merged.status).toBe('pending');
expect(merged.metadata.claimedBy).toBe('peer-B');
}
});
- it('on equal/absent stamps, keeps today\'s rank behavior (in_progress wins)', () => {
+ it('an un-stamped peer keeps today\'s rank behavior (in_progress wins)', () => {
+ // A peer too old to stamp `lastRequeuedAt` — or a spawn too old to stamp
+ // `lastSpawnedAt` — can't establish the ordering, so nothing changes for it.
const inProgress = [task('task-r', 'in_progress')];
const pending = [task('task-r', 'pending')];
expect(mergeTaskLists(inProgress, pending, { now: NOW })[0].status).toBe('in_progress');
expect(mergeTaskLists(pending, inProgress, { now: NOW })[0].status).toBe('in_progress');
- // Equal (not merely absent) stamps take the same fallback.
- const sameStamp = past(500);
- expect(mergeTaskLists(
- [stamped('task-r', 'pending', sameStamp)],
- [stamped('task-r', 'in_progress', sameStamp)],
- { now: NOW },
- )[0].status).toBe('in_progress');
+ // Requeue stamped, but the peer's spawn is not — still no ordering.
+ const halfStamped = [requeued(future(1000), future(900))];
+ const unstampedSpawn = [stamped('task-r', 'in_progress', past(1000))];
+ expect(mergeTaskLists(halfStamped, unstampedSpawn, { now: NOW })[0].status).toBe('in_progress');
+ expect(mergeTaskLists(unstampedSpawn, halfStamped, { now: NOW })[0].status).toBe('in_progress');
+ });
+
+ it('two live claims with the same owner and expiry converge on one claimedAt', () => {
+ // Same claim seen from both sides with a differing `claimedAt` (a re-claim of
+ // a task this instance already held) — the deterministic lease tiebreak must
+ // cover that field too, or each peer keeps its own copy forever.
+ const withClaimedAt = (claimedAt) => [task('task-r', 'in_progress', {
+ metadata: { ...liveClaim('peer-A'), claimedAt },
+ })];
+ const early = withClaimedAt(past(2000));
+ const late = withClaimedAt(past(500));
+ expect(mergeTaskLists(early, late, { now: NOW })[0].metadata.claimedAt)
+ .toBe(mergeTaskLists(late, early, { now: NOW })[0].metadata.claimedAt);
});
});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 7d25acc3c3..6db7f5343b 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -19,6 +19,7 @@ import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaiti
import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, normalizeReviewerModels } from '../lib/validation.js';
import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';
+import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';
import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
@@ -492,6 +493,24 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat
}
}
+ // 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
+ // tell that requeue apart from an ordinary content edit that merely happens to
+ // land on a peer's stale `pending` copy — the first must beat a stale
+ // `in_progress` snapshot, the second must NOT revert a genuinely running task.
+ // `updatedAt` alone can't distinguish them; this stamp, compared against the
+ // 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') {
+ 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];
+
// 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
// against the task's CURRENT metadata so a lease-renewal heartbeat that re-includes
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 9603475b97..3ffc6f6c98 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -563,6 +563,26 @@ describe('cosTaskStore.updateTask', () => {
expect(done.metadata.leaseExpiresAt).toBeUndefined();
});
+ it('stamps lastRequeuedAt only on in_progress → pending, and clears it on the next spawn (#3376)', async () => {
+ await addTask({ description: 'requeue', id: 'task-requeue' }, 'user');
+ // A plain content edit on a pending task is not a requeue.
+ const edited = await updateTask('task-requeue', { description: 'requeue edited' }, 'user');
+ expect(edited.metadata.lastRequeuedAt).toBeUndefined();
+
+ await updateTask('task-requeue', { status: 'in_progress' }, 'user');
+ // The orphan sweep / retry-hold release transition — this one IS a requeue.
+ const requeued = await updateTask('task-requeue', { status: 'pending' }, 'user');
+ expect(typeof requeued.metadata.lastRequeuedAt).toBe('string');
+
+ // An edit while pending carries the stamp forward untouched…
+ const stamp = requeued.metadata.lastRequeuedAt;
+ const edit = await updateTask('task-requeue', { description: 'requeue again' }, 'user');
+ expect(edit.metadata.lastRequeuedAt).toBe(stamp);
+ // …and the next spawn retires it, so a peer's pre-spawn copy can't win on it.
+ const respawned = await updateTask('task-requeue', { status: 'in_progress' }, 'user');
+ expect(respawned.metadata.lastRequeuedAt).toBeUndefined();
+ });
+
it('keeps the claim while the task stays in_progress (lease renewal, no status change) (#1563)', async () => {
await addTask({ description: 'renew', id: 'task-renew' }, 'user');
await updateTask('task-renew', {