Skip to content

feat(claims): kernel CAS, lease, and runtime routes (ADR-018 slices 1–2) - #892

Merged
lilyshen0722 merged 4 commits into
mainfrom
feat/claim-lease-kernel
Aug 11, 2026
Merged

lilyshen0722 merged 4 commits into
mainfrom
feat/claim-lease-kernel

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

First two implementation slices of the ratified ADR-018, prioritized by Sam
over the guide agent: agents cannot work effectively while contention is
resolved socially (two agents on one message 39 seconds apart, then messages
reconciling who did what).

Slice 1 — the CAS the design hangs on

One table, one statement: INSERT … ON CONFLICT DO UPDATE … WHERE the lease
is expired or the caller already holds it, RETURNING. Exactly one
concurrent winner; renewal is the same call as claiming; losers learn who
holds the lease and until when, so drivers stand down informed. Leases default
90s, clamped at 600. Release is holder-only and a miss is a result, not an
error — claim-then-decline is a normal path (D6).

Recorded deviation from the ADR sketch: claims live in a dedicated
self-bootstrapping table keyed by message id (vectorSearchService precedent)
rather than as columns on messages — same ownership semantics, no ALTER on
the hottest table in the system.

Slice 2 — the runtime surface

POST /api/agents/runtime/messages/:id/claim (claim-or-renew) and DELETE
(release). Identity from the token, lowercased at the boundary; membership
gated exactly as posting is (active AgentInstallation), so claiming grants no
authority anywhere the agent couldn't already act. The kernel never refuses an
unclaimed post (D3) — that's the #887 lesson, kept.

Tests

Six at the SQL boundary (one-winner, renewal, informed loss, lease clamp,
holder-only release, expiry-as-absence) + four at the route (identity,
403-without-install, 400-without-pod, release). Typecheck clean.

Not in this PR

commonly_claim_message MCP tool (ships as npm 0.3.0), wrapper
claim-before-act with stand-down, claimExpiresAt backfill on tasks (the
existing forever-claim bug), typing-indicator wiring (D7).

lilyshen0722 and others added 2 commits August 11, 2026 12:32
Sam ratified ADR-018 and prioritized claims over the guide agent — agents
cannot work effectively while contention is resolved socially (two agents on
one message 39s apart, narrating reconciliation afterwards).

One table, one CAS statement: INSERT ... ON CONFLICT DO UPDATE ... WHERE the
existing lease is expired OR the caller already holds it, RETURNING. Exactly
one concurrent caller gets a row; renewal is the same call as claiming
(a holder wins against itself); losers are told who holds the lease and until
when, so drivers stand down informed rather than blind.

Leases default 90s, clamped at 600 — nobody parks a claim for an hour by
passing a big number. Expired leases read as unheld everywhere. Release is
holder-only and a miss is a result, not an error, because claim-then-decline
is a normal path (D6) and the lease may have been re-won mid-decision.

Recorded deviation from the ADR's sketch: claim state lives in a dedicated
table KEYED by message id rather than on the messages row — that table is the
hottest in the system, has no in-repo DDL to migrate, and vectorSearchService
already sets the self-bootstrapping-table precedent. Same ownership
semantics, no ALTER.

The kernel never refuses an unclaimed post (D3) — this service only answers
who holds the lease. Six tests at the SQL boundary.

Next slices: runtime route, commonly_claim_message MCP tool, wrapper
stand-down, claimExpiresAt backfill on tasks.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8
…ice 2)

POST /messages/:id/claim and DELETE /messages/:id/claim on the agent runtime
surface. Identity comes from the token (agentRuntimeAuth), lowercased at the
boundary — one identity casing, the #804 lesson. Membership is gated the same
way posting is: an active AgentInstallation in the pod, so an agent cannot
claim its way into rooms it is not in. The kernel still never refuses an
unclaimed post; these routes only arbitrate the lease.

One route serves claim AND renew because the CAS lets a holder win against
itself — drivers need one call, not a state machine.

Four route tests. Next: commonly_claim_message MCP tool (npm 0.3.0), wrapper
stand-down, task claimExpiresAt backfill.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8
Comment thread backend/routes/agentsRuntime.ts Fixed
Comment thread backend/routes/agentsRuntime.ts Fixed
Comment thread backend/routes/agentsRuntime.ts Fixed
lilyshen0722 and others added 2 commits August 11, 2026 12:44
…lice 3)

Two tools, not one with a mode flag: each is one HTTP call (Invariant #1).
The claim description carries the driver contract inline where the model
reads it — STAND DOWN on loss, renew by re-calling, claim is the right to
decide not a duty to reply, chain affinity included. Release-miss is a
result, not an error, because claim-then-decline is the normal path.

Minor bump per Sam's sign-off: new capability, and the wrapper's coming
claim-before-act behaviour gets a clean version gate (tool present >= 0.3.0).

49 tests pass, including two pinning the stand-down and decline contracts.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8
Same-file phase4RateLimit on both routes, which is the pattern this file
already documents: CodeQL's js/missing-rate-limiting only recognizes direct
express-rate-limit invocations in the file where the route registers.
Claims renew on a cadence, so a limiter is correct here anyway, not just
scanner appeasement. Route tests still pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8
Comment thread backend/routes/agentsRuntime.ts Dismissed
Comment thread backend/routes/agentsRuntime.ts Dismissed
@lilyshen0722
lilyshen0722 merged commit 2e8d0e4 into main Aug 11, 2026
12 checks passed
@lilyshen0722
lilyshen0722 deleted the feat/claim-lease-kernel branch August 11, 2026 20:02
lilyshen0722 added a commit that referenced this pull request Aug 12, 2026
…cade cap, length gate (ADR-018 D3) (#894)

The 2026-08-11 pilot showed advisory guidance does not bind: the tone
contract sat in every seat's tool descriptions and the fleet still posted
a 3,614-char median, took zero claims, and ran a mention cascade until a
wrapper was killed by hand. The run loop now enforces what the contract
could only ask:

- claim-before-act on message-bearing events (kernel CAS from #892);
  losers stand down acked, holder death is covered by the holder's own
  unacked event
- lease renewal at half-life; a claim lost mid-turn suppresses the
  wrapper post instead of recreating the two-agents-one-message crossing
- per-pod cap (3) on consecutive agent-triggered turns, reset by a human
  turn or 10 quiet minutes; admit/record split so redelivered failures
  never double-count
- post-time length gate: split at fences/paragraphs/sentences up to 3
  messages, attach the full text as a file beyond that — never truncate

Every enforcement failure fails open (#887 rule): a kernel without the
claim route or an unreachable upload endpoint logs and proceeds unguarded.


Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8

Co-authored-by: Claude Fable 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 12, 2026
Per-install opt-in (config.wakeOnMessage.enabled === true, default off,
revertible). On every message post, opted-in installs in the pod are woken
with a message.posted event; the claim layer (#892 kernel, #894 wrapper)
arbitrates who acts — all wake, one acts, and with claim-before-act the CAS
losers never even spawn.

The fan-out is deliberately dumb and cheap: zero opt-ins costs nothing
beyond the installations array the mention path already loads. Guards:
sender's own identity never wakes on its own post; mention-enqueued targets
are excluded (the mention is the stronger cue — double delivery would burn
a second model turn on one trigger); DM-shaped pods are excluded
(enqueueDmEvent already routes every message there); and bot-authored wake
storms are dampened on the message.posted count with #508's window and
threshold. Human-authored messages are never dampened.

The inline frame tells the woken agent it was NOT named, that silence is
the default, and that acting starts with a claim — payload.content, not
metadata, per the inline-cue rule. message.posted is already in the CLI
wrapper's prompt and claimable sets, so deployed wrappers hear this with no
driver change (D5).


Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8

Co-authored-by: Claude Fable 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 12, 2026
* feat(tasks): task claims are leases — ADR-018 D4 backfill

claimedBy had no deadline: a dead claimant (closed laptop, killed wrapper)
held a task forever, invisibly. Message claims shipped with a lease (#892)
precisely to avoid this, which left two claim primitives with different
liveness rules — the gap D4 names.

The claim route now stamps claimExpiresAt (30 min — matches the pod's
claim-the-orphan convention of racing on work stalled ~30 min) and the CAS
admits four winners: unclaimed, the holder itself (renewal, same-call
semantics as messageClaimService), a lapsed lease, or a LEGACY claim
(claimExpiresAt null) whose claimedAt is older than one lease — legacy
rows derive their effective expiry from claimedAt, so there is no
migration and no instant steal of recently-claimed work. The 409 now
names the holder AND when the lease frees (D3: losers stand down
informed, not blind).

commonly_claim_task's description (unpublished 0.3.0) carries the lease
contract in the same falsifiable style as the tone contract.

Service-tier tests cover all six behaviors. NOT verified locally: Node 26
removed SlowBuffer, which breaks jsonwebtoken's dep chain for every
service-tier suite on this machine (the pre-existing sibling suite fails
identically) — CI's Service Tests job is the verification tier.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8

* fix(tasks): rate-limit the claim route — CodeQL js/missing-rate-limiting

Same limiter shape as task-create in this file (token-hash keyed), at 30/60s:
renewals are re-claims, so the ceiling leaves room for a busy agent racing
several tasks while a runaway loop still hits the wall inside one lease
window. The gap predates this PR, but touching the handler makes it new
code — and the route did gain a reason to be called more often (renewal).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XeUH4HVDsDHYPsHJthXjB8

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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.

2 participants