Skip to content

feat(tasks): a lapsed lease was claimable and unfindable at the same time - #1023

Merged
lilyshen0722 merged 9 commits into
mainfrom
feat/task-lease-state-and-rescue
Aug 19, 2026
Merged

lilyshen0722 merged 9 commits into
mainfrom
feat/task-lease-state-and-rescue

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

The gap

ADR-018 D4 made a task claim a lease, and the claim route honours it — one CAS, four ways to win, two of which recognise an expired hold (tasksApi.ts:340-347). The list route never learned about any of it: GET /:podId filters on stored status alone (:126).

So a lapsed task is claimable and unfindable at the same time. The CAS would grant it today; nothing returns it from a list. And claim takes a taskId — it never scans — so the only seat that can reach a lapsed row is the one that already knows its id, which is the seat that died holding it.

There is no reaper. git grep claimExpiresAt origin/main -- backend cli packages returns the model, the CAS, and the 409 body. A lapsed claim stays claimed forever.

Three live heartbeat presets already fetch these rows and throw them away: :1279 passes status: "pending,claimed", and :1289 is If `status="pending"` → claim. Same stored-status test, one layer up in prompt text.

Two halves

1. 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 is derived from claimedAt. One now per page, so two rows can't report lease states that never coexisted.

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. Three of the four branches are representable here; the fourth is structurally out of reach. A reader that treats held as "do not attempt" stops a seat from resuming its own task — there's a test pinning exactly that.

unleased is likewise a fact about the lease, not about availability: a done row is unleased because nobody holds a lease on it. Combine with status.

2. 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 — no new call, no new scanner, no new tool.

It writes { status: 'pending', assignee: null }. Clearing the assignee is the load-bearing half: 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 straight into the existing classify-and-assign loop on the same tick — so nova/pixel/ops need no edit at all, and the :1289 stored-status test stops mattering because the row is normalised upstream of it.

Tests

Real in-memory Mongo, so the CAS's $or is evaluated by Mongo rather than by a second copy of the predicate written in the test. 18 tests: the full lease matrix (live, expired, legacy-lapsed, legacy-live, neither-timestamp, terminal), the differential against a stranger's claim, self-renewal on a held row, and the rescue write.

Mutation-tested both directions:

  • Drop the field's legacy branch → 2 tests fail.
  • Drift the CAS instead (remove its fourth branch, leave the field intact) → only the differential fails. That's what it's there for.

Not covered / caveats

  • This needs reprovision-all to reach agents. theo's live HEARTBEAT.md on the PVC is dated Aug 5 — editing presets.ts changes nothing until someone runs it. Merging alone leaves the rescue inert.
  • theo becomes the single rescuer, so theo's own death is still unrecovered. That's the Dead-letter gap: an outage >~45min permanently discards queued agent work, silently #998 population, not something this PR closes.
  • Local npm test cannot run three route suites on Node 26 (jsonwebtoken fails at import); CI pins Node 20. 107 tests passed locally with 0 failures, plus the 18 new ones.

🤖 Generated with Claude Code


Three routes into one failure — patching one does not close the class

Every commit after the first fixed a different mechanism landing a rescued task in the same place: reachable by nobody. Recording them because a reader who patches one will reasonably assume the class is handled.

  1. status-only rescue. assignee survives the write, so the task returns to the lane of the seat that died holding it. No other seat's assignee-scoped fetch contains it.
  2. The assign step skips anything already assigned. Its trigger is "assignee is null/missing", so a rescued-but-still-assigned row is passed over on every subsequent tick.
  3. assignee: "" stored verbatim. The moltbot tool cannot send null (it types assignee as a string, documented "empty string to unassign"), and '' is neither null nor missing — so route 2 swallows it again, one layer down.

They share a destination and nothing else: a row that exists, reads as available, and is in no seat's fetch. The invariant worth holding on any future change here is "after a rescue, some specific seat's ordinary fetch returns this row" — not "the write succeeded", which was true in all three cases.

A fourth is deliberately still open and belongs to a different fix: a row whose assignee is a retired seat name is unreachable even when everything above is correct, because no live seat fetches that lane. Only theo's whole-board sweep reaches it, and nothing reaches theo's own.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Reviewed. The design lands the three things I'd have asked for — rescue-first via status: "claimed" (reachable through today's tool surface, no extension release needed), the explicit assignee nulling with its rationale, and always-claim in all three specialist presets so the CAS arbitrates instead of prompt text.

The differential at :194-209 is better than I would have specified. I grepped for a cross-check between deriveLeaseState and the CAS, got zero hits, and was about to file "the two copies are never compared" — the zero was my regex, not your test. It also guards against an absent leaseState satisfying the assertion vacuously, which is the failure mode that would have made it decorative.

One blocker: the PATCH has no CAS, and 5a now writes through it every 30 minutes

tasksApi.ts:509 still matches on podId + taskId alone and blindly $sets. That was latent before; 5a turns it into a scheduled operation.

Failure sequence:

  1. theo fetches lapsed rows at T
  2. a stalled claimant resumes and renews its lease through the CAS at T+ε — legitimately, since renewal is a supported branch
  3. theo's write lands at T+δ with { status: "pending", assignee: null }

The live lease is destroyed and the lane is cleared, then 5b reassigns the task on the same tick. Two seats then believe they own it — worse than not rescuing, because the row now reads as cleanly owned by the wrong seat.

The window is not milliseconds: 5a fetches all lapsed rows and then updates them in turn, so the Nth write carries the accumulated gap of the N−1 before it. And the trigger population is exactly the quota-stalled-then-resumed seat, which is what the fleet did repeatedly last night.

Fix shape

A blanket CAS on PATCH would break normal edits, which must keep working on held tasks. A precondition is narrower: something like expectLeaseLapsed: true in the body that ANDs claimableConditions(now) into the findOneAndUpdate match. A rescue arriving after a renewal then matches nothing and no-ops, and every other PATCH is unaffected.

That is small once #1022 exports the predicate — and it keeps the rule in one place rather than adding a third expression of it.

Coordination

#1023 conflicts with #1022 (both edit the list handler in tasksApi.ts). #1020 is merging first by agreement, so the order is #1020 → #1022 → #1023, or say if you'd rather #1023 went ahead of #1022 and I'll rebase onto it instead.

@samxu01
samxu01 force-pushed the feat/task-lease-state-and-rescue branch from baa41cf to 0f9d7b7 Compare August 19, 2026 10:08
samxu01 pushed a commit that referenced this pull request Aug 19, 2026
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>
lilyshen0722 and others added 8 commits August 19, 2026 03:23
…time

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…lease

Nova/Pixel/Ops fetch `{ assignee: <self>, 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 <noreply@anthropic.com>
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>
… express

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>
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>
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>
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>
@lilyshen0722
lilyshen0722 merged commit 8398c3a into main Aug 19, 2026
12 checks passed
@lilyshen0722
lilyshen0722 deleted the feat/task-lease-state-and-rescue branch August 19, 2026 10:41
lilyshen0722 added a commit that referenced this pull request Aug 19, 2026
Rebuilt on top of current main rather than replayed from the reverted branch:
that copy predated #1022's query coercion and #1023's leaseState, and pushing
it would have silently reverted both.

notifyAgents guards with try/catch AND .catch. A promise .catch cannot cover
the call throwing synchronously, which is what happens when notifyPodAgents is
undefined — and that turned every board write into a 500, strictly worse than
the silent fan-out this fixes.
lilyshen0722 added a commit that referenced this pull request Aug 19, 2026
…4 D1, re-land) (#1030)

* feat(kernel): board changes reach agents, bounded on DELIVERY (ADR-024 D1)

Re-lands D1 after #1029 reverted it. The reverted version bounded the wrong
thing: a synthetic claim key deduped ACTION, so one agent acted while every
opted-in seat still woke. sprint-review put a number on it — 39 board writes
across 5 seats is 156 wakes, every seat hits the cascade cap of 3 within
seconds, and D1 silences the fleet it exists to inform.

The bound is now on delivery: at most one PENDING board wake per (agent,
instance, pod). A second change folds into the undrained first instead of
appending. 39 writes become 1 wake; each seat looks at the board once rather
than once per row.

No messageId, deliberately — every seat SHOULD look, and the per-task claim
CAS already arbitrates who takes what one layer down, where the contention
actually is.

Folds match on payload.boardWake, never on event type: board wakes ride
message.posted alongside ordinary chat, and folding on type would collapse a
board change into an unread message and destroy it.

A human edit landing on agent churn re-prices the batch as user-agent, so one
early agent write cannot permanently mark a wake the human later contributed
to.

Residual stated in code rather than hidden: the fold is a findOneAndUpdate, so
two writes in the same instant can both miss. The bound is 'roughly one', never
the 39 it replaces.

* refactor: export wakeOnMessageEnabled so D1 gates on it instead of copying it

The config is a Mongoose Map on some paths and a plain object on others —
exactly the detail a second copy gets subtly wrong.

* feat(tasks): wire the six board-write sites to the coalesced fan-out

Rebuilt on top of current main rather than replayed from the reverted branch:
that copy predated #1022's query coercion and #1023's leaseState, and pushing
it would have silently reverted both.

notifyAgents guards with try/catch AND .catch. A promise .catch cannot cover
the call throwing synchronously, which is what happens when notifyPodAgents is
undefined — and that turned every board write into a 500, strictly worse than
the silent fan-out this fixes.

* test: pin the delivery bound, the fold key, and the actor pricing

Covers what the reverted version got wrong: folds into an undrained wake,
matches on boardWake rather than type, carries no messageId, and re-prices a
folded batch when a human edit lands on agent churn.

Also keeps the two bugs the first round caught — the self-skip keyed on
installedBy (which holds the agent's id on self-install and the HUMAN's on
human-install, silencing every agent for its own installer), and the require
pointing at a models path that does not exist.

* test: cover the wiring, where this fails invisibly

A board write that reaches Socket.io and skips the fan-out still 200s, still
updates the Kanban, and only the agents learn nothing. Includes the
synchronous-throw case, which a rejection guard does not catch.

* fix(kernel): key the self-skip on identity, not installedBy

pod-architect on review: a HUMAN-installed agent editing the board does not
match its installer's id, so it fails to skip and wakes ITSELF.

installedBy has now produced a bug from both directions. It holds the agent's
own user id on a self-install and the HUMAN's id on a human-install. Comparing
it against any actor silenced every agent for its own installer — the person
most likely to be moving tasks. Scoping that comparison to agent actors fixed
the human case and left the mirror image intact.

(agentName, instanceId) identifies the acting agent under BOTH install paths,
which is what this skip has always meant. Normalised the way
AgentInstallation stores them — lowercased name, 'default' for a missing
instance — so a case difference cannot quietly reintroduce the self-wake.

* fix(tasks): actorOf carries agent identity, not just a user id

The self-skip downstream needs (agentName, instanceId). Both auth shapes carry
the same metadata: agentRuntimeAuth sets req.agentUser, the dual-auth path
leaves the bot on req.user.

* test: the human-installed self-wake, and the sibling it must NOT suppress

Three cases the previous suite could not distinguish, because it only ever
exercised a self-installed actor:
- a human-installed agent editing the board skips itself
- the match is case-insensitive
- a DIFFERENT instance of the same agent name is still woken, so a per-user
  fan-out agent (scout has 115 identities) does not silence its own siblings
lilyshen0722 added a commit that referenced this pull request Aug 21, 2026
…ce (#1080) (#1082)

Implements fable-lead's ruling in full (pod message 56210), which named
this the spec for #1080.

Part 1 — renewal derives from work. A holder-authored task update now
renews the lease. @sprint-review measured the gap on TASK-015: a progress
note at 09:27:30 did not stop a 09:51:11 lapse, so the one signal a working
holder naturally produces was exactly the one the lease ignored. Holder
match is evaluated server-side in the findOneAndUpdate filter, never from a
snapshot; a peer's note is recorded and does not renew, or any passing agent
could keep a dead seat's claim alive forever. The note lands on both paths —
gating the lease must never gate the audit trail.

Part 2 — the rescue consults deriveAgentState. A lapsed lease held by a
provably live seat is deferred one sweep period and the holder warned, at
most three times, then rescued anyway. Deferral does NOT extend the lease:
the row stays claimable by peers throughout, so this suppresses the kernel's
rescue and not the board. Liveness isn't tenure.

Only 'listening' counts as live, and that is a reading of the ruling rather
than a quote from it. deriveAgentState returns five states and only that one
is backed by evidence (a BYO/wrapper seat polls every ~5s, so lastUsedAt is
a measurement). 'reachable' is asserted by construction for native and
push-webhook installs, and 'unknown' is the gateway tier declining to answer;
deferring on either would grant tenure to a class nobody checked. Both rescue
as today. This fixes all three cases named in the pod — TASK-008, TASK-029
and TASK-015 are wrapper seats and derive 'listening'.

Part 3 — provenance always. The rescue writes the prior holder into
lapsedFrom and names them in the audit trail, and the found-work wake renders
"lapsed from X — check their work before starting". Clearing assignee and
claimedBy is what makes a rescued row findable again (#1023) and also what
erased the only record of ownership: TASK-015 was advertised as unclaimed
while its work sat in open PR #1078, and two reviewers independently
hand-warned the room within one minute of each other.

Tests: 30 across two suites, every new assertion mutation-probed red with
the mutation verified applied first. Two probes compiled to "Tests: 0 total"
rather than failing — a suite that cannot load reads identically to one that
passes if you only check that the number moved.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant