Skip to content

fix(events): hand off declined human wakes - #1381

Merged
lilyshen0722 merged 1 commit into
mainfrom
fix/task-091-claim-decline
Sep 1, 2026
Merged

lilyshen0722 merged 1 commit into
mainfrom
fix/task-091-claim-decline

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Summary

  • add an explicit declined / completed outcome to message-claim release
  • re-enqueue exactly one remaining original human wake when the winner returns silent, with per-seat history bounding the chain
  • preserve terminal completion after a handoff and stamp human origin on wake events
  • make the native runtime recognize a message-service silent skip as a decline

Verification

  • 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.js
  • cd 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:check
  • cd cli && npm test -- --runInBand __tests__/run-loop.test.mjs

The full backend JS lint command remains red on existing TypeScript resolver/parser failures; targeted TypeScript lint is error-free.

@samxu01
samxu01 force-pushed the fix/task-091-claim-decline branch from fb0d7e8 to 07d2db8 Compare August 30, 2026 22:35

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_target and leaves the row at state='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.

@samxu01
samxu01 force-pushed the fix/task-091-claim-decline branch 2 times, most recently from 9d0c8b1 to ee5baa8 Compare August 30, 2026 22:42

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@samxu01
samxu01 force-pushed the fix/task-091-claim-decline branch 2 times, most recently from 5b8747a to 61ecd2d Compare August 30, 2026 22:56

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() filters state = 'claimed' AND expires_at >= NOW(), so a declined row reports no holder. Correct — nobody is on it.
  • claim()'s loser SELECT at :149 has no state or expiry filter and returns expiresAt verbatim. 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.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Checked the "one release call, in the finally" claim rather than taking it, and then pushed on the part it doesn't cover — whether any other terminal branch can produce a spurious declined.

claimKeeper.release has exactly one call site (agent.js:1028). Confirmed. The interesting question is the three ways runTurn can reach that finally without posting, because two of them would be bugs if the outcome mapped to declined:

  • agent posted via its own tool (:1170) — safe, and not for the reason the branch suggests. delivered is initialised to agentPostedItself at :1108, so it is already true before the delivery block runs; the return is { outcome: 'posted' } → completed. Had it been initialised false, a turn where the agent did reply visibly would be re-offered to another seat — exactly the duplicate-visible-response the comment at :1017 says this avoids.
  • claim lost mid-turn (:1175) — the reply is suppressed and delivered stays false, so the finally does compute declined for it. Harmless, but by a second mechanism rather than the intended one: release() early-returns on if (!acquired || lost), so nothing is sent at all. Defence in depth is fine; worth knowing the outcome mapping alone would get this case wrong, and that the holder-scoped WHERE claimed_by = $2 is the third layer if the first two ever slip.
  • normal silent turn — the intended path, no_action with no reason.

No finding here. Recording it because "only a genuine decline sends declined" is the invariant this feature rests on, and it currently holds across three independent guards rather than one — which is worth a reviewer having enumerated once.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Ship-step correction — this PR has two delivery channels, and the widening upthread covers only one of them.

#1381 bumps two packages: commonly-mcp 0.3.5 → 0.3.6 and cli 0.1.26 → 0.1.27. The MCP half is well characterised — npm latest is 0.3.5, 22 of 27 seats resolve npx -y @commonlyai/mcp@latest at spawn so a publish reaches them on next spawn, and the 5 staging seats need a hand refresh.

The CLI half is the one that matters here and it reaches nobody on publish.

The declined mapping — the load-bearing behaviour of TASK-091 — lives in cli/src/commands/agent.js, in the finally:

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:

  1. npm publish of 0.1.27. Necessary, not sufficient.
  2. A global reinstall. /opt/homebrew/bin/commonly resolves to ../lib/node_modules/@commonlyai/cli/src/index.js, currently at 0.1.24 — while npm latest is already 0.1.26. Two publishes have landed and the installed binary did not move. That is not a prediction; it is a natural experiment already on disk, and it falsifies "a publish alone reaches them" for this channel.
  3. A process restart per seat. There are 9 live commonly agent run seats on this machine — kai, vera, wren (booted Aug 26), otto, juno, reed, hollis, vale (Aug 28), piper (Aug 30). Each loaded its code at boot from the global install, so even a correct global update leaves every one of them on 0.1.24 until it is restarted.

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 commonly agent run wrappers. Neither list covers the other, so "which seats need a hand" has a different answer per package.

None of this blocks the merge — the PR is CLEAN with all 12 checks green and my review is bound to 61ecd2d9. It is a note for whoever does the ship, so the CLI half doesn't get marked delivered on the strength of a publish.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

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.

@samxu01
samxu01 force-pushed the fix/task-091-claim-decline branch 2 times, most recently from 5b9b48a to 353cd90 Compare September 1, 2026 11:25
@samxu01
samxu01 force-pushed the fix/task-091-claim-decline branch from 353cd90 to 5cca0da Compare September 1, 2026 11:46
@lilyshen0722
lilyshen0722 merged commit 2a605d0 into main Sep 1, 2026
11 checks passed
@lilyshen0722
lilyshen0722 deleted the fix/task-091-claim-decline branch September 1, 2026 11:56
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