Skip to content

Coding-agent subagents B3: grants minted at dequeue from the turn record (no bearer in the queue) #388

Closed

Description

@pdettori

Part of the Coding-agent subagents epic (#378). Item B3, milestone B-M1. Depends on B2 (#387) and MI1 S2, or the interim that B1 (#386) chooses.

Goal

When a worker takes an async turn off the queue, it gets that turn's inference and sandbox grants from the control plane, minted from the turn record. No caller bearer token is ever stored in the queue (MI1 §6.5).

Current state (verified on main @ 24c6f5e)

  • Today's exchange: the worker presents the caller's session token plus SH_EXCHANGE_TOKEN to POST /internal/credentials (packages/control-plane/src/exchange.ts). In direct mode on the VM it gets the user's real secret back.
  • MI1 S2 (Proposed) replaces this with POST /internal/turn-grants and /internal/grants/refresh (§6.2), with turn_exp as an absolute cap (§6.1).
  • A queued turn has no session token when it is dequeued. That's the problem §6.5 describes.

Scope

  1. A dequeue-time exchange: the worker presents the turn record id plus SH_EXCHANGE_TOKEN, and the control plane checks the record's state, owner, tombstone and deadline, then mints the grants.
  2. Refresh up to turn_exp, with the long-turn policy from Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386.
  3. Before S2: the interim Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386 chooses (for example, the credential resolved from the record, MOCA_TENANCY=single only), flagged in code and docs as interim, with a test that refuses it under multi.

M2 remainder (this issue, after the M1 interim landed in #713)

  • Both audiences' grants (MI1 §6.1), replacing the M1 interim's resolved-credential return value.
  • turn_exp and refresh, with Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386's long-turn policy. Already settled in spec §5.4: turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), clamped at mint, with turn start meaning dequeue and not enqueue.
  • The tenancy gate lifts, in both places that hold it: turn-handlers.ts (submission) and the dequeue check in turn-exchange.ts. ADR-0047 records it as a dated conditional refusal whose lifting criterion is exactly the two items above.
  • Pin model and sandboxTier to the turn record. Today the dequeue exchange reads both from the LIVE session while credentialName and cfg come from the record (spec §5.1 copies only what a turn must spend unchanged). So a PATCH /v1/sessions/{id} between submission and dequeue moves an already-queued turn onto the new model — and updateSession's own "a turn in flight keeps its model" does not cover it, because an async turn's exchange can be an hour after its submission. Pinning means adding both fields to the record, which is why it is M2 and not a different read. Raised in feat(control-plane): resolve an async turn's credential at dequeue (#388 M1) #713 review; the user-facing caveat is documented in fix(control-plane): #713 review follow-ups — correct the refusal docs, bound the dequeue turn id #714.

Acceptance

  • A test reading the stream proves no bearer token is ever in the queue.
  • A tombstoned session's queued turn is refused at dequeue.
  • Refresh is refused after turn_exp.
  • The interim path is refused under multi.
  • A turn queued before a PATCH that switches the session's model still runs on the model it was submitted with.

References

  • MI1 §6.1, §6.2, §6.5, §6.6; ADR-0032, ADR-0033

Working conventions (for a fresh session)

  • Workspace: git fetch, then create a worktree from rossoctl/main (never local main), under .worktrees/. Populate and build pi-fork (git submodule update --init --recursive && cd pi-fork && npm ci && npm run build), then pnpm install. A worktree without the pi-fork build does not typecheck.
  • Plans: write the plan with superpowers:writing-plans into docs/plans/<date>-<slug>.md. Plans are gitignored and never committed. Write it in chunks, one append per task.
  • Pre-flight table: list every process entrypoint, systemd unit, env example and shell/Go launcher whose boot contract changes, not only TypeScript call sites.
  • Tests: Redis on 6379 must be up. Use each package's own node_modules/.bin/vitest. vitest can exit non-zero with every test green, so grep the log for Errors. Redirect long output to /tmp/kagenti/.... make lint skips untracked files.
  • Commits: git commit -s with Assisted-By: Claude (Anthropic AI) <[email protected]>, never Co-Authored-By.
  • Shared KVM rig: alert the owner before using it, record a manifest of what you install, and verify cleanup.
  • Don't push or open PRs without the owner's go-ahead.

Activity

  1. added
    enhancement
    on Sep 30, 2026
  2. changed the title [-]Claude Code subagents B3: grants minted at dequeue from the turn record (no bearer in the queue)[/-] [+]Coding-agent subagents B3: grants minted at dequeue from the turn record (no bearer in the queue)[/+] on Oct 13, 2026
  3. added 2 commits that reference this issue on Nov 6, 2026
  4. cwiklik commented on Nov 6, 2026

    @cwiklik
    Contributor

    Design landed, and it makes this issue bigger than its body reads. #386 closed with docs/specs/2026-11-05-p6-async-fan-out-design.md §5.4 and ADR-0047 (#696, merged 316056a7). Posting the decisions per the spec's §12 obligation.

    The finding that resizes this issue: turn_exp does not exist in code. Scope item 2 above ("refresh up to turn_exp") and #386 item 5 both read like a policy to tune on an existing field. MI1 §6.1 specifies it — "an absolute cap: turn start + MOCA_TURN_MAX_S", with exp = min(now + MOCA_GRANT_TTL_S, turn_exp) and MOCA_TURN_MAX_S defaulting to 1800 — but no TypeScript in the repo implements it. grep -rn 'turn_exp\|turnExp' packages harness returns nothing outside docs. Expiry today is always exp = iat + ttlSeconds, clamped only for sandbox tokens by the resource's own expiresAt. So this issue has to build turn_exp, not configure it, and that is where §9's M1/M2 split comes from: M1 ships without it under MOCA_TENANCY=single, and M2 is gated behind it.

    Building it is discharging MI1 S2's own spec rather than adding to it — worth stating so the two are not designed twice.

    "Turn start" is dequeue, not enqueue. A leaf that waits an hour in the queue must still get its full MOCA_TURN_MAX_S, and a grant minted at enqueue would already be expired on arrival. §5.4 flags this as a semantic MI1 §6.1 does not currently pin down — a correction S2 needs regardless of async fan-out.

    The mint sequence (§5.4), for scope item 1:

    1. The worker calls the control plane with the turnId (plus its own identity / SH_EXCHANGE_TOKEN).
    2. The control plane loads the record and mints unless the record is cancelled or already terminal, resolves credentialName against the owner's SubjectDocument, and mints an inference grant and a sandbox grant — aud: moca-inference / moca-sandbox, claim sets per MI1 §6.1's table.
    3. state → running as a compare-and-set from queued; a record already running is a redelivery and stays running. attempts is written from the entry's deliveryCount.
    4. The worker runs runLeaf with the grants.

    Step 2's check is "not terminal", not "queued" — this is the subtle one. A narrower check defeats goal 3 in exactly the case it exists for. Step 3 sets running on the first claim, so every redelivery arrives with the record already running: a crash-reclaimed entry, a drained one, and a retryable outcome that processOne returns without acking all look identical to the mint. Refusing those would ack and drop them — and because a non-terminal record carries no TTL (§5.1) and attempt exhaustion is the only author of lost, the record would be stranded in running forever with no entry left for the reaper to find. The mint refuses only a withdrawal (cancelled) and an already-terminal turn.

    It also must not test attempts. deliveryCount is the single authority for exhaustion, checked by processOne's dead-letter branch before the mint is reached. Two counters that can disagree is the shape §5.1's heartbeat note rejects for liveness. The record's attempts is descriptive only.

    The long-turn policy (§5.4), which #386 item 5 asked for explicitly:

    • MOCA_TURN_MAX_S stays the deployment-wide ceiling at its 1800 s default. Raising it would desynchronise it from its sibling worker deadlines and change every interactive turn too.
    • A turn may request less, never more: turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S). The min is the whole policy. A caller asking for more is clamped, not refused — refusing would make a client's cap request a deployment-coupling concern.
    • An hour-long turn is an operator decision, not a caller's. Raising MOCA_TURN_MAX_S to 3600 is the supported route — auditable, deployment-wide. Note this is narrower than item 5's phrasing ("allows hour-long detached turns") implies, deliberately: letting an untrusted caller name its own expiry above the ceiling hands it control of how long its own credential lives.
    • The clamp is enforced at mint, in the control plane, never from a value the worker or caller supplies.

    One question is left open and it is yours to close: whether refresh past turn_exp is refused outright (MI1 §6.2's current rule) or whether a leaf that is provably still running may extend once. §5.4 says refusing is the safe default and what M2 should ship; the §6.2 claim heartbeat is what a future extension would key off, since it already proves liveness. Pick one and record it.

    On scope item 3, the pre-S2 interim. §9 places M1 before S2 using exactly this interim — the credential resolved from the turn record at dequeue, MOCA_TENANCY=single only, with async under multi refused by name. The spec is explicit that the cost is a tenancy gate and that the gate must be a named refusal with a lifting criterion rather than silence, in the shape ADR-0041 used for its own deprecation window. This issue's acceptance criterion "the interim path is refused under multi" is therefore M1-blocking, not M2.

    Unchanged and still correct in the body above: the current exchange (exchange.ts, session token + SH_EXCHANGE_TOKEN → POST /internal/credentials), and that a queued turn has no session token at dequeue. Note the body says "verified on main @ 24c6f5e", which predates #691 — but nothing in this issue's current-state section was changed by that removal.

    Acceptance gains one case from the design: a redelivered entry whose record already says running must still mint. That is the failure this issue is most likely to ship with, since it only shows up after a crash or a drain.

  5. cwiklik commented on Nov 10, 2026

    @cwiklik
    Contributor

    The M1 interim slice of this issue has landed. #713 merged as bb89a84e (6 commits, 11da422d..1c6e1567, 17/17 checks). Scope item 3 and three of the four acceptance criteria above are discharged; items 1 and 2 are the M2 half, which §9.1 gates behind MI1 S2. Leaving this open as that tracker rather than closing and re-cutting, same as #387.

    What landed

    POST /internal/turn-credentials, auth: 'exchange' (routes.ts:337). A worker that has just taken a turn id off the stream presents it plus the deployment-wide SH_EXCHANGE_TOKEN, and the control plane resolves the credential that turn spends from the turn record it wrote at the authenticated enqueue (turn-exchange.ts). MI1 §6.5's requirement is the whole reason the endpoint is shaped this way: no bearer token is ever stored in the queue, and at dequeue there is no session token left to present.

    Everything after deciding which subject and credential are in play is shared verbatim with the session exchange — resolveInference, refuseMisdirectedSecret, placeholderFor, sessionTier — so an async turn spends exactly the credential an interactive one would, and an injector added to a deployment narrows what a worker holds on both paths.

    Six checks, each failing closed, in this order:

    # Check Refusal
    1 the record exists turn_not_found (404)
    2 its state is not terminal turn_not_claimable (409)
    3 the session exists and its owner matches the record's session_not_found (404)
    4 the session is not tombstoned session_not_found (404)
    5 tenancy is single async_tenancy_unsupported (501)
    6 resolveInference(record) the live exchange's own codes, unchanged

    Unknown-session and owner-mismatch answer identically, with nothing to distinguish them. Check 3's owner compare is load-bearing rather than belt-and-braces: resolveInference reads owner and credentialName off the record it is handed, so a record whose owner disagrees with its session's would otherwise be a request for whichever subject's credential it names. Check 5 runs before check 6 deliberately — a gate that fired afterwards would already have read a secret it is forbidden to return, and turn-exchange.test.ts:227 pins that ordering by deleting the credential and asserting the answer stays the tenancy refusal.

    Three decisions worth recording, because none of them is obvious from the diff:

    • The endpoint is a pure read. queued → running stays with Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389's consumer, which already holds deliveryCount. SH_EXCHANGE_TOKEN is one deployment-wide secret, so a write here would let every holder of it flip an arbitrary turn out of queued — and since cancel accepts queued only, make a caller's own turn permanently uncancellable. No window opens by leaving it there: markRunning re-checks terminality itself, so a DELETE landing between the two calls is still refused.
    • Check 2 admits running, not just queued (§5.4). The first claim writes running, so every redelivery — crash-reclaimed (§6.2), drained (§6.3), or a retryable outcome left unacked — arrives on a record that already says running. Refusing those would ack and drop exactly the entries crash recovery exists for.
    • attempts is never tested. The queue entry's deliveryCount is the single authority on exhaustion, checked by the consumer's dead-letter branch before it ever calls here. A second limit read off the record could only disagree with it, and would strand a turn the queue still intends to deliver.

    The audit write is deliberately not best-effort, unlike the submission routes' auditBestEffort: those audit a write that already happened, so swallowing keeps a repair path open during an outage. Here the audit is the only record that a credential left the control plane, so a failed write refuses the credential rather than issuing one off the books. The entry carries the credential's name, never its value (§7.2), and the test asserts that against the whole stream rather than just the one entry.

    No boot contract changes: no new environment variable, no entrypoint, systemd unit, env example or launcher touched. The only caller arrives in #389.

    Acceptance

    • No bearer token is ever in the queue. turn-e2e.test.ts drains a real stream entry and asserts its fields are exactly ['turnId'], then runs the whole claim through the HTTP hop from that one field.
    • A tombstoned session's queued turn is refused at dequeue. turn-exchange.test.ts:191. This matters more here than on the interactive path: a tombstoned session's queue entries are still on the stream, so without check 4 a DELETE /v1/sessions/{id} would be followed by its leaves running anyway, each one spending the owner's credential.
    • The interim path is refused under multi. turn-exchange.test.ts:214, by name. Asserted even though submitTurn already refuses multi — that refusal stops new submissions, while a deployment flipped to multi with entries already on the queue would otherwise drain them down the single-tenant path this gate exists to forbid.
    • Refresh is refused after turn_exp is left to M2. There is no grant to refresh.

    One gap found by review, after the tests were green

    The post-merge review mutation-tested the new code — delete a line, run the suite, see whether anything fails — and found that removing refuseMisdirectedSecret(resolved, …) from exchangeTurnCredential left all 1152 control-plane tests green. The check is shared with the session exchange, so every test that covered it lived on the session path (exchange-auth-header.test.ts) and passed either way. That is the one failure on this path that costs a user their key rather than only failing the turn: in direct mode a raw sk-ant-… key would be sent to a gateway host that is not api.anthropic.com (#368).

    1c6e1567 adds the test on the async path specifically, verified load-bearing the same way: with the call removed, exactly one test fails and it is that one. touchBundle on this path is still uncovered — it is best-effort by design, so a silent no-op costs a bundle TTL refresh and not a turn.

    What is left here, and what gates it

    Scope items 1 and 2, per §9.1's "M2 — requires S2 (grants, token endpoint)":

    1. Both audiences' grants (MI1 §6.1), replacing this slice's resolved-credential return value.
    2. turn_exp and refresh, with the long-turn policy from Coding-agent subagents B1: design — async leaf turns on sessions for P6 (spec + ADR) #386. The policy is already settled in §5.4 — turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), clamped at mint, with turn start meaning dequeue and not enqueue.
    3. The tenancy gate lifts, in both places that hold it: turn-handlers.ts:110 (submission) and check 5 above (dequeue). ADR-0047 records it as a dated conditional refusal whose lifting criterion is exactly items 1 and 2.

    Two decisions handed to #389

    Both are written down here rather than left to be rediscovered:

    1. The response carries no envelope. A worker needs one to run the leaf, and the e2e test's fakeWorker gets it by calling turns.get(turnId) directly against Redis (turn-e2e.test.ts:183) — outside the HTTP hop. So this endpoint is not the complete claim handshake its own description implies. Coding-agent subagents B4: async leaf worker on P6 (deploy/vm, compose) #389 decides: either envelope joins the response, or the description says plainly that the worker reads the record directly.
    2. sandboxTier and model are read from the LIVE session, while credentialName and cfg are pinned to the record. §5.1 copies onto the record only what a turn must spend unchanged, so the two it does not copy can only be read from the session as it is now. The consequence is real: a PATCH /v1/sessions/{id} between submission and dequeue moves an already-queued turn onto the new model. updateSession's own "a turn in flight keeps its model" does not cover it, because an async turn's exchange can be an hour after its submission. Pinning them means adding both to the turn record — M2 work, not a different read here.

    Also still carried into #389, unchanged from #704's list: the leafResultKey sanitization divergence (harness/src/run-leaf.ts:91-102,183-185), which remains the one real defect among them — a result can be written where the status read will never look, and nothing exercises it until a real leaf runs.

    Assisted-By: Claude Code

  6. 9 remaining items

  7. modified the milestones: v0.11.0, v0.12.0 on Nov 17, 2026
  8. cwiklik commented on Nov 18, 2026

    @cwiklik
    Contributor

    Landing note: M2 shipped in #807 and #822, and the one open question is already answered in code — closing

    M1 was recorded here by #713. M2 was never recorded, which is the only reason this is still open. Verified on main @ 6ea986d7.

    Scope item (from the M1 comment above) Where Evidence on main
    1. Both audiences' grants (MI1 §6.1), replacing M1's resolved-credential return value #807 (32b34d75, "mint a turn's grants from the turn record") grant-exchange.ts:182 — grantsForTurn mints from the turn record; GRANT_AUDIENCES at grant.ts:37, with the refresh route the only caller that legitimately accepts either
    2. turn_exp and refresh, with #386's long-turn policy #822 (c5ed823e, "mint turn grants at dequeue under multi tenancy") turn_exp = dequeue + min(caps.wallClock ?? MOCA_TURN_MAX_S, MOCA_TURN_MAX_S), anchored at dequeue and not enqueue. ttlSeconds is MOCA_TURN_MAX_S, so exp == turn_exp and nothing refreshes mid-turn — decision D4, with its reasoning and its shortcut: limit recorded at grant-exchange.ts:161-181
    3. The tenancy gate lifts, in both places that held it #822 Submission: turn-handlers.test.ts:165 asserts async is ADMITTED under MOCA_TENANCY=multi and that async_tenancy_unsupported is not returned. Dequeue: turn-exchange.ts:187 records the gate as gone. main.ts:255 names the boot contract that replaced the per-request refusals

    The open policy question is answered — in shipped, tested code

    What #686's status comment still listed as open here was ADR-0047's question: past turn_exp, is a refresh refused outright, or may a still-running turn extend? It ships as refused outright:

    • turn_exp is carried forward unchanged on refresh, so refreshing cannot extend a turn however many times it happens (grant-exchange.ts:209, refreshTurnGrants).
    • verifyGrant raises grant_invalid on a grant whose turn_exp has passed, before the session is read at all.
    • Pinned four ways: grant-exchange.test.ts:264 ("refuses outright once turn_exp has passed, rather than extending the turn"), grant.test.ts:199 (a grant past turn_exp whose own exp is still in the future), grant.test.ts:121 (exp clamped down to turn_exp, and minting refused once the turn is out of time), grant-redeem.test.ts:34.

    The async spec's own wording for this — "refusing is the safe default and what M2 should ship" (§5.4) — is what M2 shipped, so there is nothing left to answer or split out.

    Also closed since the M1 comment

    The two decisions that comment handed to #389 are both resolved: envelope joins the claim response (turn-exchange.ts:231,301, sessionId applied last so a stored envelope cannot override the record's own) rather than the worker reading Redis behind the HTTP hop, and model and sandboxTier are pinned to the turn record (#788, turn-store.ts:163-165), so a PATCH /v1/sessions/{id} between submission and dequeue can no longer move an already-queued turn onto a new model. The leafResultKey sanitization divergence carried over from #704 — the one real defect on that list — was fixed in #840.

    Epic #686 then has only #391 (PR #856, in review) left.

    Assisted-By: Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions