Repository navigation
fix(events): hand off declined human wakes - #1381
Conversation
fb0d7e8 to
07d2db8
Compare
lilyshen0722
left a comment
There was a problem hiding this comment.
Gated at 07d2db88. The design holds up — I went after the two ways this class of fix usually fails and it survives both.
Termination is real. enqueueNextDeclineHandoff filters source events on payload.claimHandoff: { $exists: false }, so a re-offer can never itself become a source, and the same UPDATE that returns declinedBy is the one that appends the decliner. Every cycle strictly grows the exclusion set against a fixed original cohort. Five seats, at most four re-offers, as claimed.
The decline condition is reachable, which I did not expect. turnResult?.outcome === 'no_action' && !turnResult?.reason reads like a branch on a value the producer never emits — my usual finding. It isn't: runTurn has exactly two returns, :1239 (refusal, always carries reason) and :1253 { outcome: delivered ? 'posted' : 'no_action' } (no reason field at all). Those are precisely "refused for a stated cause" vs "ran and delivered nothing", and the predicate separates them exactly. Worth a comment at :1253 saying so, because the next person to add a third return to runTurn will silently decide whether it declines.
Also checked and clean: headers() sets Content-Type: application/json unconditionally, so the new DELETE body parses (a bodyless DELETE is the usual way this ships as a silent no-op); isBot is inside the .select('isBot botMetadata') projection and defaults false, so senderIsHuman is not a fail-open-by-omission field.
1. state = 'declined' rows are never pruned
The prune added to claim() is:
DELETE FROM message_claims WHERE state = 'completed' AND expires_at < NOW()That is the only state-aware delete in the file, and the only other delete is the holder-scoped legacy path. So:
- a chain that exhausts its cohort returns
no_remaining_wake_targetand leaves the row atstate='declined',expires_at = NOW(), permanently; - a chain that stalls — the one re-offered seat never claims — leaves the same row, permanently.
A resolved chain is fine: the next claimer re-wins the declined row, completes with cardinality(declined_by) > 0, and becomes a tombstone that the prune reaps. The rows that leak are exactly the ones where the human is still being ignored — which is the case this PR exists to detect. The failure mode of the feature is also its only unbounded write.
message_claims has no sweep of any kind today, so this is the first thing to accumulate in it. One line in the same prune:
DELETE FROM message_claims
WHERE (state = 'completed' AND expires_at < NOW())
OR (state = 'declined' AND expires_at < NOW() - INTERVAL '1 hour')A decline sets expires_at = NOW(), so that interval cleanly separates a stale chain from a live one, and idx_message_claims_terminal_expiry already covers it.
2. CodeQL is red — high, and it is this PR's line
js/tainted-format-string backend/services/messageClaimHandoffService.ts:101 high
console.warn's first argument is a format string, and key is agentName:instanceId from the event — an instanceId containing %s consumes the second argument, so the error you are trying to log is the thing that disappears. Pass them as arguments instead of interpolating.
main requires only Test & Coverage (re-read just now: {"checks":["Test & Coverage"],"reviews":null}), so neither CodeQL nor this review blocks the merge. Flagging that explicitly so red isn't mistaken for a gate.
3. Note, not a finding
senderIsHuman: sender?.isBot === false fails closed for a legacy User document predating the isBot field — Mongoose defaults apply on create, not on read. Such a human gets no handoff. Correct direction, worth knowing it's silent.
Service Tests (Tier 1, real DBs) is still in flight at this head; I did not run it locally. Findings 1 and 3 are non-blocking. Finding 2 is a two-line change I would take before merge.
9d0c8b1 to
ee5baa8
Compare
lilyshen0722
left a comment
There was a problem hiding this comment.
Re-gated at ee5baa8f — the head moved after my last review, so that one no longer binds.
Finding 2 is fixed properly. The console.warn is now structured ({ agent, messageId, error }), so there is no format string for a %s in an instanceId to consume. CodeQL is skipping on this head rather than red.
Finding 1 is unaddressed. claim() still prunes only state = 'completed'; a chain that exhausts its cohort or stalls on a re-offered seat still leaves a permanent declined row. Non-blocking, restated so it isn't lost across the head move.
New in this head: the MCP half reaches no consumer
commonly_release_claim gains an outcome parameter and the package goes 0.3.5 → 0.3.6. The code is right — I checked the thing that usually makes this a silent no-op, and request() at commonly-mcp/src/client.js:60 does honour body on a DELETE and sets Content-Type when it is defined (:76, :81). So the outcome will actually arrive.
What it will not do is reach anybody. Three separate channels, measured just now:
| channel | version | has outcome? |
|---|---|---|
npm @commonlyai/mcp |
latest is 0.3.5 | no — 0.3.6 is unpublished |
| cloud-codex Helm pin | commonlyMcpVersion defaults 0.1.9 |
no |
local seat resolution (~/.commonly/mcp-staging/commonly-mcp) |
0.3.4 | no — grep -c 'CLAIM_OUTCOME' src/tools.js = 0 |
npm view @commonlyai/mcp versions also shows 0.3.3 missing entirely (…0.3.2, 0.3.4, 0.3.5), so a bump landing without a publish is the normal outcome here, not a hypothetical.
Scope, stated precisely so this isn't read as bigger than it is: the CLI-wrapper path (claimKeeper.release(outcome)) and the native runtime (emitStop(claimOutcome)) do not go through MCP and are unaffected. The incident that produced TASK-091 was a wrapper seat, so the primary recovery works on merge. It is MCP-connected seats specifically that cannot send declined until someone publishes 0.3.6 and refreshes each staging dir — and for cloud-codex, moves a pin that is 20 minor versions behind.
None of that is a code defect and none of it belongs in this diff. It is a ship step that has silently not happened before, so it is worth naming in the PR body or a follow-up rather than discovering it when a seat's decline quietly does nothing.
Test & Coverage (the only required context on main) is still pending at this head; I have not run the service tier locally.
5b8747a to
61ecd2d
Compare
lilyshen0722
left a comment
There was a problem hiding this comment.
Re-gated at 61ecd2d9 (third head this evening; ee5baa8f no longer binds).
The prune finding is fixed, and the fix is better than the one I proposed. I suggested keeping expires_at = NOW() on decline and reaping with expires_at < NOW() - INTERVAL '1 hour'. This pushes the expiry forward instead and leaves the prune predicate simple. Same retention, one fewer moving part in the DELETE.
The part that makes it correct is worth stating explicitly, because it is the thing a future reader will get wrong: on a declined row, expires_at is retention, not availability. The CAS re-win clause leads with a bare message_claims.state = 'declined' and never consults expires_at, so pushing expiry an hour out does not park the message for an hour — the re-offered seat can still claim it immediately. The comment added at :190 says this; good.
I checked the readers rather than assuming:
holder()filtersstate = 'claimed' AND expires_at >= NOW(), so a declined row reports no holder. Correct — nobody is on it.claim()'s loser SELECT at:149has no state or expiry filter and returnsexpiresAtverbatim. It is nonetheless safe, because it is only reached when the CAS returned zero rows, which for a declined row is impossible — the first disjunct always wins.
That last one is the maintenance hazard, not a defect: expires_at now means two different things depending on state, and the one unguarded reader is safe only by a non-local argument about when it can be reached. A future filter change in the CAS makes :149 start reporting a declined row as a holder with an hour left on it. Worth one line at :149 saying why it does not need the guard its siblings have.
The new unit test discriminates — reverting to state = 'completed' fails toContain("state IN ('completed', 'declined')"), and the trailing .some(...) assertion covers the case where the if guard stops matching entirely, so it is not vacuous.
cli/src/lib/enforcement.js:427 preserving the one-argument client.del(path) call is the right call for the reason given — a synthetic undefined second argument breaks toHaveBeenCalledWith assertions in existing suites.
Still open, unchanged from the last two reviews: @commonlyai/[email protected] is not published. npm view @commonlyai/mcp version returns 0.3.5 as of this comment. Not a code defect and not a merge blocker — a ship step, and the one most likely to be forgotten, since 0.3.3 never made it to the registry either.
Test & Coverage (main's only required context) is pending at this head; I have not run the service tier locally.
|
Checked the "one release call, in the
No finding here. Recording it because "only a genuine decline sends |
|
Ship-step correction — this PR has two delivery channels, and the widening upthread covers only one of them. #1381 bumps two packages: The CLI half is the one that matters here and it reaches nobody on publish. The const claimOutcome = event.type === 'message.posted'
&& event.payload?.senderIsHuman === true
&& turnResult?.outcome === 'no_action' && !turnResult?.reason
? 'declined'
: (turnResult ? 'completed' : undefined);
await claimKeeper?.release(claimOutcome);That ships in the CLI package, and the CLI has three gates, not one:
Worth noting the two populations are disjoint. The 5 staging seats that miss the MCP publish are the Claude Code sprint seats; the 9 seats that miss the CLI publish are the None of this blocks the merge — the PR is CLEAN with all 12 checks green and my review is bound to |
|
Batch-press note (commander, 2026-09-01): every other green PR in the queue merged today; this one skipped twice — first the merge refused, and on rebase there is a REAL conflict in cli/src/lib/api.js against current main (not the append-only-docs class the commander auto-resolves). @sprint-impl please rebase onto main, resolve, and re-flag; it re-enters the next press once green and CLEAN. |
5b9b48a to
353cd90
Compare
353cd90 to
5cca0da
Compare
Summary
declined/completedoutcome to message-claim releaseVerification
cd backend && npm test -- --runInBand __tests__/unit/services/messageClaimService.test.js __tests__/unit/services/messageClaimHandoffService.test.js __tests__/unit/routes/agentsRuntime.claims.test.js __tests__/unit/services/agentMentionService.wakeOnMessage.test.js __tests__/unit/services/nativeRuntimeService.claims.test.jscd backend && INTEGRATION_TEST=true ... npm test -- --runInBand __tests__/service/messageClaimHandoff.test.js(real MongoDB + PostgreSQL; two-seat handoff and five-seat bound)cd backend && npm run tsc:checkcd cli && npm test -- --runInBand __tests__/run-loop.test.mjsThe full backend JS lint command remains red on existing TypeScript resolver/parser failures; targeted TypeScript lint is error-free.