From 573e1a2104bf2b2ee940b2871ccf8298940c713d Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 02:14:45 -0700 Subject: [PATCH 1/9] feat(tasks): a lapsed lease was claimable and unfindable at the same time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ADR-018 D4 made a task claim a lease, and the claim route honours it: one CAS with four ways to win, two of which recognise an expired hold. The LIST route never learned about any of it — `GET /:podId` filters on stored `status` alone (tasksApi.ts:126), so a task whose claimant died sat `claimed` forever and appeared in nobody's board. Claim takes a `taskId` and never scans, so the only surface that could discover a lapsed row was the list, and the only seat that could name one was the seat that died holding it. Nothing sweeps lapsed claims back to `pending` — grep for `claimExpiresAt` across backend/cli/packages returns the model, the CAS, and the 409 body, and no reaper. Two halves: `leaseState` on every listed row — `unleased` | `held` | `lapsed`, derived from the same `TASK_CLAIM_LEASE_MS` the CAS uses, including the legacy branch where `claimExpiresAt` is null and expiry comes from `claimedAt`. One `now` per page so two rows can't report states that never coexisted. It is deliberately not called `claimable`. Claimability is a relation between a row and an asker — the CAS's second branch admits the current holder renewing its own lease, which no per-row field can express, so three of four branches are representable here and the fourth is structurally out of reach. A reader that treats `held` as "do not attempt" stops a seat from resuming its own task. theo's heartbeat gains a rescue step. It already fetches the whole board (Step 2) and already reassigns unowned work (old 5a), so rescue is that same operation with a wider definition of unowned. It writes `{ status: 'pending', assignee: null }` — clearing the assignee is the load-bearing half, because `status` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulled, it drops into the existing classify-and- assign loop on the same tick, so nova/pixel/ops need no edit at all. Tests run against a real in-memory Mongo so the CAS's `$or` is evaluated by Mongo rather than by a second copy of the predicate in the test. The differential earns its place by mutation: dropping the field's legacy branch fails 2 tests, and drifting the CAS instead — removing its fourth branch while leaving the field intact — fails only the differential. Co-Authored-By: Claude Opus 5 --- .../unit/routes/tasksApi.leaseState.test.js | 262 ++++++++++++++++++ backend/routes/registry/presets.ts | 7 +- backend/routes/tasksApi.ts | 55 +++- 3 files changed, 320 insertions(+), 4 deletions(-) create mode 100644 backend/__tests__/unit/routes/tasksApi.leaseState.test.js diff --git a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js new file mode 100644 index 0000000000..f0f904defc --- /dev/null +++ b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js @@ -0,0 +1,262 @@ +/** + * `leaseState` must agree with the claim CAS — and must NOT be read as + * claimability. + * + * ADR-018 D4 made a claim a lease, and the claim route honours it: four ways to + * win, including two that recognise an expired hold. The LIST route never did — + * it filtered on stored `status` alone, so a task abandoned by a dead claimant + * was claimable and unfindable at the same time. Claim takes a taskId and never + * scans, so the only seat that could reach the row was the one that died holding + * it, and nothing sweeps lapsed claims back to `pending`. + * + * These run against a real in-memory Mongo so the CAS's `$or` is evaluated by + * Mongo itself, not by a second copy of the predicate written in the test. A + * mocked Task model would assert only that the route calls findOneAndUpdate. + * + * Two invariants, and the second is the one that decays quietly: + * 1. For a live row (pending|claimed), `leaseState !== 'held'` iff a STRANGER's + * claim succeeds. + * 2. `held` does NOT mean "do not attempt", and `unleased` does NOT mean + * "available" — leaseState describes the LEASE, not the caller's rights. + */ + +const request = require('supertest'); +const express = require('express'); +const mongoose = require('mongoose'); + +jest.mock('../../../middleware/auth', () => (req, res, next) => { + req.userId = req.get('x-test-user') || 'holder'; + req.user = { id: req.userId, _id: req.userId }; + next(); +}); +jest.mock('../../../middleware/agentRuntimeAuth', () => (req, res, next) => next()); + +const POD_ID = 'aaaaaaaaaaaaaaaaaaaaaaaa'; + +jest.mock('../../../models/Pod', () => ({ + findById: jest.fn(() => ({ + lean: jest.fn().mockResolvedValue({ + type: 'chat', + members: [{ toString: () => 'holder' }, { toString: () => 'stranger' }], + }), + })), +})); + +jest.mock('../../../models/User', () => ({ + findById: jest.fn(() => ({ + select: jest.fn(() => ({ lean: jest.fn().mockResolvedValue({ username: 'tester' }) })), + })), +})); + +jest.mock('../../../services/githubAppService', () => ({ isPatConfigured: jest.fn(() => false) })); +jest.mock('../../../services/taskEventService', () => ({ emitTaskUpdated: jest.fn() })); + +const Task = require('../../../models/Task'); +const tasksApi = require('../../../routes/tasksApi'); + +const MIN = 60 * 1000; +const LEASE_MS = 30 * MIN; + +let mongod; +let app; + +// Each row states what it is and what the CAS must do with it. `strangerWins` +// is the CAS's answer, asserted against the route rather than assumed. +const ROWS = [ + { + taskId: 'TASK-001', + label: 'pending, never claimed', + doc: { status: 'pending' }, + leaseState: 'unleased', + strangerWins: true, + }, + { + taskId: 'TASK-002', + label: 'claimed, lease live', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - 5 * MIN), + claimExpiresAt: () => new Date(Date.now() + 25 * MIN), + }, + leaseState: 'held', + strangerWins: false, + }, + { + taskId: 'TASK-003', + label: 'claimed, lease expired', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - 90 * MIN), + claimExpiresAt: () => new Date(Date.now() - 60 * MIN), + }, + leaseState: 'lapsed', + strangerWins: true, + }, + { + taskId: 'TASK-004', + label: 'legacy claim (no claimExpiresAt), older than one lease', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - LEASE_MS - MIN), + claimExpiresAt: null, + }, + leaseState: 'lapsed', + strangerWins: true, + }, + { + taskId: 'TASK-005', + label: 'legacy claim, still inside one lease', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - 5 * MIN), + claimExpiresAt: null, + }, + leaseState: 'held', + strangerWins: false, + }, + { + taskId: 'TASK-006', + label: 'claimed with neither timestamp — unprovable, so held', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: null, + claimExpiresAt: null, + }, + leaseState: 'held', + strangerWins: false, + }, +]; + +// Terminal rows: no lease is held, so `unleased` is literally true — and the CAS +// still refuses them. This pair is the whole reason the field is not named +// `claimable`. +const TERMINAL = [ + { + taskId: 'TASK-007', label: 'done', doc: { status: 'done' }, leaseState: 'unleased', strangerWins: false, + }, + { + taskId: 'TASK-008', label: 'blocked', doc: { status: 'blocked' }, leaseState: 'unleased', strangerWins: false, + }, +]; + +const materialize = (row, num) => { + const d = row.doc; + return { + podId: mongoose.Types.ObjectId.createFromHexString(POD_ID), + taskNum: num, + taskId: row.taskId, + title: row.label, + status: d.status, + claimedBy: d.claimedBy || null, + claimedAt: typeof d.claimedAt === 'function' ? d.claimedAt() : (d.claimedAt || null), + claimExpiresAt: typeof d.claimExpiresAt === 'function' ? d.claimExpiresAt() : (d.claimExpiresAt || null), + }; +}; + +const listed = async () => { + const res = await request(app).get(`/api/v1/tasks/${POD_ID}`).set('x-test-user', 'stranger'); + expect(res.status).toBe(200); + return new Map(res.body.tasks.map((t) => [t.taskId, t])); +}; + +describe('task leaseState', () => { + beforeAll(async () => { + // eslint-disable-next-line global-require + const { MongoMemoryServer } = require('mongodb-memory-server'); + mongod = await MongoMemoryServer.create(); + await mongoose.connect(mongod.getUri()); + + app = express(); + app.use(express.json()); + app.use('/api/v1/tasks', tasksApi); + }); + + afterAll(async () => { + await mongoose.disconnect(); + if (mongod) await mongod.stop(); + }); + + beforeEach(async () => { + await Task.deleteMany({}); + await Task.create([...ROWS, ...TERMINAL].map((r, i) => materialize(r, i + 1))); + }); + + it.each([...ROWS, ...TERMINAL])('$label → leaseState $leaseState', async (row) => { + const byId = await listed(); + expect(byId.get(row.taskId).leaseState).toBe(row.leaseState); + }); + + // The differential: the field and the CAS are two expressions of one rule + // written in different shapes (a per-row projection vs a Mongo query + // predicate). Nothing but this test makes them move together. + it.each(ROWS)('$label → a stranger\'s claim agrees with leaseState', async (row) => { + const byId = await listed(); + const state = byId.get(row.taskId).leaseState; + + const res = await request(app) + .post(`/api/v1/tasks/${POD_ID}/${row.taskId}/claim`) + .set('x-test-user', 'stranger') + .send({}); + + const won = res.status === 200; + expect(won).toBe(row.strangerWins); + // For a live row the correspondence is exact in both directions. + expect(state !== 'held').toBe(won); + }); + + // `unleased` is true of the LEASE and says nothing about availability: the CAS + // refuses these rows outright. This pair is the whole reason the field is not + // named `claimable`. + it.each(TERMINAL)('$label reads unleased and is still refused', async (row) => { + const byId = await listed(); + expect(byId.get(row.taskId).leaseState).toBe('unleased'); + + const res = await request(app) + .post(`/api/v1/tasks/${POD_ID}/${row.taskId}/claim`) + .set('x-test-user', 'stranger') + .send({}); + + expect(res.status).toBe(409); + }); + + // The branch a per-row field structurally cannot carry. If someone ever reads + // `held` as "do not attempt", this is what breaks: a seat stops resuming the + // task it claimed last cycle. + it('held does not mean unclaimable — the holder renews its own live lease', async () => { + const byId = await listed(); + expect(byId.get('TASK-002').leaseState).toBe('held'); + + const res = await request(app) + .post(`/api/v1/tasks/${POD_ID}/TASK-002/claim`) + .set('x-test-user', 'holder') + .send({}); + + expect(res.status).toBe(200); + expect(res.body.task.claimedBy).toBe('holder'); + }); + + it('a rescued row returns to the pool rather than to the dead seat\'s lane', async () => { + // What theo's heartbeat performs on a lapsed row. Clearing the assignee is + // the load-bearing half: status alone sends the task back to the lane of the + // seat that died holding it, where nobody else's `assignee:` fetch + // will ever see it. + await Task.updateOne({ taskId: 'TASK-003' }, { $set: { assignee: 'deadseat' } }); + + const res = await request(app) + .patch(`/api/v1/tasks/${POD_ID}/TASK-003`) + .set('x-test-user', 'stranger') + .send({ status: 'pending', assignee: null }); + + expect(res.status).toBe(200); + expect(res.body.task.status).toBe('pending'); + expect(res.body.task.assignee).toBeNull(); + + const byId = await listed(); + expect(byId.get('TASK-003').leaseState).toBe('unleased'); + }); +}); diff --git a/backend/routes/registry/presets.ts b/backend/routes/registry/presets.ts index 3eb6c4843d..75c61e81bb 100644 --- a/backend/routes/registry/presets.ts +++ b/backend/routes/registry/presets.ts @@ -1178,13 +1178,14 @@ For each new human message describing work not already in tasks: - \`commonly_create_task(devPodId, { title, assignee, dep?, depMockOk?, source: "human" })\` - Reply: which specialist, dependency order, ONE clarifying question if ambiguous. -**Step 5: Assign unassigned tasks + auto-source from GitHub** -5a. \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "pending" })\` → for each task where assignee is null/missing, classify by title/description and \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { assignee })\`: +**Step 5: Rescue abandoned work, assign unassigned tasks + auto-source from GitHub** +5a. **Rescue first.** From the Step 2 board (no new call), take every task with \`leaseState: "lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: null })\`. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. +5b. \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "pending" })\` → for each task where assignee is null/missing, classify by title/description and \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { assignee })\`: - API/routes/services/models/tests → "nova" - UI/components/pages/CSS/frontend → "pixel" - deploy/infra/k8s/CI/Dockerfile → "ops" - Ambiguous → "nova" -5b. Sync GitHub issues to the board (run EVERY heartbeat — unconditional): +5c. Sync GitHub issues to the board (run EVERY heartbeat — unconditional): 1. \`commonly_list_github_issues(50)\` → up to 50 open issues (excludes PRs). If empty → skip to Step 6. 2. Determine assignee from labels: "backend"/API/routes/services/models/tests → "nova"; "frontend"/UI/components/pages/CSS → "pixel"; "devops"/deploy/infra/k8s/CI/Dockerfile → "ops"; ambiguous → "nova". 3. Title: if \`milestone\` is set → \`[{milestone}] GH#{number} — {title}\`, else \`GH#{number} — {title}\`. diff --git a/backend/routes/tasksApi.ts b/backend/routes/tasksApi.ts index 1609be2ef6..a61b7005e5 100644 --- a/backend/routes/tasksApi.ts +++ b/backend/routes/tasksApi.ts @@ -171,6 +171,13 @@ router.get('/:podId', auth, async (req: AuthReq, res: Res) => { // meaning what it reads as. Anything that is not a string is dropped. const assignee = typeof req.query?.assignee === 'string' ? req.query.assignee : undefined; const status = typeof req.query?.status === 'string' ? req.query.status : undefined; + // Deliberately absent from the MCP tool schema, and NOT an oversight to close. + // Agents discover work via `status=pending`; this filter is rescue/ops + // infrastructure. Exposing it teaches every seat to poll the whole board on a + // timer — the surface asymmetry IS the guard, because a tool description isn't + // one, and every other tier gap found on 2026-08-19 was an accident someone + // could mistake for policy. This is the reverse: a policy someone could + // mistake for an accident, and close by helpfully adding the param. const claimable = req.query?.claimable === 'true'; const access = await requirePodMember(podId || '', userId); if (access.error) return res.status(access.status || 500).json({ error: access.error }); @@ -183,7 +190,12 @@ router.get('/:podId', auth, async (req: AuthReq, res: Res) => { // "what can this pod's agents pick up right now", lapsed leases included. if (claimable) query.$or = claimableConditions(new Date()); const tasks = await Task.find(query).sort({ taskNum: 1 }).lean(); - return res.json({ tasks }); + // One `now` for the whole page: derived per row, two rows either side of a + // tick boundary could otherwise report lease states that never coexisted. + const now = new Date(); + return res.json({ + tasks: tasks.map((task: Record) => ({ ...task, leaseState: deriveLeaseState(task, now) })), + }); } catch (err) { console.error('GET /tasks error:', err); return res.status(500).json({ error: 'Failed to list tasks' }); @@ -396,6 +408,47 @@ export const claimableConditions = ( { status: 'claimed', claimExpiresAt: null, claimedAt: { $lt: new Date(now.getTime() - TASK_CLAIM_LEASE_MS) } }, ]; +export type TaskLeaseState = 'unleased' | 'held' | 'lapsed'; + +// `claimableConditions` above is a QUERY PREDICATE — it selects rows, and for the +// CAS it also takes the caller. It cannot LABEL a row, and a rescuer needs the +// label: theo must tell "assign this" (unleased) from "rescue this" (lapsed) in +// one pass over a board it already has. So this is a second expression of the +// same expiry rule, kept deliberately and pinned to the first by the differential +// in tasksApi.leaseState.test.js — mutate either side and that test reds. +// +// Both read one `TASK_CLAIM_LEASE_MS`. That shared constant is what makes the two +// shapes agree; the test is what proves they still do. +// +// It is deliberately NOT called `claimable`, and the difference is load-bearing. +// Claimability is a RELATION between a row and an asker: the CAS's second branch +// (`{ status: 'claimed', claimedBy }`) admits the current holder renewing its own +// lease, and no per-row field can express that — the same row is claimable by its +// holder and not by anyone else, simultaneously. So read `held` as "someone holds +// a live lease", never as "do not attempt": a seat resuming ITS OWN task must +// still call claim and will still win. Three of the CAS's four branches are +// representable here; the fourth is structurally out of reach. +// +// Combine with `status` before deciding anything. A `done` row is `unleased` +// because nobody holds a lease on it, not because it is available to work. +function deriveLeaseState( + task: { status?: string; claimedAt?: Date | string | null; claimExpiresAt?: Date | string | null }, + now: Date, +): TaskLeaseState { + if (task?.status !== 'claimed') return 'unleased'; + // Mirrors CAS branch 3 (`claimExpiresAt: { $lt: now }`), strict-less included. + if (task.claimExpiresAt) { + return new Date(task.claimExpiresAt).getTime() < now.getTime() ? 'lapsed' : 'held'; + } + // Mirrors CAS branch 4: claims that predate leases entirely carry a null + // `claimExpiresAt`, so their expiry is derived from `claimedAt` — they lapse one + // lease after they were taken, not instantly, so nobody steals work claimed two + // minutes ago during a rollout. A claimed row carrying NEITHER timestamp cannot + // be proven lapsed and the CAS refuses it too, so it reads `held`. + if (!task.claimedAt) return 'held'; + return new Date(task.claimedAt).getTime() < now.getTime() - TASK_CLAIM_LEASE_MS ? 'lapsed' : 'held'; +} + router.post('/:podId/:taskId/claim', rateLimit({ windowMs: 60_000, // Higher than task-create's 20: a claimant renews by re-claiming, and a From 485284171c5eff9bc9eb015c97db96dca0a002e8 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 02:21:17 -0700 Subject: [PATCH 2/9] test(tasks): the differential passed on a tree with no leaseState at all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three of the six differential cases went green against origin/main. With no `leaseState` on the row, `state !== 'held'` reads `undefined !== 'held'` — true — so every stranger-wins row asserted `true === true` and measured nothing. The projection tests failed and carried the suite, which is exactly how this hides: the file looks red, so nobody asks which assertions were doing the work. Assert the field is one of the three states before comparing it. 18/18 now fail against origin/main instead of 15/18. Co-Authored-By: Claude Opus 5 --- backend/__tests__/unit/routes/tasksApi.leaseState.test.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js index f0f904defc..1e2075a4b8 100644 --- a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js +++ b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js @@ -197,6 +197,10 @@ describe('task leaseState', () => { it.each(ROWS)('$label → a stranger\'s claim agrees with leaseState', async (row) => { const byId = await listed(); const state = byId.get(row.taskId).leaseState; + // Guard the guard: without this, an ABSENT field satisfies `state !== 'held'` + // and every stranger-wins row passes against a tree that has no leaseState + // at all — the assertion would be measuring undefined, not the rule. + expect(['unleased', 'held', 'lapsed']).toContain(state); const res = await request(app) .post(`/api/v1/tasks/${POD_ID}/${row.taskId}/claim`) From 69801e051b464c3b5712ecf2d6b1c498c3932d0e Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 02:24:05 -0700 Subject: [PATCH 3/9] fix(tasks): the rescue step relied on an array from three steps earlier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 5a read "the Step 2 board (no new call)". Step 2 is unscoped, so the data was right — but reusing it asks the model to still be holding an array fetched three steps and two decisions ago, which is how a step becomes a silent no-op rather than a visible failure. Fetch `{ status: "claimed" }` explicitly and filter on `leaseState`. The scope matters and is the reason the old 5a could never have been widened in place: a lapsed task's stored status IS `claimed`, so the `{ status: "pending" }` fetch at the assign step can never return one, and broadening the ownership test there would have been inert. Works with no MCP release — `status` is already on the tool's inputSchema, where `claimable` is not. Co-Authored-By: Claude Opus 5 --- backend/routes/registry/presets.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/routes/registry/presets.ts b/backend/routes/registry/presets.ts index 75c61e81bb..e6c4d87f41 100644 --- a/backend/routes/registry/presets.ts +++ b/backend/routes/registry/presets.ts @@ -1179,7 +1179,7 @@ For each new human message describing work not already in tasks: - Reply: which specialist, dependency order, ONE clarifying question if ambiguous. **Step 5: Rescue abandoned work, assign unassigned tasks + auto-source from GitHub** -5a. **Rescue first.** From the Step 2 board (no new call), take every task with \`leaseState: "lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: null })\`. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. +5a. **Rescue first.** \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "claimed" })\` → take every task whose \`leaseState\` is \`"lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: null })\`. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. Fetch it rather than reusing the Step 2 array: a lapsed task is stored as \`claimed\`, so a \`status: "pending"\` fetch can never see it, and asking yourself to still be holding an array from three steps ago is how this step quietly becomes a no-op. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. 5b. \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "pending" })\` → for each task where assignee is null/missing, classify by title/description and \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { assignee })\`: - API/routes/services/models/tests → "nova" - UI/components/pages/CSS/frontend → "pixel" From 3a2231cda6485d3114859c21e9ef93b489ce29f7 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 02:25:44 -0700 Subject: [PATCH 4/9] fix(agents): specialists worked resumed tasks without ever holding a lease MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nova/Pixel/Ops fetch `{ assignee: , status: "pending,claimed" }`, and Branch 1 explicitly covers "pending or claimed" — so a task they are resuming is already in `tasks[0]`. Step 2 then claimed it only when `status="pending"`. A resumed task reads `claimed`, so it fell through unclaimed and went straight to delegation: the work proceeded with an expired lease that nobody renewed. That was survivable while nothing acted on lapsed leases. It stops being survivable in the same release that adds a rescue sweep — a slow-but-alive seat would have its task set back to `pending` and reassigned underneath it, while it was still delegating the same task to Cody. Claim unconditionally instead and let the CAS decide. It already grants on all three of the cases a specialist can legitimately be in: unclaimed, held by the caller (renewal), or lapsed. A 409 is the only real refusal and means someone else holds it now. This deletes the stored-status test rather than widening it — the same test that made lapsed work undiscoverable at the route. Co-Authored-By: Claude Opus 5 --- backend/routes/registry/presets.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/routes/registry/presets.ts b/backend/routes/registry/presets.ts index e6c4d87f41..d3a3496d4b 100644 --- a/backend/routes/registry/presets.ts +++ b/backend/routes/registry/presets.ts @@ -1287,7 +1287,7 @@ DO NOT change the parameters. ### Branch 1 — you have a task (assignee nova, pending or claimed) 1. Take \`tasks[0]\` (\`taskId\`, \`title\`, \`description\`, \`status\`). REOPENED (\`completedAt\` set + \`status="pending"\`) → treat as fresh. Skip a task whose \`dep\` is set and not \`done\`; pick the next. -2. If \`status="pending"\` → \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. If claim fails, take the next task. +2. **Always claim before working**, whatever the status says — \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. The server decides: it grants a fresh 30-minute lease if the task is unclaimed, if you already hold it (renewal), or if the previous holder let their lease lapse. Only a 409 means someone else genuinely holds it right now — take the next task. Do NOT gate this on \`status="pending"\`: a task you are resuming reads \`claimed\`, so gating there means working it with an expired lease that nobody renews, and a rescue sweep can take it out from under you mid-delegation. 3. **Scope it, then delegate the implementation to Cody.** Write a self-contained backend spec: which files/area (backend/ — Node.js/Express/Mongoose), the API contract (endpoint path, request/response schema), auth on every endpoint + input validation, and the Jest tests expected (run from backend/). Post ONE message to DevPodId: \`@codex Please implement TASK-NNN: . <spec>. Branch off ${DEFAULT_BRANCH}, add/adjust Jest tests in backend/, run the backend test suite (cd backend && npm test), open a PR against ${DEFAULT_BRANCH}, and reply with the PR URL.\` Then \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "claimed", notes: "delegated to @codex — <one line>" })\` and record the taskId in \`## Delegated\` (JSON array). Cody (cloud-codex) is the only dev agent with a real shell. @@ -1375,7 +1375,7 @@ DO NOT change the parameters. ### Branch 1 — you have a task (assignee pixel, pending or claimed) 1. Take \`tasks[0]\` (\`taskId\`, \`title\`, \`status\`). REOPENED (\`completedAt\` set + \`status="pending"\`) → treat as fresh. Skip a task whose \`dep\` is set and not \`done\` unless \`depMockOk\` is true; pick the next. -2. If \`status="pending"\` → \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. If claim fails, take the next. +2. **Always claim before working**, whatever the status says — \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. The server decides: it grants a fresh 30-minute lease if the task is unclaimed, if you already hold it (renewal), or if the previous holder let their lease lapse. Only a 409 means someone else genuinely holds it right now — take the next task. Do NOT gate this on \`status="pending"\`: a task you are resuming reads \`claimed\`, so gating there means working it with an expired lease that nobody renews, and a rescue sweep can take it out from under you mid-delegation. 3. **Scope it, then delegate the implementation to Cody.** Write a self-contained UI spec: which files/area (frontend/src/ — React hooks, MUI, CSS-in-JS), the component behavior, WCAG 2.1 AA requirements (aria-labels, keyboard-nav, contrast), reuse of shared components, and the Jest/RTL tests expected. If Nova's API isn't ready and \`depMockOk\`, note that a mock (axios-mock-adapter) is acceptable. Post ONE message to DevPodId: \`@codex Please implement TASK-NNN: <title>. <spec>. Branch off ${DEFAULT_BRANCH}, add/adjust frontend Jest/RTL tests, run the frontend test suite (cd frontend && npm test), open a PR against ${DEFAULT_BRANCH}, and reply with the PR URL.\` Then \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "claimed", notes: "delegated to @codex — <one line>" })\` and record the taskId in \`## Delegated\`. Cody (cloud-codex) is the only dev agent with a real shell. @@ -1464,7 +1464,7 @@ DO NOT change the parameters. ### Branch 1 — you have a task (assignee ops, pending or claimed) 1. Take \`tasks[0]\` (\`taskId\`, \`title\`, \`status\`). REOPENED (\`completedAt\` set + \`status="pending"\`) → treat as fresh. Skip a task whose \`dep\` is set and not \`done\`; pick the next. -2. If \`status="pending"\` → \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. If claim fails, take the next. +2. **Always claim before working**, whatever the status says — \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. The server decides: it grants a fresh 30-minute lease if the task is unclaimed, if you already hold it (renewal), or if the previous holder let their lease lapse. Only a 409 means someone else genuinely holds it right now — take the next task. Do NOT gate this on \`status="pending"\`: a task you are resuming reads \`claimed\`, so gating there means working it with an expired lease that nobody renews, and a rescue sweep can take it out from under you mid-delegation. 3. **Scope it, then delegate the implementation to Cody.** Write a self-contained IaC spec: which files/area (k8s/, helm/, .github/workflows/, Dockerfile), the change, deployment safety (rolling/blue-green, readinessProbe), any new env var (update the Secret AND the deployment YAML together), and a rollback plan. Post ONE message to DevPodId: \`@codex Please implement TASK-NNN: <title>. <spec>. Branch off ${DEFAULT_BRANCH} as Infrastructure-as-Code (no direct kubectl/helm), open a PR against ${DEFAULT_BRANCH} with a rollback plan, and reply with the PR URL.\` Then \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "claimed", notes: "delegated to @codex — <one line>" })\` and record the taskId in \`## Delegated\`. Cody (cloud-codex) is the only dev agent with a real shell. From d108c75fa1f983358e1b5dca7776d0ce5eb16bee Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 02:31:54 -0700 Subject: [PATCH 5/9] fix(tasks): the rescue read the lease, then wrote without rechecking it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sweep period EQUALS the lease duration: theo ticks every 30m and TASK_CLAIM_LEASE_MS is 30m (tasksApi.ts:311). So a stalled-but-alive seat sits right on the boundary and gets a read-then-blind-write gamble aimed at it once per cycle, unattended, forever — low odds per tick, ~16 rolls a night, pointed squarely at the quota-stalled population. `commonly_update_task` carries no precondition: PATCH is `findOneAndUpdate({ podId, taskId }, update)` with nothing about status or lease in the filter. So a seat that renewed between theo's fetch and theo's write had its fresh lease overwritten, and two seats worked one task — the exact failure the lease exists to prevent, reintroduced by the code meant to honour it. Claim before rewriting. `commonly_claim_task` IS the compare-and-set: it grants only if the task is still unclaimed, still lapsed, or already theo's, and 409s if the holder renewed first. Theo then rewrites a task it holds the lease on. No new backend surface, no new tool, and no MCP release — the arbitration already exists, the rescue just wasn't using it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- backend/routes/registry/presets.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/routes/registry/presets.ts b/backend/routes/registry/presets.ts index d3a3496d4b..829a2725d1 100644 --- a/backend/routes/registry/presets.ts +++ b/backend/routes/registry/presets.ts @@ -1179,7 +1179,7 @@ For each new human message describing work not already in tasks: - Reply: which specialist, dependency order, ONE clarifying question if ambiguous. **Step 5: Rescue abandoned work, assign unassigned tasks + auto-source from GitHub** -5a. **Rescue first.** \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "claimed" })\` → take every task whose \`leaseState\` is \`"lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: null })\`. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. Fetch it rather than reusing the Step 2 array: a lapsed task is stored as \`claimed\`, so a \`status: "pending"\` fetch can never see it, and asking yourself to still be holding an array from three steps ago is how this step quietly becomes a no-op. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. +5a. **Rescue first.** \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "claimed" })\` → take every task whose \`leaseState\` is \`"lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each, **claim it before you rewrite it**: \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. A 409 means the holder renewed between your read and your write — that seat is alive, so leave the task alone and move on. Only once the claim succeeds: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: null })\`. The claim is the interlock, and it is load-bearing because your sweep period EQUALS the lease: you run every 30 minutes and a lease lasts 30 minutes, so a read-then-write with no precondition gambles against a stalled-but-alive seat on every single cycle, unattended, forever. \`commonly_update_task\` has no precondition; \`commonly_claim_task\` is a compare-and-set. Let the server arbitrate rather than your snapshot. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. Fetch it rather than reusing the Step 2 array: a lapsed task is stored as \`claimed\`, so a \`status: "pending"\` fetch can never see it, and asking yourself to still be holding an array from three steps ago is how this step quietly becomes a no-op. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. 5b. \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "pending" })\` → for each task where assignee is null/missing, classify by title/description and \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { assignee })\`: - API/routes/services/models/tests → "nova" - UI/components/pages/CSS/frontend → "pixel" From 2b0dba5a6a36dcfd365ae3925d8c74af25aed7e4 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 02:35:24 -0700 Subject: [PATCH 6/9] fix(tasks): the rescue told a moltbot to send a value its tool cannot express MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rescue clause said `commonly_update_task(..., { assignee: null })`. On the openclaw surface theo actually runs, that tool types `assignee` as a plain string and documents "empty string to unassign" — a moltbot cannot send null at all. So the clause was unrunnable by the only seat meant to run it. The obvious repair is worse than the bug: `assignee: ""` validates, and lands in Mongo as `''`. The classify-and-assign step triggers on "assignee is null/missing", and `''` is neither — so a rescued task would sit unassigned- looking, permanently skipped, in a lane no seat fetches. Rescued out of one hole into a quieter one. Normalise blank to null at the PATCH gate so both spellings converge, and send the sentinel the moltbot tool documents. Two tests, one per caller shape; the null case passes on main (already worked), the `''` case is the new behaviour. Checked the running gateway rather than the recipe for all three tools this clause touches: get_tasks returns the backend rows verbatim (its field list is documentation, not a projection, so `leaseState` reaches theo), claim_task exists so the interlock is reachable, and update_task PATCHes fields — while the MCP server's tool of the SAME NAME only appends a note. One name, two verbs, two tiers. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- .../unit/routes/tasksApi.leaseState.test.js | 15 +++++++++++++++ backend/routes/registry/presets.ts | 2 +- backend/routes/tasksApi.ts | 11 +++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js index 1e2075a4b8..7e9a47c8ca 100644 --- a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js +++ b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js @@ -244,6 +244,21 @@ describe('task leaseState', () => { expect(res.body.task.claimedBy).toBe('holder'); }); + // The openclaw tool types `assignee` as a plain string and documents "empty + // string to unassign", so a moltbot cannot send null. Stored verbatim, '' is + // neither null nor missing, and the assign step skips the row forever. + it.each([[null, 'an MCP/HTTP caller'], ['', 'a moltbot']])('unassign via %p (%s) lands as null', async (value) => { + await Task.updateOne({ taskId: 'TASK-003' }, { $set: { assignee: 'deadseat' } }); + + const res = await request(app) + .patch(`/api/v1/tasks/${POD_ID}/TASK-003`) + .set('x-test-user', 'stranger') + .send({ status: 'pending', assignee: value }); + + expect(res.status).toBe(200); + expect(res.body.task.assignee).toBeNull(); + }); + it('a rescued row returns to the pool rather than to the dead seat\'s lane', async () => { // What theo's heartbeat performs on a lapsed row. Clearing the assignee is // the load-bearing half: status alone sends the task back to the lane of the diff --git a/backend/routes/registry/presets.ts b/backend/routes/registry/presets.ts index 829a2725d1..8268b2b477 100644 --- a/backend/routes/registry/presets.ts +++ b/backend/routes/registry/presets.ts @@ -1179,7 +1179,7 @@ For each new human message describing work not already in tasks: - Reply: which specialist, dependency order, ONE clarifying question if ambiguous. **Step 5: Rescue abandoned work, assign unassigned tasks + auto-source from GitHub** -5a. **Rescue first.** \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "claimed" })\` → take every task whose \`leaseState\` is \`"lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each, **claim it before you rewrite it**: \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. A 409 means the holder renewed between your read and your write — that seat is alive, so leave the task alone and move on. Only once the claim succeeds: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: null })\`. The claim is the interlock, and it is load-bearing because your sweep period EQUALS the lease: you run every 30 minutes and a lease lasts 30 minutes, so a read-then-write with no precondition gambles against a stalled-but-alive seat on every single cycle, unattended, forever. \`commonly_update_task\` has no precondition; \`commonly_claim_task\` is a compare-and-set. Let the server arbitrate rather than your snapshot. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. Fetch it rather than reusing the Step 2 array: a lapsed task is stored as \`claimed\`, so a \`status: "pending"\` fetch can never see it, and asking yourself to still be holding an array from three steps ago is how this step quietly becomes a no-op. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. +5a. **Rescue first.** \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "claimed" })\` → take every task whose \`leaseState\` is \`"lapsed"\` — its claimant's 30-minute lease ran out, so the seat holding it died or stalled. For each, **claim it before you rewrite it**: \`commonly_claim_task("69b7ddff0ce64c9648365fc4", taskId)\`. A 409 means the holder renewed between your read and your write — that seat is alive, so leave the task alone and move on. Only once the claim succeeds: \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { status: "pending", assignee: "" })\`. The claim is the interlock, and it is load-bearing because your sweep period EQUALS the lease: you run every 30 minutes and a lease lasts 30 minutes, so a read-then-write with no precondition gambles against a stalled-but-alive seat on every single cycle, unattended, forever. \`commonly_update_task\` has no precondition; \`commonly_claim_task\` is a compare-and-set. Let the server arbitrate rather than your snapshot. Clearing the assignee is NOT optional — \`status\` alone returns the task to the lane of the seat that died holding it, where no other seat's assignee-scoped fetch will ever see it. Nulling it hands the task to 5b below, which reassigns it on this same tick. Never touch \`leaseState: "held"\`: that is a live claim, possibly someone mid-work. Fetch it rather than reusing the Step 2 array: a lapsed task is stored as \`claimed\`, so a \`status: "pending"\` fetch can never see it, and asking yourself to still be holding an array from three steps ago is how this step quietly becomes a no-op. You are the only seat that reads the whole board, so if you skip this nobody else rescues it. 5b. \`commonly_get_tasks("69b7ddff0ce64c9648365fc4", { status: "pending" })\` → for each task where assignee is null/missing, classify by title/description and \`commonly_update_task("69b7ddff0ce64c9648365fc4", taskId, { assignee })\`: - API/routes/services/models/tests → "nova" - UI/components/pages/CSS/frontend → "pixel" diff --git a/backend/routes/tasksApi.ts b/backend/routes/tasksApi.ts index a61b7005e5..a7b6468780 100644 --- a/backend/routes/tasksApi.ts +++ b/backend/routes/tasksApi.ts @@ -618,6 +618,17 @@ router.patch('/:podId/:taskId', taskWriteRateLimit(60), auth, async (req: AuthRe const fieldUpdates: Record<string, unknown> = {}; const body = (req.body || {}) as Record<string, unknown>; allowed.forEach((k) => { if (body[k] !== undefined) fieldUpdates[k] = body[k]; }); + // Unassign has two spellings and only one of them was reaching the DB. The + // openclaw tool types `assignee` as a plain string and documents "empty string + // to unassign", so a moltbot literally cannot send null; an MCP or HTTP caller + // sends null. Stored as '', the row is neither null NOR missing, so theo's + // classify-and-assign step — whose trigger is exactly "assignee is null/missing" + // — skips it forever, and a rescued task lands in a lane no seat fetches. One + // normalisation here beats teaching every caller which spelling this backend + // happens to accept. + if (typeof fieldUpdates.assignee === 'string' && fieldUpdates.assignee.trim() === '') { + fieldUpdates.assignee = null; + } if (Object.keys(fieldUpdates).length === 0) return res.status(400).json({ error: 'No updatable fields provided' }); if (fieldUpdates.status !== undefined) { const raw = String(fieldUpdates.status).trim().toLowerCase(); From 2fcee7af66b3304357d6a130cb09cc7230697594 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 03:11:08 -0700 Subject: [PATCH 7/9] test(tasks): near-edge lease rows, and an honest note on what they miss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The matrix jumped from hours-inside to hours-outside the lease, so a wrong constant or a unit error had a wide corridor to hide in. Four rows seconds either side of both the `claimExpiresAt` and the legacy `claimedAt` edge close it, on both the field and the CAS via the differential. The comment they shipped with claimed more. It said strict-vs-inclusive drift was what they caught — so I mutated the field's `<` to `<=` and all 28 stayed green. The two differ only at exact equality, and nothing here is exactly equal; worse, that case is unreachable through this surface at all, because the route generates its own `now` inside the request and no fixture can land on it. Comment now says what the rows cover and what they cannot, because a row labelled "boundary" reads as covering the boundary. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- .../unit/routes/tasksApi.leaseState.test.js | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js index 7e9a47c8ca..a02393cef4 100644 --- a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js +++ b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js @@ -130,6 +130,63 @@ const ROWS = [ leaseState: 'held', strangerWins: false, }, + // Near-edge rows: seconds either side of the lease, where the extremes above are + // hours. They catch a sign flip, a wrong constant, or a unit error. + // + // They do NOT catch strict-vs-inclusive. Mutating the field's `<` to `<=` leaves + // all 28 green, because the two differ only at exact equality and nothing here is + // exactly equal. That case is unreachable through this surface at all: the route + // generates its own `now` inside the request, so a test cannot place a timestamp + // on it. Stated rather than implied — a row labelled 'boundary' reads as covering + // the boundary, and this one covers its neighbourhood. + { + taskId: 'TASK-009', + label: 'lease expires in 5s — inside the edge', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - 25 * MIN), + claimExpiresAt: () => new Date(Date.now() + 5000), + }, + leaseState: 'held', + strangerWins: false, + }, + { + taskId: 'TASK-010', + label: 'lease expired 2s ago — just outside', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - 30 * MIN - 2000), + claimExpiresAt: () => new Date(Date.now() - 2000), + }, + leaseState: 'lapsed', + strangerWins: true, + }, + { + taskId: 'TASK-011', + label: 'legacy claim 5s short of one lease — inside the edge', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - LEASE_MS + 5000), + claimExpiresAt: null, + }, + leaseState: 'held', + strangerWins: false, + }, + { + taskId: 'TASK-012', + label: 'legacy claim 2s past one lease — just outside', + doc: { + status: 'claimed', + claimedBy: 'holder', + claimedAt: () => new Date(Date.now() - LEASE_MS - 2000), + claimExpiresAt: null, + }, + leaseState: 'lapsed', + strangerWins: true, + }, ]; // Terminal rows: no lease is held, so `unleased` is literally true — and the CAS From c8f6576fbb343f45c861326641c7e5c27307a1c1 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 03:22:05 -0700 Subject: [PATCH 8/9] chore(tasks): drop the duplicate MCP-omission comment, #1026 owns it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I carried this comment into #1023 when it did not survive #1022's merge. It now has a dedicated PR, so two copies would land — and a policy stated twice is a policy that can be edited in one place and left stale in the other, which is the failure this comment exists to prevent. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- backend/routes/tasksApi.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/backend/routes/tasksApi.ts b/backend/routes/tasksApi.ts index a7b6468780..bcc7231be6 100644 --- a/backend/routes/tasksApi.ts +++ b/backend/routes/tasksApi.ts @@ -171,13 +171,6 @@ router.get('/:podId', auth, async (req: AuthReq, res: Res) => { // meaning what it reads as. Anything that is not a string is dropped. const assignee = typeof req.query?.assignee === 'string' ? req.query.assignee : undefined; const status = typeof req.query?.status === 'string' ? req.query.status : undefined; - // Deliberately absent from the MCP tool schema, and NOT an oversight to close. - // Agents discover work via `status=pending`; this filter is rescue/ops - // infrastructure. Exposing it teaches every seat to poll the whole board on a - // timer — the surface asymmetry IS the guard, because a tool description isn't - // one, and every other tier gap found on 2026-08-19 was an accident someone - // could mistake for policy. This is the reverse: a policy someone could - // mistake for an accident, and close by helpfully adding the param. const claimable = req.query?.claimable === 'true'; const access = await requirePodMember(podId || '', userId); if (access.error) return res.status(access.status || 500).json({ error: access.error }); From 29d49c8a1375a4162a0a04190be2ee924dcca0d4 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Wed, 19 Aug 2026 03:28:46 -0700 Subject: [PATCH 9/9] test(tasks): pin the status split the rescue and assign steps depend on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit theo's rescue asks for `{ status: "claimed" }` and its assign step asks for `{ status: "pending" }`. That split is only correct while a lapsed row is INVISIBLE to the pending fetch — which is the original defect, preserved on purpose because `leaseState` is what makes it discoverable instead. Nothing said so. A later change making `?status=pending` include lapsed rows would look like a fix, and would silently make the rescue step double-handle every row it had just written. Now one test asserts both halves: TASK-003 is absent from the pending fetch and present under the claimed fetch carrying `leaseState: 'lapsed'`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --- .../unit/routes/tasksApi.leaseState.test.js | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js index a02393cef4..b2707eceac 100644 --- a/backend/__tests__/unit/routes/tasksApi.leaseState.test.js +++ b/backend/__tests__/unit/routes/tasksApi.leaseState.test.js @@ -285,6 +285,32 @@ describe('task leaseState', () => { expect(res.status).toBe(409); }); + // The two-fetch shape theo depends on, pinned. Rescue asks for + // `{ status: 'claimed' }` and assign asks for `{ status: 'pending' }`, and that + // split is only correct while a lapsed row is INVISIBLE to the pending fetch — + // which is the original defect, deliberately preserved. If someone later + // fixes `?status=pending` to include lapsed rows, the rescue step starts + // double-handling every row it just wrote and this test says so. + it('a lapsed row is absent from ?status=pending and present under ?status=claimed', async () => { + const pending = await request(app) + .get(`/api/v1/tasks/${POD_ID}`) + .query({ status: 'pending' }) + .set('x-test-user', 'stranger'); + expect(pending.status).toBe(200); + const pendingIds = pending.body.tasks.map((t) => t.taskId); + expect(pendingIds).toContain('TASK-001'); + expect(pendingIds).not.toContain('TASK-003'); + + const claimed = await request(app) + .get(`/api/v1/tasks/${POD_ID}`) + .query({ status: 'claimed' }) + .set('x-test-user', 'stranger'); + expect(claimed.status).toBe(200); + const lapsed = claimed.body.tasks.find((t) => t.taskId === 'TASK-003'); + expect(lapsed).toBeDefined(); + expect(lapsed.leaseState).toBe('lapsed'); + }); + // The branch a per-row field structurally cannot carry. If someone ever reads // `held` as "do not attempt", this is what breaks: a seat stops resuming the // task it claimed last cycle.