Skip to content

feat(393): gates v2 -- any leaf kind, an async decision route, and a deadline - #972

Merged
pdettori merged 26 commits into
rossoctl:mainfrom
cwiklik:feat/393-gates-v2
Nov 23, 2026
Merged

pdettori merged 26 commits into
rossoctl:mainfrom
cwiklik:feat/393-gates-v2

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Closes #393 (child B7 of epic #378): the human gate, extended to the kinds and the dispatch path that had none.

Four parts, in the order the commits land:

§1 — any leaf kind can be gated. requireApproval: true on a prompt or solve envelope registers request_approval and parks the run, the way item.require_approval already did for a verdict leaf. The gate is decided before the sandbox lease (gateShortCircuit, split out of decideSeed in the first commit), so a parked leaf holds nothing — a converge leaf used to lease a pod and then park on it.

§2 — an async turn can be answered. POST /v1/sessions/{id}/decision takes {gateId, action, feedback}, copies the paused turn's envelope, appends the decision and 202s with a new turn id. paused is terminal and unflippable, so a decision never reopens the paused turn — it creates a linked one (resumeOf). The idempotency key is keyed by the gate, which is what makes a double-click and a racing deadline sweep converge on a single resume. A stale gateId is refused with gate_not_pending.

§3 — a gate can carry a deadline. gateDeadlineS on the submission and MOCA_GATE_DEADLINE_S on the deployment (default 0, never) are both ceilings, and the tightest in force wins — including the turn record's own TTL, because a gate whose record is gone can no longer be answered by anyone. Paused turns go into one global zset scored by deadline, and a 30 s .unref()ed sweep answers whatever expired with the turn's onTimeout: abort by default, reject by request, and never approve — an unanswered gate is the absence of a yes, and a clock cannot consent. Across replicas the index ZREM is the lock; no leader election, no lock key.

§4 — what survives an open gate. A gate can stay open for an hour. Asserted and written down rather than changed: the gate and the transcript are session entries, so they survive the sandbox; a solve resume re-converges and rebuilds a reclaimed workspace while keeping a surviving worktree's original baseline. Two gaps are documented with what the user loses and keeps (a prompt leaf has no repo to rebuild; uncommitted edits don't survive a move), both pointing at #338's lease work.

Operator-facing changes

  • New env var MOCA_GATE_DEADLINE_S, default 0 = never, wired through deploy/compose, deploy/k8s/base (optional ConfigMap key) and deploy/vm/env/control-plane.env.example. Unset changes nothing for an existing deployment.
  • API 1.35.0 → 1.36.0: the decision route, plus gateDeadlineS / onTimeout on the async submission. docs/api/CHANGELOG.md and docs/reference/change-policy.md updated.

Testing

  • packages/control-plane: 2088 passed / 4 skipped (86 files), including the store contract against real Redis.
  • harness: 1018 passed. One unrelated pre-existing failure on macOS — test/context-overlay.test.ts fails with mv: Permission denied after the populate script's chmod -R a-w; this PR's harness changes are test-only and in other files.
  • make typecheck, make fmt, make check-links: clean. make lint could not run locally (hadolint needs a Docker daemon) — left to CI.
  • Not exercised: every gate path here is unit-tested only. Nothing has run against a real model, a real sandbox lease, or the compose/Kind end-to-end, so the acceptance check worth doing on a live deployment is that a turn submitted with requireApproval: true, gateDeadlineS: 60, onTimeout: 'reject' pauses and is resumed by the sweep within ~90 s.

One thing a reviewer should look at

packages/control-plane/src/turn-handlers.ts and handlers.ts are in a runtime import cycle (assertOwner). A module that reaches turn-handlers.js first makes HANDLERS spread an uninitialized TURN_HANDLERS and silently serve no turn routes at all — {...undefined} is {}, so it fails quietly. The new gate-sweep.ts is a fresh way into that cycle; it is pinned with comments and main.ts imports server.js well before it, but the underlying cycle is pre-existing and worth its own fix (moving assertOwner/requirePrincipal into handler-util.ts).

Assisted-By: Claude Code

…ircuit

A paused or aborted leaf does no model call and touches no workspace, but
decideSeed cannot say so until it has a fresh prompt -- which on the verdict
path needs a leased sandbox and a converged worktree. gateShortCircuit answers
the stop-now half with no prompt, so every leaf kind can park before it leases.

decideSeed keeps its signature and delegates, so the two cannot disagree.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
realProduceVerdict leased a pod and converged a worktree on its way to
discovering the leaf was parked at a gate -- on a saturated pool, a lease taken
from a leaf that could have used it. The pause/abort half of the gate front-end
moves above the lease, beside the verdict fast-path that skips it for the same
reason; the seed half stays below, because it needs workspaceRef.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…costs

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik
cwiklik requested a review from pdettori as a code owner November 20, 2026 22:39
@cwiklik cwiklik added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 20, 2026

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Extending the gate to every leaf kind is the right shape, and the promises in the body hold where I checked them against head: onTimeout is refused unless it is abort or reject and re-validated on read, resolveGateDeadline takes the minimum of the positive bounds so an unset 0 never becomes a deadline, the decision route is auth: 'api' + sessionScoped and calls assertOwner first, and gateShortCircuit runs before any lease on all three kinds. Three problems are in the new paths rather than the old ones: the session-wide continuation replay now reaches prompt/solve leaves that never asked for it, the continuation text tells prompt/solve resumes to call submit_verdict, which those leaves do not register, and a failed submitResume leaves the gate marked answered with nothing left to retry it.

Not run here: the packages/control-plane and harness suites (this review environment has no dependencies installed for head). The findings below are from reading head at ab8e269, cross-checked against turn-store.ts, gate.ts and run-leaf.ts.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness/src, packages/control-plane/src, their tests), YAML (deploy), docs/OpenAPI
Agent/IDE config (.claude/.vscode): none
Commits: 11 commits, all signed-off: yes
CI status: passing (codeql, dependency-review, deploy-scripts, deploy-scripts-bash32, docs, hadolint, k8s-kind-e2e, lint, microvm-gates, proto, shellcheck, trivy-scan)

Checked and correct, so not raised as findings: the gate is decided before selectPoolSandbox on prompt, solve and converge; paused is terminal and never reopened (resumeOf links a new record); the sweep's ZREM plus the gate-keyed idempotency key is a real mutex across replicas; MOCA_GATE_DEADLINE_S defaults to 0 and the TTL only clamps an existing deadline.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Comment thread harness/src/run-leaf.ts Outdated
}
// '' is the sentinel for "the caller builds its own fresh prompt": every kind's fresh prompt is
// different (and the prompt leaf's needs a sandbox path), so only the CONTINUATION comes from here.
const seed = decideSeed(state, decision, '');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — decideSeed with no pending gate re-derives the last decision's continuation, and with '' as the fresh prompt that continuation is the entire plan. For a fresh gated prompt or solve leaf in a session that answered an earlier gate, plan.continuation is therefore set, and both consume sites prefer it (line 933, line 1218). The leaf then runs Human decision: APPROVED… instead of env.prompt plus gatePromptNote(), never calls request_approval, and the new gate is bypassed silently — the opposite of the comment above the consume site. Suggested fix: keep the continuation only when this invocation carries a decision to consume, e.g.

...(decision && seed.prompt ? { continuation: seed.prompt } : {}),

Test: a session with one decided gate, then a fresh requireApproval prompt submission, asserting the leaf prompt is the task plus the steer.

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.

Fixed in fd36d89e, with your suggested guard: ...(decision && seed.prompt ? { continuation: seed.prompt } : {}).

Confirmed the diagnosis before changing anything — the continuation was keyed on the session's last decision rather than on this invocation's, which for the prompt and solve kinds is never right: unlike a verdict leaf, each of their turns brings its own prompt, so a replay is only ever a resume.

Test is harness/test/run-leaf-gate-kinds.test.ts > "opens a NEW gate for a fresh turn after an earlier decision": it seeds gate 0 plus its decision entry, then submits a fresh requireApproval prompt and asserts the leaf prompt is the task plus gatePromptNote(), that nextGateId is 1, and that the prompt contains no APPROVED. I checked it fails against the old line (it reports failed rather than responded, because the injected executeTurn's assertions throw) before keeping the fix.

Comment thread harness/src/run-leaf.ts
: buildSolvePrompt(env.problemStatement!, workspaceRef);
// A resume runs the continuation, not the problem statement again; a fresh gated run gets the
// steer toward request_approval appended (design §1).
const prompt = gate?.continuation

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — the continuation this prefers for a resumed prompt (and, at line 933, solve) leaf is continuationPrompt (gate.ts:106-116), which is verdict-leaf text: "When finished, call submit_verdict exactly once" / "or call submit_verdict when done". Prompt and solve leaves register only requestApprovalExtension (solve at line 1185; the prompt leaf likewise) — submitVerdictExtension is added only on the verdict path (allowVerdict, line 1386). A resumed prompt/solve leaf is therefore told to call a tool it does not have. Suggested fix: choose the continuation by leaf kind — the gatePromptNote()-style steer for prompt/solve, continuationPrompt for verdict — or pass the kind into decideSeed.

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.

Fixed in fd36d89e. continuationPrompt(action, feedback?, verdictTool = true) and decideSeed(..., verdictTool = true); planLeafGate — the prompt/solve entry point — passes false, and the verdict path at run-leaf.ts:1380 keeps the default, so its wording is unchanged.

Without the tool the two continuations end "Proceed with the proposed action, then stop." and "Revise accordingly. You may call request_approval again when ready, then stop." — request_approval stays, since both kinds do register it.

Pinned in two places: a unit assertion in gate.test.ts that neither action names submit_verdict when verdictTool is false and that decideSeed threads the flag to both continuationPrompt sites, and an integration assertion on the resumed prompt leaf in run-leaf-gate-kinds.test.ts.

await queue.enqueue(turn.turnId);
} catch (err) {
// The same compensation submitTurn does, for the same leak and with the same COMPARING release.
await turns.finalize(turn.turnId, 'failed', deps.now());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — when queue.enqueue throws, this finalizes the resume as failed and releases the gate-keyed idempotency key, but the failed record still carries resumeOf, and findPausedBySession treats any record with resumeOf as "the gate was answered" (turn-store.ts:346). The human retry then takes the found.resumed branch, finds no idempotency holder, and gets 409 gate_not_pending (line 404 onward); on the sweep path claimGate already ZREM'd the member, so no later pass retries either. A transient enqueue error therefore strands a gate that was never answered. Suggested fix: do not put resumeOf on the failed record (or have findPausedBySession ignore resumes that ended failed), and have the sweep re-add the zset member when its submission fails — the gate-keyed idempotency key makes the retry safe.

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.

Fixed in f4b27c2a, taking both halves of your suggestion.

findPausedBySession no longer counts a resume that ended failed: if (rec.resumeOf && rec.state !== 'failed') resumed.add(rec.resumeOf). I kept the broad failed rather than trying to tell "failed before the enqueue" from "ran and failed" — the narrower discriminator would be attempts === 0, and it buys little, because re-sending the decision for a resume that did run is a retry the harness makes safe: it owns the gate's durable state, and gateShortCircuit can never flip a decision already recorded there.

The sweep now hands the claim back when the submission throws — new TurnStore.releaseGate(turnId, dueAt), re-added at (paused.endedAt ?? now) + gateDeadlineS * 1000, the same instant toTerminal scored it, so the deadline is restored rather than extended and dueGates' oldest-first fairness is preserved.

One behaviour change worth naming: a resume that ran and then failed now makes its gate answerable again, where it used to be a permanent 409. Tests: turn-store-gate.test.ts ("does not count a FAILED resume…", "releaseGate puts a claimed gate back at its own deadline") and gate-sweep.test.ts ("hands the gate back when the resume fails to submit, and a later pass retries it").

Your follow-up on this block — that the hand-back is unconditional, and that a throwing releaseGate would mask the submission error — is a real gap; I'm answering that on its own thread.

`${rec.sessionId}:gate:${decision.gateId}`,
);
const prior = held ? await turns.get(held) : null;
if (prior?.resumeOf === found.paused.turnId) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — the replay check verifies only that prior.resumeOf is this paused turn, not that the stored decision is the one being re-sent. If the deadline sweep (or another caller) has already created an abort resume that is still live, a human's approve gets 202 with the abort turn's id and is silently dropped — while docs/api/CHANGELOG.md promises this for "the same decision" only. Comparing prior.envelope.decision (action and feedback) before replaying, and falling through to 409 otherwise, would keep the documented contract.

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.

Taken, in f4b27c2a. New sameDecision(prior, sent) compares the action and the feedback against prior.envelope.decision (the gate id is equal by construction — it is in the idempotency key), normalising both sides with ?? '' because parseGateDecision omits feedback when absent. Anything else falls through to the existing 409 gate_not_pending.

So the sweep's abort followed by a human approve is now a 409 rather than a 202 naming the abort turn, which is what docs/api/CHANGELOG.md promises. Same action with different feedback is also a 409 — the first decision already ran, and reporting that as success would be the same silent drop.

Test: turn-gate-decision.test.ts > "409s on a DIFFERENT decision for a gate already resumed, rather than replaying", which also asserts that the decision which did resume it still replays with its own turn id.

…dict

Two review findings on the gate's prompt/solve path, both in the new code.

The continuation was keyed on the session's LAST decision, not on this
invocation's: a session that answered an earlier gate re-derived that
decision's continuation for every later turn. A fresh `requireApproval`
prompt or solve therefore ran "Human decision: APPROVED..." instead of its
own prompt plus the steer, never called `request_approval`, and bypassed
the gate it had just asked for. The continuation is now carried only when
the invocation actually consumes a decision -- which is the only case the
prompt and solve kinds ever replay, since each of their turns brings its
own prompt.

And that continuation was verdict-leaf text: "call submit_verdict exactly
once". A prompt or solve leaf registers `request_approval` alone, so the
resume was told to call a tool it does not have. `continuationPrompt` and
`decideSeed` take a `verdictTool` flag, true for the verdict kind as
before and false for the two that have no such tool.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
A transient `enqueue` error used to leave the gate marked answered with
nothing able to retry it. `submitResume` compensates by finalizing the
record it had already created, and that record keeps its `resumeOf` --
which `findPausedBySession` read as "the gate was answered", so a human
retry got 409 `gate_not_pending`; on the sweep path the `claimGate` ZREM
had already removed the index member, so no later pass came back to it
either. The gate was unanswerable by anyone.

Two halves, matching the two paths:

- `findPausedBySession` ignores a resume that ended `failed`: it never
  ran, so it answered nothing. Safe for a resume that did run and then
  failed, because the harness owns the gate's durable state and cannot
  flip a decision already recorded there -- re-sending is a retry.
- the sweep hands the claim back (`TurnStore.releaseGate`) at the deadline
  the gate already had when its submission throws, so the next pass
  retries it, oldest-first. The gate-keyed idempotency key is what makes
  that retry converge on one resume.

Also, the decision route's replay now compares the stored decision rather
than only `resumeOf`. The CHANGELOG promises the 202 replay for "the same
decision"; without the compare, a human's `approve` landing after the
sweep's `abort` was answered with the abort turn's id and silently
dropped -- a conflict reported as success. It is a 409 now.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Reviewed at head f4b27c2, the two commits on top of ab8e269. Both address findings from the previous pass, and I checked each against the code it changes at head:

  • The continuation is now gated on decision (harness/src/run-leaf.ts:713), so a fresh gated prompt or solve turn runs its own prompt plus gatePromptNote(); the silent gate bypass the previous pass described is gone, and the new test reproduces exactly that state (a decided gate 0, then a fresh requireApproval submission).
  • verdictTool=false threads through decideSeed to both continuationPrompt sites, and the registration is as claimed: the prompt leaf and produceSolve wire requestApprovalExtension alone, and submitVerdictExtension is added only on the verdict path (run-leaf.ts:1403), so a resumed prompt/solve turn is no longer told to call a tool it lacks.
  • findPausedBySession ignores a failed resume and the sweep hands the claim back, which closes the stranding path. The recomputed score is the same instant toTerminal used — endedAt + gateDeadlineS*1000, with gateDeadlineS already clamped at submission to the tightest of the deployment ceiling, the submission and the record TTL — so the hand-back restores the original deadline rather than extending it.
  • sameDecision compares action and feedback against prior.envelope.decision; parseGateDecision omits feedback when absent and the comparison normalises both sides with ?? '', so a human approve racing a sweep abort now gets the 409 that docs/api/CHANGELOG.md promises instead of the abort turn's id.

One suggestion below, on the hand-back's interaction with a decision that lands while the submission is failing. No must-fix.

Not run here: the packages/control-plane and harness suites — the review environment has no dependencies installed for head, and the program does not execute code from reviewed PRs. The findings are from reading head at f4b27c2, cross-checked against turn-store.ts, turn-handlers.ts and gate.ts.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness/src, packages/control-plane/src, and their tests)
Agent/IDE config (.claude/.vscode): none
Commits: 13 commits, all signed-off: yes
CI status: passing (codeql, dependency-review, deploy-scripts, deploy-scripts-bash32, docs, hadolint, k8s-kind-e2e, lint, microvm-gates, proto, shellcheck, trivy-scan)

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

// the member is the only thing that brings a later pass back to it. Re-added at the deadline
// it already had, which `toTerminal` scored as `paused-at + gateDeadlineS`.
const dueAt = (paused.endedAt ?? deps.now()) + (paused.gateDeadlineS ?? 0) * 1000;
await turns.releaseGate(turnId, dueAt);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — the hand-back is unconditional, so it can put back a gate that was answered while this submission was failing. submitResume finalizes the failed record and releases the gate-keyed idempotency key before it throws; in that window a human POST /decision sees resumed: false, claims the now-free key and resumes the gate successfully. releaseGate then re-adds the member at its (past) score, and the next pass calls submitResume again. That is harmless while the human's resume is still live — the key returns its turn id — but once that resume has gone terminal toTerminal has released the key too, so the pass creates a SECOND resume from the same paused turn and the continuation runs twice: double spend and double side effects for one decision.

Suggested fix: hand the gate back only when it is still unanswered, using the key submitResume would use:

const held = await turns.idempotencyHolder(paused.owner, `${paused.sessionId}:gate:${gateId}`);
if (!held) await turns.releaseGate(turnId, dueAt);

Second, smaller point on the same block: if releaseGate itself throws (a Redis error is not unlikely here — it may be what failed the enqueue), throw err never runs, so the log below reports the hand-back's error rather than the submission failure that caused it, and the gate stays out of the index. Worth logging the original before the re-add, or wrapping the hand-back so the first error survives.

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.

Real, and worse than the key can fix. Guarded in c18867ac, but on durable state rather than on idempotencyHolder: toTerminal releases the gate-keyed key as soon as the resume finishes, so by the time a later pass looks at the handed-back member the key is empty and the double resume happens anyway. resumeOf on the record is durable, so the guard reads that instead —

const found = await turns.findPausedBySession(paused.sessionId);
if (found?.paused.turnId === paused.turnId && !found.resumed) await turns.releaseGate(turnId, dueAt);

the same question decideGate asks. A newest-paused that is some other turn means the chain moved on (somebody's resume ran and paused at a gate of its own, which carries its own member), and a resumed marker means the gate is answered; neither hands back. The pass's own failed resume still does not count, because findPausedBySession skips a failed one — so the ordinary enqueue failure keeps retrying as before.

The hand-back also has its own try/catch now, for the second half of your point: a throwing releaseGate logged its own error and swallowed the submission's. It now logs gate hand-back failed: separately and throw err always runs.

Test: gate-sweep.test.ts > "does NOT hand the gate back when it was answered in the failing window" — a finished human resume (key already released), the sweep's submission failing, then asserting dueGates stays empty and a later pass enqueues nothing. Checked it fails with the guard removed.

One window this does NOT close, pre-existing and unrelated to the hand-back: a replica that dies between submitResume's enqueue and its claimGate. The member survives, and a later pass steps over the by-then-terminal key and builds a second resume. claimGate's doc comment already records losing that race as the accepted failure mode; closing it needs the sweep to check resumed on the normal path, which is a 50-record scan per gate per pass.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Follow-up review at f4b27c2a (was ab8e2698). The two new commits close the three problems from the last round, and I verified each fix against the code:

  • Fresh turn after a decided gate. planLeafGate attaches a continuation only when the invocation carries a decision (run-leaf.ts:713), so a fresh gated prompt/solve runs its own prompt plus gatePromptNote() and takes nextGateId from the request entries. The new test seeds a decided gate and asserts the task, not the old continuation.
  • No submit_verdict for prompt/solve. continuationPrompt takes verdictTool, and planLeafGate passes false; the verdict path keeps the default. Neither prompt nor solve registers submitVerdictExtension.
  • A failed resume no longer answers the gate. findPausedBySession ignores a resume that ended failed, and the sweep hands the claimed member back at its original score (releaseGate), so a transient enqueue error is retried instead of stranding the gate. The compensating release of the gate-keyed idempotency key was already there.
  • Replay is for the same decision. sameDecision compares action and feedback, so a human approve landing after the sweep's abort is a 409 gate_not_pending, not a 202 for the abort turn.

One problem remains in the same area as the last round: a second gated async turn admitted while a gate is open parks on the first turn's gate, and the decision resumes the second turn, stranding the first (inline comment). The rest are suggestions and nits that carry over unchanged.

Not run here: the packages/control-plane and harness suites (this review environment has no dependencies installed for the head); the findings are from reading head. CI is 18/18 green.

Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (harness/src, packages/control-plane/src, their tests), OpenAPI/docs
Agent/IDE config (.claude/.vscode): none
Commits: 13, all signed-off: yes
CI status: passing (18/18)

Two one-line docs items, left in the body because their lines are outside the diff: docs/reference/configuration.md:27 still says MOCA_ASYNC_QUEUED_PER_OWNER and MOCA_TURN_SUMMARY_BYTES are "the exceptions" that use countEnv — MOCA_GATE_DEADLINE_S does too (main.ts:380), so it is three; and docs/harness/reference/leaf-and-envelope.md:32's "Optional fields on any envelope" list does not carry requireApproval (kind-scoped, exactly like the maxTurns (verdict leaf only) entry beside it).

Assisted-By: Claude Code

const { turns } = service(deps);
const decision = parseGateDecision(ctx.body);

const found = await turns.findPausedBySession(rec.sessionId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix. A second gated async turn is accepted while a gate is open, and that second turn is the one a decision resumes.

submitTurn never checks for a paused turn, so with a distinct idempotencyKey (documented in dispatch-archetypes.md as queueing several turns on one session) T2 is admitted while T1's gate 0 is open. The leaf then does the right thing for a re-POST of the same envelope — gateShortCircuit parks it on the pending gate — but for a different turn that means T2 reports T1's gateId and summary as its own paused result, and this call answers with the newest paused turn, T2. The human's decision therefore resumes T2, which has never run its own prompt (a continuation replaces it), while T1 stays paused with no way to answer it — and with the default MOCA_GATE_DEADLINE_S = 0, no sweep either.

Repro: T1 POST /v1/sessions/{id}/turns {async:true, kind:'prompt', prompt:'A', requireApproval:true, idempotencyKey:'a'} → paused at gate 0; T2 the same with prompt:'B', idempotencyKey:'b' → also paused at gate 0 (with T1's summary); POST .../decision {gateId:0, action:'approve'} → 202 resuming T2, T1 stranded.

Suggested fix: refuse a requireApproval submission while the session has a paused turn (one findPausedBySession read in submitTurn, guarded on parsed.envelope.requireApproval), or make the decision route resume the turn whose leaf result names decision.gateId rather than the newest paused one. The harness cannot tell a fresh turn from a re-dispatch of the same envelope, so the control plane is where this has to be enforced.

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.

Confirmed and fixed in 5ea3050f. I checked the premise first: submitTurn never read findPausedBySession — decideGate was the only caller — so a distinct idempotencyKey was all it took, and your trace is exactly right down to the second turn reporting the first's gateId as its own.

Took your first option, because the second one (resolve the decision against the turn whose result names decision.gateId) answers the decision correctly and still leaves two turns racing one gate in the harness's session state.

submitTurn now refuses a gated submission while the session has an unanswered paused turn, with a new gate_pending (409) naming it. Placed with the other pre-enqueue refusals, before reserveOpenSlot, so a refusal burns no quota slot. Both spellings of "gated" are covered — requireApproval, and item.require_approval for the converge kind, which has the same exposure.

Deliberately narrow: an ungated turn on the session is still admitted, since it never calls request_approval and so cannot park on the open gate. A session must stay usable while a human thinks.

Tests in turn-gate-decision.test.ts > "one open gate per session": the refusal (asserting countOpen stays 0 and the first turn's gate is still answerable), the converge spelling, an ungated turn admitted, and a gated turn admitted once the gate has been answered. openapi.yaml, CHANGELOG.md 1.36.0 and the requireApproval field description carry the rule.

expect(await deps.turns.dueGates(deps.nowOf())).toEqual(['t-1']);
});

it('a human decision and the sweep converge on one resume', async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. This test is sequential: the decision runs first, clears the index, and sweepGates then has nothing to claim. It pins "an approved gate is not also expired", not the race the ZREM and the gate-keyed idempotency key exist for. Two properties are still untested:

  • two sweepGates passes over the same due gate — only one may enqueue;
  • a sweep and a decideGate submitted together — both 202s, one turn.

The suite has real Redis, so Promise.all([sweepGates(d), sweepGates(d)]) and Promise.all([sweepGates(d), HANDLERS.decideGate!(...)]) asserting exactly one queued turn would pin both without new machinery.

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.

Fair — that test pins the outcome of a decision having cleared the index, not a race. Added two real ones in c18867ac, and kept the sequential one, since it is the only check that an approved gate is not also aborted thirty seconds later:

  • "two passes racing on one gate resume it once" — Promise.all([sweepGates(deps), sweepGates(deps)]), asserting the counts sum to 1 and the queue holds one entry. The fake's zRem returns the count it actually removed, so claimGate's CAS really does pick a loser.
  • "a sweep racing a human decision produces one resume" — Promise.all of sweepGates and decideGate, asserting one queue entry, that it is a resume of the paused turn, and that the decision either names that same turn id or came back gate_not_pending. Both interleavings are valid; what must hold either way is one resume, which is what the gate-keyed idempotency key <sessionId>:gate:<gateId> buys.

Also extracted the route-built session setup into a gatedSession() helper so the new test and the existing convergence test share it.

* pending gate worth finding, and the alternative (a second index keyed by session) would have to
* be kept in step with every transition.
*/
async findPausedBySession(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. The 50-turn scan bounds the search for the paused turn, so a gate becomes unanswerable through POST /decision once the session has 50 newer turns. That is reachable here: ungated turns keep running while a gate is open, and with MOCA_GATE_DEADLINE_S = 0 (the default) nothing else answers the gate. Either state the bound in the route's docs, or keep paging the ordered session index until the paused record is found (a bounded extra read rather than the full week-long walk the comment is avoiding).

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.

Documented rather than paged, in 9dcb174d — a shortcut: note on findPausedBySession:

a gate stops being findable once scan NEWER turns exist on the session, which reads as 409 gate_not_pending on the decision route and as a gate the sweep's claimGate has already dropped — a refusal, never a decision landing on the wrong turn. Hard to reach now that submitTurn refuses a second GATED turn while one is open: it takes 50 ungated turns on the same session while a human thinks. Upgrade to a per-session paused marker written by toTerminal if a caller ever needs to hold a gate open across a long run of other turns.

Two reasons for deferring rather than paging: the failure mode is a refusal, not a wrong answer, and the one-open-gate rule added in 5ea3050f for the other finding shrinks the window to "50 ungated turns while a gate is open". The real fix is a sh:cp:paused:<sessionId> marker written on the paused transition and cleared by submitResume — a second index to keep in step with every transition, worth it when a caller needs it, not before.

Comment thread docs/api/openapi.yaml
alone: the resumed turn's envelope -- prompt, model, credential name, sandbox tier, caps --
is copied from the paused record, so resolving a gate cannot change what the turn runs.

Answers `202` with a NEW turn id, linked to the paused one by `resumeOf`. A paused turn is

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. This and docs/harness/reference/leaf-and-envelope.md promise a link no route returns. resumeOf is a turn-record field only: TurnStatus has no such property, and GET /v1/sessions/{id}/turns/{turnId} returns turnId, state, attempts, cancelRequested and result. A client polling the resume, as this paragraph tells it to, cannot see what it resumes. Either expose resumeOf on TurnStatus (one line in the handler plus the schema), or reword both places to "the 202 names the resume turn".

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.

Right — the record carried resumeOf and the read never showed it, so the link the decision route promises was only visible in the audit log. Exposed in 9dcb174d:

  • getTurn spreads it when present: ...(turn.resumeOf ? { resumeOf: turn.resumeOf } : {}), next to cancelRequested.
  • TurnStatus.resumeOf added to openapi.yaml — "the paused turn this one answers the gate of; present only on a resume".
  • A test in turn-gate-decision.test.ts asserts it on the status read of a decision's turn and asserts it is absent on an ordinary turn, so the conditional spread stays conditional.

Omitted rather than null for the ordinary case, matching how every other optional field on that body behaves.

}
// `true` only: an absent flag and `false` mean the same thing, and storing both would put two
// spellings of "no gate" on the wire (the same rule the `converge` normalisation below follows).
const gated = b.requireApproval === true ? { requireApproval: true as const } : {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit. requireApproval is validated and then dropped for the verdict kind: gated is spread only into the prompt and solve envelopes, and no error is raised. A client that sends it alongside item believes the turn is gated and gets an ungated turn. Refuse it for the verdict kind with a message pointing at item.require_approval (which the OpenAPI description already names), rather than accepting and ignoring it.

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.

Agreed, and worse than cosmetic: silently dropping it runs an ungated turn for a caller who asked for a gate. Now a 400 (9dcb174d), in the verdict branch of parseTurnSubmission:

if (b.requireApproval === true) {
  throw new CpError(
    'invalid_request',
    'requireApproval applies to the prompt and solve kinds; a converge leaf asks for its gate with item.require_approval',
  );
}

Refused rather than honoured, because item.require_approval is the verdict kind's own flag and has been since ADR-0016 — accepting both spellings would mean two ways to ask for the same gate on one kind. The kind's own flag still parses, and the requireApproval description in openapi.yaml now says so.

Two existing tests asserted the old behaviour and were updated: turn-record.test.ts's "ignores it on a converge leaf" became "refuses it on a converge leaf, which has item.require_approval", and the gate-deadline clamp test in turn-handlers.test.ts moved from a converge body to a prompt body.

Comment thread docs/api/openapi.yaml
and lets it try something else, `abort` ends the leaf with `status: "aborted"`.
feedback:
type: string
maxLength: 4096

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit. maxLength counts characters, but parseGateDecision bounds BYTES (Buffer.byteLength(feedback) > 4096), so a 4096-character multi-byte note passes this schema and is refused with 400 invalid_request. test/openapi-contract.test.ts already states the rule for exactly this case — "maxLength counts characters, so it would admit values the server refuses. The limit lives in the description instead." Drop the maxLength and describe "4096 UTF-8 bytes".

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.

Correct — maxLength is characters in JSON Schema and the check is on UTF-8 bytes, so a generated client would accept a 2000-character string of multi-byte text that the server refuses. Noted on GateDecision.feedback in 9dcb174d rather than changed: the server check has to stay in bytes (it is what bounds the record), and there is no byte-length keyword to say it in, so the schema keeps the character bound as the loose one and the description carries the exact rule.

.filter((m) => (lo.exclusive ? m.score > lo.bound : m.score >= lo.bound))
.sort((a, b) => b.score - a.score);
// LIMIT applies AFTER the sort, so the direction decides which page a bounded read gets.
.sort((a, b) => (opts.REV ? b.score - a.score : a.score - b.score));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit. Real ZRANGE ... BYSCORE orders equal scores lexicographically by member (reversed under REV); this fake falls back to insertion order. Equal scores are not hypothetical here: the gate index scores are now + gateDeadlineS * 1000, so two turns paused in the same millisecond tie, and findPausedBySession's newest-first read has the same exposure. A test that depends on which of two tied members comes first would pass here and could differ on real Redis. Sort on (score, value) in both directions.

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.

Good catch — a score tie paged in insertion order here and in member order in production, so a bounded dueGates read could have passed on an order real Redis never gives. Fixed in 9dcb174d:

/** Byte-wise, as Redis compares members of equal score; `localeCompare` would not be. */
const byMember = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);

applied as a.score - b.score || byMember(a.value, b.value) forward and reversed under REV, so the tiebreak follows the sort direction the way Redis's does. localeCompare deliberately avoided: it is locale-dependent and would not match Redis's byte comparison.

Pinned by a new test in turn-store-gate.test.ts — two gates parked in the same millisecond, inserted t-b then t-a, come back ['t-a','t-b'], and the LIMIT 1 page is ['t-a']. It fails on the old fake.

A gate is SESSION state: the harness derives it from the session's own durable
entries, so a second gated turn admitted while one is open parked on the OPEN
gate, reported that gate id as its own, and -- being the newest paused turn --
was the turn a decision resumed. The first turn stayed `paused` with nothing
able to answer it, and no sweep either at the default MOCA_GATE_DEADLINE_S=0.

`submitTurn` now refuses a gated submission while the session has an unanswered
paused turn, with a new `gate_pending` (409) naming that turn. Refused before
the open-slot reservation, like every other refusal on the path, so nothing is
left behind. Narrow by design: an ungated turn never calls `request_approval`,
so it cannot park on the open gate and is still admitted.

Both spellings of "gated" are covered -- `requireApproval` for prompt and solve,
`item.require_approval` for converge. And `requireApproval` sent WITH a converge
submission is now 400 `invalid_request` rather than a silently dropped flag,
which ran an ungated turn for a caller who asked for a gate.

Also reports `resumeOf` on the turn status read: a gate's answer is always a new
turn, and openapi promised the link back without any route serving it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The hand-back added for the last review round was unconditional, which bought a
double spend: a human decision can land in the window a sweep's `submitResume`
failed in, and re-adding the member then lets a later pass build a SECOND resume
from the same paused turn -- the continuation running twice for one decision.

The gate-keyed idempotency key cannot answer "was this gate answered?", because
`toTerminal` releases that key as soon as the resume finishes. `resumeOf` on the
record is durable, so the guard reads it: hand back only when
`findPausedBySession` still reports THIS turn, unresumed. The pass's own failed
resume does not count (a `failed` resume is skipped), so the ordinary enqueue
failure still hands back and still retries.

The hand-back also runs in its own try/catch now: one that throws must not
replace the submission error that caused it.

Plus two race tests the reviewer asked for: two sweeps on one gate (the ZREM is
the lock) and a sweep against a concurrent decision (the gate-keyed key is),
both asserting exactly one resume.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
- openapi: `gate_pending` in the error enum and on submitTurn's 409, the new
  `TurnStatus.resumeOf`, the one-open-gate rule under `requireApproval`, and a
  note that `feedback`'s 4096 is BYTES where `maxLength` counts characters.
- CHANGELOG 1.36.0: the two new refusals and the new status field.
- configuration.md: three env vars use the strict `countEnv` parser, not two --
  `MOCA_GATE_DEADLINE_S` is the one the list missed.
- leaf-and-envelope.md: `requireApproval` is on the optional-fields list, scoped
  to the prompt and solve leaves.
- turn-store: a `shortcut:` note on `findPausedBySession`'s 50-turn scan, which
  bounds how many newer turns a session may have before its gate stops being
  findable -- a refusal, never a decision landing on the wrong turn.
- the fake Redis breaks a zset score tie BY MEMBER, as real Redis does, so a
  bounded page cannot come out in insertion order in tests and member order in
  production; pinned by a `dueGates` tie test.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Large, and unusually well argued: the body states what it does not prove, and each of the four promises holds where the code can show it.

  • The gate is decided before the lease. planLeafGate runs at run-leaf.ts:588 (solve) and :740 (prompt), and selectPoolSandbox is first reached at :779; the verdict short-circuit is at :1325, above its own lease at :1342. The two selectPoolSandbox-is-never-called tests are the right shape for that promise.
  • A decision never reopens the paused turn. submitResume builds a new record with resumeOf and copies cfg, credentialName, model, modelLimits, sandboxTier and caps from the paused record, not from the live session, so a PATCH during the wait cannot move it.
  • The tightest ceiling wins. resolveGateDeadline filters non-positive bounds and takes the minimum, and the record-TTL clamp is applied only when a deadline already exists — which is what keeps an ungated deployment's turns deadline-free.
  • Never approve. parseTurnSubmission refuses any other onTimeout, and the sweep passes paused.onTimeout ?? 'abort'.

I went looking for races in the two places I expected them and could not construct one: claimGate's ZREM really is a CAS (the fake redis returns the removed count, so a fake that always claimed would be caught), a sweep racing a human converges on one resume through the gate-keyed claimKey, and the losing sweep's claimGate returns 0. The hand-back re-reads findPausedBySession before re-indexing, which is the check that keeps a human's decision from being replayed.

No must-fix. Four notes below: two behavioural edge cases, one consistency argument against the PR's own principle, one nit.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness gate/run-leaf/run-turn; control-plane turn-handlers/turn-store/turn-record/gate-sweep/errors/routes/main), docs (openapi, CHANGELOG, change-policy, configuration, deploy manifests), tests
Agent/IDE config (.claude/.vscode): none
Commits: 16 commits, all signed-off: yes
CI status: passing (18/18 at head 9dcb174d)
Not run locally: the control-plane and harness suites — no node_modules in this sandbox. The above is from the head source and the green CI at this SHA. I agree with the body that the live check worth doing is the requireApproval: true, gateDeadlineS: 60, onTimeout: 'reject' submission, since no gate path here has met a real model, lease or Kind cluster.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

// the control plane is the only side that can tell a fresh submission from a re-dispatch of the
// same envelope. Before the reservation, like every other refusal on this path: nothing left
// behind. Only for a GATED submission -- an ordinary turn on the session never touches the gate.
if (asksForGate(parsed.envelope)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — this check is check-then-act, and the window is the exact case it is here to prevent. Sequence: submission B asks for a gate; findPausedBySession finds nothing paused because A is still queued; A reaches paused and toTerminal releases its idempotency key; B's claimKey at :350 is therefore fresh; B is admitted, and because the harness derives the gate from session entries it parks on A's open gate and reports that gate id as its own. decideGate then resumes the newest paused turn — B — leaving A paused with nothing that can answer it and, at the default MOCA_GATE_DEADLINE_S=0, no sweep either. The harness re-validates, so nothing wrong can be approved; what is lost is A.

Suggested fix: narrow it to a lock rather than a read — a per-session admission key (SET sh:cp:session:<id>:gate-admit NX) taken before the reservation and released by submitResume/claimGate when the gate is answered — or, cheaply, a second findPausedBySession immediately before turns.create.

Why now: it is the only 202 in this PR that can leave a gate nobody can answer.

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.

Fixed in 0ea9258 — but with a third approach, because both suggestions here have a cost I did not want to pay.

A SET NX admission key needs a release on every terminal transition. Leak it once (a crashed worker, a reaper-written lost) and that session can never gate again — a worse failure than the one it closes. And "read paused again just before turns.create" narrows nothing: the first turn is still queued or running for the whole of its run, so the second read sees exactly what the first did.

So TurnStore.findGateHolder instead. It reuses the session-index scan findPausedBySession already walks, and reports two kinds of holder:

  • a turn already paused and unresumed, and
  • a gated turn still queued or running — it has not reached its request_approval call yet, but it will park on that same session gate when it does.

An ungated in-flight turn is not a holder: it never calls request_approval, so it cannot take the gate. That is what keeps ordinary traffic on a session unaffected, and there is a test for it.

No new key, no release path. The window shrinks from "the whole of the first turn's run" (seconds to minutes) to "the two Redis round-trips between the read and turns.create" — disclosed in a shortcut: comment on the method, with the upgrade named: a per-session admission lock with a release on every terminal transition, if a caller ever submits gated turns concurrently on one session. No on-ramp in this repo does.

Two details worth recording, both of which the tests pin:

  • A resume is itself a gated non-terminal turn while it runs, so an answered gate still reports a holder until the resume lands. Correct — that resume can pause at a gate of its own.
  • A failed resume did not answer the gate it links to, so the gate still has a holder. Same rule findPausedBySession uses.

Tests: findGateHolder gets its own describe block in turn-store-gate.test.ts (queued gated turn; ungated in-flight ignored; paused → its queued resume → null once the resume is done; failed resume still reports the gate), and turn-gate-decision.test.ts gains refuses a second gated turn while the first is still QUEUED.

Comment thread harness/src/gate.ts
`Revise accordingly. You may call request_approval again when ready, or call submit_verdict when done.`,
verdictTool
? `Revise accordingly. You may call request_approval again when ready, or call submit_verdict when done.`
: `Revise accordingly. You may call request_approval again when ready, then stop.`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — on a reject, this names request_approval, but the tool is registered only when the envelope carries requireApproval (run-leaf.ts:958-960 for a prompt leaf, :1191-1193 for solve). planLeafGate produces a continuation for any envelope with a decision (run-leaf.ts:940), so a sync /v1/runs caller who re-POSTs decision without requireApproval — which docs/harness/reference/leaf-and-envelope.md now describes as "A prompt or solve envelope takes the same decision field", with no mention that the flag must come with it — gets a resumed leaf steered at a tool it does not have.

Suggested fix: register the extension on env.requireApproval || env.decision !== undefined, or pass "may re-gate" into continuationPrompt and drop the sentence when there is no tool.

Why now: it is the failure the verdictTool flag exists to prevent, one level out.

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.

Right, and fixed in 146486c by registering the extension rather than by dropping the continuation sentence — dropping it would regress the main gated path, where "you may call request_approval again" is exactly what a rejected leaf should hear.

Both registration sites now key on env.requireApproval || env.decision !== undefined: runPromptLeaf's exec({...}) gate field, and realProduceSolve's extension list. Costs nothing on the ungated path — planLeafGate already reads the durable session for any invocation that is gated or carries a decision, so the extra registration adds no Redis work.

Red-green proof: new test registers the tool for a resume carrying a decision WITHOUT requireApproval in run-leaf-gate-kinds.test.ts (envelope with only decision, asserts input.gate is defined, nextGateId === 1, and the prompt carries both Human decision: REJECTED and request_approval). Reverted the prompt-leaf condition → 1 failed / 11 passed; restored → 12 passed.

docs/harness/reference/leaf-and-envelope.md now says requireApproval need not be repeated with a decision, and why.

// CP-side scheduling, so they stay OFF the envelope: the harness has no sweep and no clock for
// this -- a gate's deadline is enforced by whoever is still running when the gate is not.
if (
b.gateDeadlineS !== undefined &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — gateDeadlineS/onTimeout go into common, so they are accepted on a turn that never asks for a gate: submitTurn stores them, and nothing reads them, because toTerminal arms the index only on paused. That is the silently-ignored flag this PR refuses one branch down — requireApproval on a converge leaf is a 400 "instead of a silently dropped flag, which ran an ungated turn for a caller who asked for a gate". A client that sends gateDeadlineS without requireApproval gets a 202 and no deadline, and only learns it when the gate it expected never expires.

Suggested fix: refuse them when asksForGate(envelope) is false, with the same 400 shape and wording, or document on both fields that they are inert without a gate.

Why now: the principle is already in the PR; this is the one place it is not applied.

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.

Agreed — fixed in 0ea9258. gateDeadlineS or onTimeout on a turn that asks for no gate is now 400 invalid_request, for the same reason requireApproval on a converge leaf is refused: both are silently inert otherwise.

Concretely: toTerminal arms the gate index only on the paused transition, so an ungated turn stores those two fields and nothing ever reads them. A caller who set a deadline would get their 202 and learn it had none only when the gate they expected never expired.

The predicate is one exported asksForGate, moved from turn-handlers.ts into turn-record.ts so the parse-time refusal and the admission guard cannot drift — it covers requireApproval for prompt/solve and item.require_approval for the converge kind, and both spellings are accepted by the new test.

Two pre-existing tests were sending a bare gateDeadlineS/onTimeout and now assert the new behaviour instead: parses gateDeadlineS and onTimeout sends requireApproval: true, and stores no deadline when neither the deployment nor the submission asks for one sends item.require_approval: true. docs/api/openapi.yaml and the API changelog both record the 400.

}
throw err;
}
resumed += 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit — this counts a resume the sweep may not have created. If a human's submitResume claims the gate key after our claimGate and before our own submitResume, the latter's claimKey returns the human's turn id and we still increment resumed. The value is only logged and asserted, so it is a reporting nit; having submitResume report whether it created the turn (it already knows, from claim.fresh) would make the counter mean what its name says.

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.

Fixed in 0ea9258. submitResume now returns { turnId, created }, and the sweep increments only when created is true.

The case that matters: a human's submitResume claims the gate-keyed idempotency key ${sessionId}:gate:${gateId} between our claimGate and our own submission, so our claim replays their turn id back to us. Counting that reports a gate this sweep expired when a human answered it.

decideGate destructures turnId and ignores the flag — a replay there is already the right answer to return.

Test: does not count a resume a human created holds the gate key for a t-human resume, then asserts sweepGates(deps) is 0 and the queue is empty.

…hole run

A gate is session state the harness derives from the session's durable
entries, so two gated turns on one session collide. The admission guard
read only `paused`, which left the first turn's entire run -- seconds to
minutes -- open for a second gated turn to be admitted. `findGateHolder`
walks the session index as `findPausedBySession` does and reports a gated
turn still `queued` or `running` as a holder too; an ungated in-flight
turn is not one, so ordinary traffic on a session is unaffected. The
residual window is now the two Redis round-trips before `turns.create`,
recorded as a `shortcut:`.

`gateDeadlineS` and `onTimeout` on a turn that asks for no gate are now
400 rather than silently inert: `toTerminal` arms the gate index only on
the `paused` transition, so a caller who set a deadline would have
learned it had none only when the gate never expired. The predicate is
one exported `asksForGate`, shared by the parse and the guard so they
cannot drift.

`submitResume` reports whether it created the turn, so the sweep counts
only gates it actually expired and not a human's resume it replayed.

Refs rossoctl#393

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The reject continuation tells the model it "may call request_approval
again", and a sync caller may re-POST `decision` without repeating
`requireApproval`. Without the tool that resumed leaf is steered at a
tool it does not have -- the same failure `verdictTool` exists to
prevent, one level out. Costs nothing on the ungated path: `planLeafGate`
already reads the durable session for any invocation carrying a decision.

Refs rossoctl#393

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik
cwiklik requested a review from clawgenti November 21, 2026 01:44

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Reviewed at head 146486c, the two commits on top of 9dcb174. Every behavioural note from the last pass is closed, and the tests hold each one closed rather than just the code change. I re-ran both suites locally instead of leaning on CI.

  • The check-then-act window is narrowed to the shortcut its own comment admits. findGateHolder reports a gated turn that is still queued or running, so a second gated submission is refused through the whole of the first one's run, not only after it parks. The residual race (two round-trips between the read and turns.create) is written down in the method's shortcut: block and is now seconds instead of the whole run; the ungated branch continues, so ordinary traffic pays nothing.
  • submitResume's created split is threaded everywhere it matters. The decision handler takes turnId, the sweep counts only created, and the replay path returns created: false. The new sweep test holds the gate key in exactly the state a human resume is in between its own claim and its claimGate, which is the interleaving that used to overcount.
  • gateDeadlineS/onTimeout on an ungated turn is refused with the same reasoning as requireApproval on a converge leaf, and both spellings of "gated" satisfy it, including item.require_approval.
  • The harness registers request_approval for a decision-carrying leaf in both the prompt and solve kinds, and the new test asserts the tool is in the stack and that the reject continuation names it.

No must-fix. One suggestion, in the new registration predicate; everything else is green.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness run-leaf and its gate-kind tests; control-plane turn-handlers/turn-store/turn-record/gate-sweep and their tests), docs (openapi, CHANGELOG, leaf-and-envelope.md)
Agent/IDE config (.claude/.vscode): none
Commits: 18 commits, all signed off: yes
CI status: 16 green at head 146486c; the check and deploy-scripts jobs are still running

Verified by: packages/control-plane full vitest run against a local Redis — 2109 passed, 4 skipped, 0 failed (without Redis, 9 e2e tests fail on ECONNREFUSED, which is environmental, so I started one). tsc --noEmit clean. harness run-leaf-gate-kinds.test.ts 12/12, after building the pi-fork submodule. prettier --check clean on every changed .ts/.yml/.md. A throwaway probe (deleted afterwards) backs the suggestion: decision: null on an otherwise ungated prompt leaf gives input.gate = {"capture":{},"nextGateId":0}, where the same leaf with no decision key gives undefined.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Comment thread harness/src/run-leaf.ts Outdated
// resumed leaf is steered at a tool it does not have -- the same failure `verdictTool` exists
// to prevent, one level out. Costs nothing on the ungated path: `planLeafGate` already read
// the session for any invocation carrying a decision.
...(env.requireApproval || env.decision !== undefined

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — env.decision !== undefined also matches a JSON null, and planLeafGate treats that differently: its own guard is falsy (if (!env.requireApproval && !env.decision) return { kind: 'run', nextGateId: 0 }), so a leaf that sends "decision": null gets request_approval registered with nextGateId: 0 without the session ever being read. Probe on this head: decision: null → input.gate = {"capture":{},"nextGateId":0}; no decision key → undefined. That id is gateRequests.length everywhere else (gate.ts), so on a session that already has a gate the model's request is appended as gate 0, which computeGateState counts as already decided — the request is silently answered by an old decision, or the numbering is corrupted for the next gate.

Suggested fix: match planLeafGate's predicate in both places — env.decision != null (or !!env.decision) here and at line 1199 — so "carrying a decision" means the same thing to the registration and to the plan that computes nextGateId. Why now: this line is what lets a decision-only resume gate again, and a null decision is the one input where the two predicates disagree.

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.

Good catch, and the probe is right — fixed in 3d261d8.

Both sites now use !!env.decision, which is planLeafGate's own !env.decision inverted, so "carrying a decision" means one thing to the registration and to the plan that computes nextGateId. Confirmed against run-leaf.ts:678 before editing: a null decision takes the early return, so the session is never read and nextGateId stays 0 — and gate.ts numbers every request by gateRequests.length, so a 0 on a session that already has a gate is either silently answered by the old decision or corrupts the numbering for the next one.

Test: treats a null decision as no decision, as planLeafGate does — pendingGate(sid) so the session genuinely has a gate, envelope carries only decision: null, asserts input.gate is undefined and that read was never called. Red-green: reverted the prompt-leaf predicate → 1 failed / 12 passed; restored → 13 passed, and 43 passed across the three gate suites.

No docs change: decision: null is "no decision", which is what the envelope reference already says absent means.

The two registration sites keyed on `env.decision !== undefined`, which
matches a JSON `decision: null`; `planLeafGate`'s own guard is
`!env.decision`, which does not. A leaf sending `decision: null` without
`requireApproval` therefore got `request_approval` registered with
`nextGateId: 0` and the durable session never read -- so on a session
that already has gates the model's request is appended as gate 0, which
`computeGateState` reads as already decided.

Both sites now use `!!env.decision`, the same predicate the plan that
computes `nextGateId` uses.

Refs rossoctl#393

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik

cwiklik commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@ingpaolodettori-dev — ready for another look when you have a moment. Merge is blocked only on your CHANGES_REQUESTED from round two; everything it asked for is in, and six commits have landed since it.

Since your review:

Commit What
5ea3050f One open gate per session — a second gated submission on a session with a pending gate is refused gate_pending
c18867ac A swept gate is handed back only while it is still unanswered, so a failed resume cannot double-spend one a human answered
9dcb174d The gate contracts the round found undocumented (openapi + API changelog)
0ea9258c That gate hold now covers a gated turn still queued/running, not just paused; gateDeadlineS/onTimeout on an ungated turn is 400 instead of silently inert; the sweep counts only gates it actually expired
146486ca request_approval registered for a leaf carrying a decision, so the reject continuation's "you may call it again" is callable
3d261d8e decision: null is not a decision — the registration predicate now matches planLeafGate's

Every clawgenti finding across all three rounds has a threaded reply on its own comment with the commit, the reasoning, and the red-green note. The two places I did not take the suggestion as written are both explained in-thread: the gate-holder TOCTOU (a SET NX admission key needs a release on every terminal transition — leak it once and the session can never gate again, so it closes a narrow window by opening a permanent one), and the 50-turn session-index scan, which stays bounded with the limit recorded in a shortcut: comment.

CI is green at 3d261d8e: 18 checks, 0 failures, including k8s-kind-e2e.

Assisted-By: Claude Code

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review at 3d261d8e. The new commit treats a JSON decision: null as no decision on both the prompt and solve paths, matching planLeafGate's !env.decision, and pins that no session is read and no gate tool is registered. That part is correct.

Two must-fix findings:

  1. The deadline path is inert. pausedGateId reads a top-level result.gateId off the stored leaf result, but toResultRecord (harness/src/leaf-result-store.ts:77) stores {status:'paused', gate:{gateId, summary, proposed_action}} and no writer sets a top-level id. sweepGates reads that null as "result not readable yet" and continues, so no gate is ever resumed by its deadline — MOCA_GATE_DEADLINE_S and per-submission gateDeadlineS never fire, and each due gate is re-read every 30 s until its record TTL expires. decideGate's wrong-gateId refusal is likewise unreachable, so a stale id is accepted and spawns a resume the harness ignores. CI is green because the fixtures seed the flat shape no producer writes.
  2. Sync solve gates lose the decision when the session id is mapped. planLeafGate/appendGateDecision use the raw env.sessionId, but realProduceSolve opens its Pi session under leafSessionId(env) (toSessionId of tenant/sessionId). With a tenant on an unauthenticated /runs envelope, or a sessionId outside [A-Za-z0-9._-] (e.g. the documented run-1/item-1), the resume reads a different session, finds no pending gate, and runs the fresh prompt plus gatePromptNote() instead of the continuation — approve re-asks for approval and abort does not abort. Async turns (UUID ids) are unaffected; the prompt kind matches because it is opened raw too.

Also: decideGate drops submitResume's created: false, so a human decision that loses the gate key to the sweep is answered 202 with the sweep's turn id and the differing action is silently dropped; the sweep/decision test fixtures should be seeded from the toResultRecord shape so they cannot mask the first finding; and GateDecision.gateId in openapi.yaml points at result.gateId, while the status read exposes the nested result.gate.gateId.

Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (control plane: turn store, handlers, gate sweep, records, errors; harness: run-leaf, gate, request-approval), OpenAPI + docs, deploy env
Agent/IDE config (.claude/.vscode): none
Commits: 19, all signed-off: yes
CI status: passing (17/17)

Not run here: the packages/control-plane and harness suites (no dependencies installed for this checkout). Findings are from reading head 3d261d8e, cross-checked against harness/src/leaf-result-store.ts, harness/src/run-leaf.ts, packages/control-plane/src/turn-result.ts, packages/server/src/server.ts and the harness /runs envelope path.

Assisted-By: Claude Code

export async function pausedGateId(deps: CpDeps, paused: TurnRecord): Promise<number | null> {
if (!deps.leafResults) return null;
const result = await readLeafResult(deps.leafResults, paused.sessionId, paused.turnId);
return typeof result?.gateId === 'number' ? result.gateId : null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix. readLeafResult returns the record the harness stored, and toResultRecord (harness/src/leaf-result-store.ts:77-88) writes a paused result as {status:'paused', gate:{gateId, summary, proposed_action}} — the id is nested under gate; no writer sets a top-level gateId (that shape exists only on the in-process LeafResult a sync /runs caller gets back). So this returns null for every real paused turn.

Two consequences. sweepGates (gate-sweep.ts:45-51) reads null as "result not readable yet" and continues, so no gate is ever resumed by its deadline — MOCA_GATE_DEADLINE_S and per-submission gateDeadlineS are inert, and each due gate is re-read every 30 s until its record TTL expires. And decideGate's mismatch check (:460-467) is unreachable, so a stale/wrong gateId is accepted and spawns a resume the harness then ignores. Read result?.gate?.gateId (or have the harness write the id at both levels) — and see the fixture comment, which is why CI is green.

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.

Confirmed and fixed in f4735aa. pausedGateId now reads result.gate.gateId.

You were right about the blast radius: with the read returning null for every real paused turn, the gateId mismatch check was unreachable and onTimeout was inert — the sweep could not name the gate it was expiring, so it never aborted one. My fixtures are what hid it; see the reply on the fixture comment.

Red/green proof: with the honest pausedResult() fixtures and the old top-level read, nine tests fail across turn-gate-decision.test.ts and gate-sweep.test.ts.

Comment thread harness/src/run-leaf.ts Outdated
): Promise<LeafGatePlan> {
if (!env.requireApproval && !env.decision) return { kind: 'run', nextGateId: 0 };
const store = sharedSessionStore(config?.redisUrl ?? 'redis://localhost:6379');
const state = computeGateState((await store.read(env.sessionId)).map((r) => r.entry));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix (sync solve gates). This reads the session under the raw env.sessionId, and appendGateDecision (:655) re-opens it under the same raw id. That matches a prompt leaf, whose turn is opened raw (runPromptLeaf passes sessionId: env.sessionId to executeTurn). It does not match a solve leaf: realProduceSolve opens its Pi session under leafSessionId(env) (:1094), i.e. toSessionId(tenant ? ${tenant}/${sessionId} : sessionId), and that is the key the gate-request entry is appended to.

Whenever toSessionId changes the id — a tenant on an unauthenticated /runs envelope, or any sessionId outside [A-Za-z0-9._-], such as the documented run-1/item-1 — this read finds no pending gate and returns no continuation. A re-POSTed decision then runs the leaf's fresh problemStatement plus gatePromptNote() instead of the continuation: approve asks for approval again, abort does not abort. Async turns are unaffected (UUID session ids pass through toSessionId unchanged). Use the id the leaf's own session is opened under — pass it in (raw for prompt, leafSessionId(env) for solve) — and pin it with a test that uses a non-clean id.

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.

Confirmed and fixed in 0c0692f, the way you asked: planLeafGate and appendGateDecision now take the session id as a parameter, and each kind passes the id it opens its own Pi session under — raw env.sessionId in runPromptLeaf, leafSessionId(env) in runSolveLeaf.

Pinned by a gated solve leaf > finds the gate of a session id toSessionId rewrote in run-leaf-gate-kinds.test.ts: the envelope id is gate-kinds-solve/slashed, the gate is seeded under leafSessionId({sessionId: raw}), and the test asserts both that produce receives the APPROVED continuation and that the decision entry landed on that same session. It expect(sid).not.toBe(raw) first, so it cannot quietly stop exercising the rewrite. Reverting the solve call site to env.sessionId fails it.

Also worth noting for the record why this never showed up in the async path: control-plane session ids are UUIDs, which toSessionId passes through unchanged. It was the sync /v1/runs callers using the documented <run>/<item> convention, and any tenant, that hit it.

);
}

const { turnId } = await submitResume(deps, found.paused, decision);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. submitResume returns created: false when its gate-keyed claimKey replayed somebody else's resume, and this line drops the flag. The found.resumed branch above only covers the sequential case: a human approve and the deadline sweep's abort can both read resumed: false, the sweep then wins the key, and this call returns the sweep's turn id — which is 202'd as though the human's different decision had been accepted. sameDecision is only consulted inside the found.resumed branch, so it never sees this race. When created is false, re-read the returned turn and run the same sameDecision test (202 on a match, 409 gate_not_pending otherwise).

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.

Taken, in f4735aa. The tail is now:

if (!created && !replays(await turns.get(turnId), found.paused.turnId, decision)) { ... 409 }

and the found.resumed branch calls the same replays helper, so the replay rule is stated once.

Two notes on the shape of the window, because it is narrower than "claim before create":

  • claimKey steps over a holder whose record is missing, so the loser cannot land on a recordless claim — it would be handed fresh: true instead. The reachable window is between create's hSet and its session-index zAdd: the winner's record is live, so the claim is lost, but findPausedBySession has not seen it yet, so found.resumed was false.
  • A prior of null is therefore not that window but an expired or session-deleted record, and it is still not a replay: 409, whose documented caller move is a re-read, beats 202-ing a decision nobody can show was applied.

Test: 409s when another decision won the gate key between the read and the submit, which reproduces that window by zRem-ing the winner from the session index after its create.

if (result !== null) {
deps.fake.strings.set(
leafResultKey(turn.sessionId, turn.turnId),
JSON.stringify({ status: 'paused', gateId: 0, gate: { summary: 's', proposed_action: 'p' } }),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. This fixture (and :133, and turn-gate-decision.test.ts:66) seeds {status:'paused', gateId, gate:{...}} — a shape no producer writes; toResultRecord nests the id under gate. That is why the pausedGateId must-fix above passes every test. Seed through the harness's toResultRecord shape, or one shared pausedResult(gateId) helper, so the fixtures cannot drift from the writer.

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.

Done in f4735aa. All three literals are gone, replaced by one exported helper in test/helpers/deps.ts:

export const pausedResult = (gateId: number, summary = 's', proposedAction = 'p'): string =>
  JSON.stringify({ status: 'paused', gate: { gateId, summary, proposed_action: proposedAction } });

with a doc comment naming toResultRecord as the shape's source, and why one helper rather than a literal per suite — an invented fixture is exactly what let pausedGateId read null for every real paused turn with every test green. Nine tests fail against the old read once the fixtures are honest.

Comment thread docs/api/openapi.yaml Outdated
type: integer
minimum: 0
description: |
the gate being answered, as the paused turn's `result.gateId` reports it. Sent rather

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit. The status read exposes the stored record's result.gate.gateId (nested; TurnStatus.result.gate is an object), not a top-level result.gateId. Point the description at result.gate.gateId so a caller reads the right path.

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.

Fixed in f4735aa: the description now says "as the paused turn's result.gate.gateId reports it".

Checked that it is reachable before changing only the prose — clipFields(gate, ['summary','proposed_action'], bytes) copies {...src}, so gateId survives the projection into the status read. Doc path only; no projection change needed.

Three doc conflicts, all the same version-number race: upstream's rossoctl#823
took control-plane API 1.35.0, so rossoctl#393's two entries move up to 1.36.0
(gates on any leaf kind, with the data plane's 1.8.0 twin) and 1.37.0
(the gate deadline). `openapi.yaml`, the CHANGELOG's data-plane table and
change-policy's decision-5 row follow.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
`planLeafGate` and `appendGateDecision` took the whole envelope and read
`env.sessionId`, but only a prompt leaf's Pi turn runs under that raw id -- a
solve leaf's runs under `leafSessionId(env)`, which prefixes the tenant and
maps every character outside [A-Za-z0-9._-] to "-". For any session id
`toSessionId` rewrites (the documented `<run>/<item>` convention, or any
tenant) the gate read found no pending gate, so a re-POSTed decision ran the
leaf's fresh problem statement instead of the continuation: an `approve` that
asks for approval again, an `abort` that does not abort. The decision entry
landed on the wrong key too, so it was not durable.

Both helpers now take the session id as a parameter, and each kind passes the
id it opens its own Pi session under.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
`pausedGateId` read a top-level `result.gateId`, a shape no writer produces:
`toResultRecord` nests the id under `gate`, and the top-level field exists only
on the in-process `LeafResult` a synchronous `/runs` caller is handed back. So
it returned null for every real paused turn -- the gateId mismatch check never
fired, and the sweep's `onTimeout` was inert because it could not name the gate
to abort. Three test fixtures invented the top-level shape, which is what kept
this green; they are replaced with one `pausedResult()` helper that matches the
stored record, and with honest fixtures the old read fails nine tests.

Also: the `!created` tail of `decideGate` now applies the same `sameDecision`
test the `found.resumed` branch does. A human `approve` and the sweep's `abort`
can both read an unresumed gate before either joins the session index, and the
loser was 202'd with the winner's turn id -- reporting that its own, different
decision had been accepted.

And the `gateId` description in openapi.yaml names `result.gate.gateId`, the
field a caller can actually read.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik

cwiklik commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@ingpaolodettori-dev — re-review please when you have a moment. Both must-fixes are addressed and merging is still blocked on the CHANGES_REQUESTED.

  • must-fix: pausedGateId read a shape no writer produces (f4735aac) — now reads result.gate.gateId. You were right about the blast radius: it returned null for every real paused turn, so the gateId mismatch check was unreachable and the sweep's onTimeout was inert. Three invented fixtures are replaced with one pausedResult() helper matching toResultRecord; with honest fixtures the old read fails nine tests.
  • must-fix: wrong session id for a solve leaf's gate (0c0692f5) — planLeafGate and appendGateDecision take the session id as a parameter; prompt passes raw env.sessionId, solve passes leafSessionId(env). Pinned with the non-clean id you asked for (gate-kinds-solve/slashed), asserting both the APPROVED continuation reaching produce and the decision entry landing on that same session.
  • suggestion: created: false dropped — the !created tail now shares one replays helper with the found.resumed branch. Worth a look at that thread: the reachable race window is narrower than "claim before create" (claimKey steps over a recordless holder), so the test reproduces the hSet→zAdd window inside TurnStore.create instead.
  • suggestion: fixtures and nit: openapi result.gate.gateId — both done.

All 18 checks pass at f4735aac, and the branch is MERGEABLE after the merge of main. Replies on each of your five threads have the details.

Assisted-By: Claude Code

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Re-review at head f4735aa. The increment since 146486c is four commits, and each is a correction I can follow end to end:

  • 3d261d8 — a null decision is not a decision. This closes the last pass's only suggestion. Both registration sites now use !!env.decision, the same predicate planLeafGate's own !env.decision guard uses, and the new test asserts both halves: input.gate is undefined and the durable store is not read. That is the right shape of fix — the two sites had drifted from the plan that computes nextGateId, and the test now pins them to it.
  • 735cf18 — merge of upstream/main. Three doc conflicts, all the version-number race, resolved as documented: control plane 1.37.0, the data plane's 1.8.0 twin. I checked the three files agree — docs/api/openapi.yaml:14 is 1.37.0, docs/api/harness-openapi.yaml:18 is 1.8.0, and both CHANGELOG.md and change-policy.md name the pair consistently.
  • 0c0692f — the gate is read under the id the leaf's own session uses. The premise holds in the code, not just in the message: runPromptLeaf hands executeTurn sessionId: env.sessionId (line 962), while the solve leaf's turn is opened under leafSessionId(env) (sid, line 1109), and both plan sites now pass the matching id. It is also complete: runLeaf dispatches only solve and prompt to a gate-planning kind, and a converge leaf never calls planLeafGate. The new test uses a gate-kinds-solve/slashed id — the documented <run>/<item> convention — so it fails on the old read and passes on the new one, and it checks the decision was appended to that same session.
  • f4735aa — pausedGateId reads result.gate.gateId. This was a dead mismatch check and an inert onTimeout, and the most valuable part of the fix is the test repair: three fixtures that invented the top-level gateId shape are replaced by one pausedResult() helper that matches what toResultRecord actually stores. A test that fabricates its own input shape is how the bug survived, so replacing the fabrication rather than adding a fourth is the fix. The !created tail of decideGate gaining the same sameDecision test is a real race closed, not a tidy-up: a human approve and the sweep's abort can both read an unresumed gate before either joins the index.

No must-fix. One nit, and the carried-forward question below.

Nit — replays() returns a bool, so the caller needs prior! to read prior.turnId. Returning the narrowed record (or the turn id) would keep the non-null proof in one place; the assertion is safe today because replays is false for a null prior, but it is the kind of ! that survives a later refactor.

Carried forward, for a human — the earlier reviews on this PR left reviewDecision at CHANGES_REQUESTED (an event type this program must not use). It should be dismissed once someone is satisfied; I cannot.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness run-leaf and gate-kind tests; control-plane turn-handlers and gate-sweep tests), docs (openapi ×2, CHANGELOG, change-policy, leaf-and-envelope)
Agent/IDE config (.claude/.vscode): none
Commits: 22 commits, all signed-off: yes
CI status: passing — all 18 checks green at f4735aa, including check (6m39s) and microvm-gates

Verified by: read the four commit diffs in full (3d261d8, 735cf18, 0c0692f, f4735aac) and traced each claim into the code at head: the two planLeafGate call sites and their session ids, runLeaf's kind dispatch, the !!env.decision registration predicate, the version trio. git merge-base --is-ancestor 146486c HEAD confirms the previous review's head is in this history, so the increment is exactly those four commits; git diff --stat 146486c..HEAD is 85 files only because the merge brings upstream/main with it. Not run this pass: the control-plane and harness suites locally (a fresh clone has no node_modules and the harness needs its pi-fork submodule built) — the previous pass ran both green at 146486c, and CI's check job exercises both at this head.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Reviewed at head f4735aac, the three commits on top of 146486c: the null-decision predicate, the solve leaf's own gate session id, and the paused gate id read. Each closes a real defect, and each is held closed by a test rather than by the code change alone — I reverted all three in turn and the named test failed every time. I re-ran both suites locally at the head instead of leaning on CI.

  • The paused gate id is read where it is written. toResultRecord nests the id under gate and no writer sets a top-level one; the three fixtures that invented the top-level shape are exactly what kept the mismatch check and the sweep's onTimeout green-but-inert. One pausedResult() helper now matches the stored record, and with it the old read fails nine tests — so the fix is pinned, not just asserted.
  • A solve leaf reads gate state under the id its own Pi session uses. planLeafGate and appendGateDecision take the session id as a parameter: leafSessionId(env) for a solve leaf (which toSessionId may rewrite), the raw env.sessionId for a prompt leaf (which is what its executeTurn is handed). Both match their writers now, and the new test covers the documented <run>/<item> slash case end to end.
  • decision: null no longer registers the gate tool. Both registration sites now use !!env.decision, the same falsy predicate planLeafGate uses to compute nextGateId, which is what made the two disagree.
  • The !created guard closes the human-vs-sweep reporting race. The reasoning that found.resumed cannot catch it (it was still false when the caller read) is correct, and the new test reproduces the mid-create window honestly by removing the session-index member.

One suggestion, on the claimKey idempotency that §2's convergence promise rests on; everything else holds.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (harness run-leaf and its gate-kind tests; control-plane turn-handlers/turn-store/gate-sweep/turn-result and their tests), docs (openapi.yaml, CHANGELOG, leaf-and-envelope.md)
Agent/IDE config (.claude/.vscode): none
Commits: 22 (21 plus the upstream merge), PR commits all signed off: yes; DCO green
CI status: all 18 checks green at f4735aac

Verified by: packages/control-plane full vitest run against a local Redis — 2117 passed, 4 skipped, 0 failed; tsc --noEmit clean. harness full vitest run — 1024 passed, 5 skipped, the single failure being test/context-overlay.test.ts, the pre-existing root-environment case the PR body already names; run-leaf-gate-kinds.test.ts 14/14. Mutation checks: the old top-level result.gateId read fails 9 control-plane tests, the raw session id in the solve leaf fails the new slash-id test, and !== undefined fails the null-decision test. prettier --check clean on all 36 changed .ts/.yml/.md files. One throwaway probe (deleted afterwards) backs the suggestion: with the gate key held by a turn whose record is not written yet, POST /v1/sessions/{id}/decision answered 202 with a new turn id instead of converging on the holder.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

// on one turn when they race (design §3).
const idempotencyKey = `${paused.sessionId}:gate:${decision.gateId}`;
const candidate = `t-${deps.newId()}`;
const claim = await claimKey(turns, paused.owner, idempotencyKey, candidate);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — claimKey is the convergence guarantee §2/§3 rest on, and it has a window where it steals a live claim. claimIdempotencyKey (turn-store.ts:167) writes the key hash, and the record follows at the turns.create on line 183 one round trip later. In between, this call's turns.get(held) (line 98) returns null, claimKey reads that as "the holder finished", releaseIdempotencyKeyIf deletes a live claim, and the second claimIdempotencyKey wins the key.

Probe on this head (fake-Redis, deleted afterwards): with ${sessionId}:gate:0 held by a turn whose record does not exist yet — exactly the winner's mid-create state — POST /v1/sessions/{id}/decision returned 202 with a NEW turn id rather than the holder's. If the holder is a real in-flight resume, both resumes are then live, and a second leaf reading after the first appends its decision finds no pending gate and re-derives the same continuation (harness/src/gate.ts:213) — so a human-approved continuation runs twice: double spend, double side effects, for one decision.

The window is a few round trips wide, and it needs the winner preempted between its claim and its create, so it is rare. Two reasons to raise it here anyway: the claimKey doc comment says the second claim can only lose to a non-terminal holder "by definition", and this is the case where it does not; and while claimKey predates this PR (ordinary submissions on main share the window), a gate key is where a human and the 30 s sweep race on purpose, which is a new and regular way to reach it.

Suggested fix: make the stepover distinguish "record terminal" from "record unreadable" — do not step over a holder whose record is absent — and recover a genuinely orphaned key (a crash between claim and create) another way, e.g. a modest TTL on the key hash, or by creating the record before the claim and unwinding it when the claim is lost. At minimum, a comment recording the window would stop the next reader trusting "by definition".

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.

Confirmed, including the harm chain, and tracked as #989. The comment you asked for at minimum is in c0ada03f.

Verified by reading rather than re-probing: claimIdempotencyKey writes the key hash and create writes the record a round trip later, so an unreadable holder and a terminal one are the same observation, and the stepover's releaseIdempotencyKeyIf matches the holder it just read — so it succeeds against a live claim. The second hop is as you describe: resume B's planLeafGate finds gate 0 already decided, decideSeed's no-pending-gate branch re-derives continuationPrompt(lastDecision…), and planLeafGate returns it as continuation because the envelope carries a decision. So the approved continuation, not the fresh prompt, is what runs the second time.

You were right to call out the "by definition" too — that is the one case the sentence is wrong about, and it is now replaced by the window, the gate-key consequence, and a shortcut: with the upgrade trigger.

Not fixed here, deliberately. The mirror reading is not free: treat an unreadable holder as live and a crash between a claim and its create wedges that key with no record and no release — and the default key is the session id, so every later turn of that session would be answered with the ghost's id, with no self-heal. Telling a stalled claimant from a crashed one needs a lease, and §5.1 rules out the Lua/WATCH/MULTI that would make claim-plus-record atomic. #989 writes up the three candidates (claimedAt plus a grace, which I'd recommend; a key TTL shorter than the record's; create-before-claim, which contradicts §4.3's nothing-left-behind) with the trade-off each makes, and acceptance tests for both directions — the stolen claim and the orphan that must still self-heal.

That is a change to the idempotency protocol for every submission on main, not just for gates, which is why it is an issue and not a sixth commit on this PR. Happy to take it as the next one if you would rather it land before this merges.

…laim

The doc said the second claim can only lose to a holder that is "by
definition" non-terminal. That is the one case it is wrong about: a claim is
not atomic with the record it names, so a holder stalled between
`claimIdempotencyKey` and `create` reads exactly like one whose record expired,
and the stepover releases a live claim. Both submissions then enqueue a turn
for one key -- and on a gate key the second leaf finds the gate already decided
and re-derives the same continuation, so one human approval runs twice.

Comment only: the opposite reading wedges a crashed claim's key instead (the
default key is the session id), and telling a stalled claimant from a crashed
one needs a lease the design's no-Lua rule currently rules out. Recorded as a
`shortcut:` with that upgrade trigger so the next reader does not trust the
"by definition".

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Reviewed at head 4237341a, the single commit on top of f4735aa. It changes no code: it replaces the "by definition" sentence in claimKey's doc with the window where that reasoning does not hold, and records it as a shortcut: with an upgrade trigger.

I reproduced the window rather than taking it on trust. A throwaway probe at this head (deleted afterwards) holds the gate key for a turn whose record is not yet written — exactly what a claimant stalled between claimIdempotencyKey and create looks like — and then posts a decision: POST /v1/sessions/{id}/decision answers 202 with a new turn id, idempotencyHolder flips to that new turn (the live claim was stepped over, not preserved), and after the stalled claimant creates its own record there are two queued records for "<sid>:gate:0". So the doc's account is accurate, including "one human approval runs twice"; the second half of it — that the later leaf re-derives the same continuation instead of re-pausing — is already pinned by harness/test/gate.test.ts ("already-decided this gate (double resume) → seed continuation, record null (no re-record)").

That closes the suggestion from the previous pass, which asked for the residual window to be written down rather than left behind a comment claiming it could not happen. No must-fix. Two non-blocking notes below: the shortcut:'s first proposed upgrade path does not discriminate as worded, and a small documentation casualty in turn-store.ts.

One nit on the PR body: §2 still says the gate-keyed idempotency "is what makes a double-click and a racing deadline sweep converge on a single resume" without the exception this commit adds. That is true whenever the first resume's record exists; a sentence pointing at claimKey's doc would keep the body honest about the case where it does not.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (packages/control-plane/src/turn-handlers.ts, turn-store.ts; harness/src/gate.ts for the continuation claim), tests (harness/test/gate.test.ts, packages/control-plane/test/turn-gate-decision.test.ts)
Agent/IDE config (.claude/.vscode): none
Commits: 23, all signed-off: yes (DCO green)
CI status: passing — 18/18 at 4237341a

Verified by: the probe described above, run against the in-memory Redis fake at this head (202 t-id-3; holder t-id-3; records t-id-3(queued), t-stalled-A(queued) — probe deleted afterwards); harness/test/gate.test.ts 28/28 at this head, including the double-resume case the comment cites; and reading decideSeed's no-pending-gate branch, which returns continuationPrompt(lastDecision...), against the doc's claim. Not run: the control-plane and harness suites in full — the increment is comments only and the check job exercises both at this SHA.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

*
* shortcut: a stalled claimant and a crashed one are indistinguishable without a lease, and §5.1
* rules out the Lua/WATCH/MULTI that would make claim-plus-record one step; upgrade when the key
* can carry one (a TTL shorter than the record's, or a `claimedAt` plus a grace), which tells the

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion — Of the two upgrade paths named here, the first does not tell the two cases apart as written. A claim TTL that is allowed to fire looks exactly like the window this comment is about: when it expires, claimIdempotencyKey's HSETNX wins the key for the next submission while the turn it named can still be alive, and nothing else refuses that second submission — gate_pending guards a gated submission, not POST /decision, and an ordinary turn has only the claim. That re-opens the duplicate fan-out §4.3 exists to prevent, for any turn slower than the TTL.

A TTL only helps if its remaining value is read back as an age clock — never allowed to expire — and it outlives the slowest live turn. That is claimedAt with an extra round trip.

Suggested fix: keep only the second option and name the discriminator: store claimedAt on the claim hash, and treat now - claimedAt > grace as crashed (stepover is then safe) and anything younger as stalled (treat the holder as live). If a smaller change is wanted, re-read turns.get(held) once before the stepover after a short pause (~250 ms): that shrinks the window without new state, though it does not close it.

Why now: this block is the instruction the next person follows to fix the window, so it should not point them at a change that widens it.

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.

You're right about the sentence as written, and it's fixed in 9137cc0e.

"A TTL shorter than the record's" compresses away the precondition that makes a TTL safe, and read literally it is a TTL that fires — which is exactly the stepover this comment warns about, except now performed by HSETNX against a holder nobody even looked at. Worse than the window it was supposed to close, and your point about nothing downstream catching it is the part I'd have missed: gate_pending guards a gated submission, so it never sees POST /decision, and an ordinary turn has only this claim between it and a duplicate.

The note now names the discriminator the way you suggested:

upgrade when the key carries a claimedAt, so an age past a grace that outlives the slowest turn means crashed and anything younger means live … NOT a TTL that is allowed to expire: [why] … A TTL helps only if its remaining value is read as that same age clock and never fires, which is claimedAt the long way round.

One nuance for the record, since #989 keeps the TTL as candidate 2: there the argument is explicitly that it cannot fire — a key is held only while its turn is non-terminal (MOCA_TURN_MAX_S, 1800 s), the record's own TTL starts at the terminal transition, and the key TTL would be tied to resultTtlSeconds (86 400 s). That holds, but only because of the two-order-of-magnitude gap, and it is load-bearing in a way a reader will skim past — so I've flagged it on the issue rather than leaving it implicit. claimedAt is still the recommendation there, for the reason you give: it is the only option that states the rule instead of relying on a margin.

I did not take the 250 ms re-read. It shrinks the window at the cost of a sleep on the submit path for a case that needs a protocol change anyway, and a partial fix here would make #989 look handled.

return held.turnId ?? null;
}

async releaseIdempotencyKeyIf(owner: string, key: string, expected: string): Promise<boolean> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit — idempotencyHolder was inserted between releaseIdempotencyKeyIf's doc comment and the method itself, so that contract — compare-then-delete, "the ONLY release", and why a blind del is never allowed — is now a floating comment that releaseIdempotencyKeyIf no longer carries. The second block attaches to idempotencyHolder, and the release method reads as undocumented in editors and generated docs.

Suggested fix: move the release block below idempotencyHolder's own doc, immediately above async releaseIdempotencyKeyIf.

Why now: the new claimKey doc leans on exactly this contract ("The release is CONDITIONAL on the stale holder we actually read"), and it is the rule all three release call sites have to keep.

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.

Confirmed and fixed in 9137cc0e — my regression: idempotencyHolder is new in this PR and I inserted it in the wrong place, so the release contract ended up documenting the reader and releaseIdempotencyKeyIf ended up with nothing. Moved back onto the method, below idempotencyHolder's own doc, exactly as suggested. Comment-only; no code moved.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review at 4237341a. The head is f4735aac plus exactly one commit, 4237341a, and that commit is comment-only (turn-handlers.ts doc block, +21/−4, no executable line): it records the claimKey step-over window clawgenti raised — a holder stalled between claimIdempotencyKey and create reads as stale, so a live claim can be released and re-won — as a shortcut: with the lease-based upgrade trigger. I checked the comment against the code and it describes the window accurately; it is clawgenti's own inline thread, so it is not reposted here. CI is 18/18 green and every commit is DCO-signed.

One must-fix, one suggestion, one body nit.

Must-fix — a same-key retry of a gated turn is 409'd instead of 202'd with the existing turn. The gate_pending guard (turn-handlers.ts:345-356) runs before the idempotency claim (:388), and findGateHolder returns a gated turn that is paused, queued, or running. A client that re-sends the same gated submission with the same idempotencyKey (or the default, the session id) is therefore refused 409 gate_pending instead of reaching claimKey and being answered 202 with the existing turn id. That is the pre-existing contract on this same operation — the submitTurn description in docs/api/openapi.yaml says "Resubmitting on a key whose turn is still non-terminal answers 202 with the EXISTING turn id", text this PR does not touch — and the new 409 response contradicts it for gated turns. It matters for retry safety: a client that lost the first 202 cannot tell "succeeded, here is your turn" from "rejected". No test retries with the same key; the gate_pending tests all use distinct keys (k2/k3). Minimal fix: compare the holder's idempotencyKey to this submission's and let a same-key holder fall through to the idempotency path, refusing only a holder on a different key.

Suggestion — the sweep submits without the "already resumed" check its catch block makes. sweepGates claims the member (gate-sweep.ts:54) and calls submitResume with no durable re-read, while its failure path (:82) re-reads findPausedBySession and hands the member back only for an unresumed gate. If a resume that enqueued successfully did not clear its member — submitResume's claimGate (turn-handlers.ts:211) runs after the enqueue, so a crash or Redis error there leaves it behind — and that resume has since gone terminal (which releases the gate-keyed idempotency key), a later pass claims the stale member, claimKey finds the key free, and submitResume creates a SECOND resume from the same paused turn: the continuation runs twice. Re-reading findPausedBySession after claimGate and skipping when this turn is already resumed, as the catch block does, closes it.

Nit — the body's version is stale. The PR body says "API 1.35.0 → 1.36.0", but docs/api/openapi.yaml at head is 1.37.0, and the CHANGELOG now carries both a ## 1.36.0 and a ## 1.37.0 section while main is still 1.35.0. After merge the file goes straight from 1.35.0 to 1.37.0, so 1.36.0 is a changelog version that never existed in info.version. Confirm the intended bump (a single 1.36.0, or keep 1.37.0 and explain the 1.36.0 section) and align the body.

Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane turn-handlers, turn-store, gate-sweep, turn-record, errors, routes; harness gate path), OpenAPI + CHANGELOG + change-policy, deploy env
Agent/IDE config (.claude/.vscode): none
Commits: 23, all signed-off: yes (DCO green)
CI status: passing — 18/18 green at 4237341a

Not run here: the packages/control-plane and harness suites (this checkout has no dependencies installed). Findings are from reading the head source, the PR diff, the existing review threads and the documented contract; clawgenti's 23 Nov probe on the claimKey window and the author's replies were cross-checked rather than re-run.

Assisted-By: Claude Code

// of its run, and a `paused`-only read admitted a second gated turn through all of it.
if (asksForGate(parsed.envelope)) {
const holder = await turns.findGateHolder(rec.sessionId);
if (holder) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix. This guard runs before the idempotency claim at line 388, and findGateHolder returns a gated turn in paused, queued, or running. So a client retrying the same gated submission with the same idempotencyKey (or the default session-id key) is refused 409 gate_pending here instead of reaching claimKey and being answered 202 with the existing turn id. The submitTurn description in docs/api/openapi.yaml still promises "Resubmitting on a key whose turn is still non-terminal answers 202 with the EXISTING turn id" — text this PR does not change — so the new 409 contradicts it for gated turns, and a client that lost the first 202 cannot tell a successful retry from a rejection. No test retries with the same key (the gate_pending tests use distinct k2/k3). Minimal fix: compare the holder's idempotencyKey to this submission's key and let a same-key holder fall through to the idempotency path (202 with its turn id), refusing only a holder on a different key. Alternatively, claim first and gate the refusal on claim.fresh.

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.

Fixed in 07aefee9, pushed before your approval landed — same finding RepoMan raised, so this thread and that one got the same change.

Reproduced first: with the guard unchanged, the new test replays a RETRY of the gated submission that opened the gate fails, because the default key is the session id and so a plain resubmission hits the guard rather than claimKey. Took the minimal fix you named — compare the holder's key with this submission's and fall through on a match — with one addition, because the literal version has a hole: a paused holder's key is already released (paused is terminal, toTerminal releases it), so a same-key fall-through there wins the key fresh and opens the second gated turn the guard exists to prevent. Hence holder.paused || is tested first, with its own test (refuses a same-key retry once that turn is PAUSED) — and the refusal's message already tells that client the right move, which is to answer the gate rather than resend.

The openapi.yaml text you measured it against is updated in both places that promised the unconditional refusal: the requireApproval description and the 409 body.

}
// Claimed as late as possible: everything above is a read, and a claim that is not followed by
// a submission strands the gate.
if (!(await turns.claimGate(turnId))) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. The member is claimed and submitResume is called with no durable "already resumed" re-read, while the failure path below (:82) re-reads findPausedBySession and hands the member back only for an unresumed gate. If a resume that enqueued successfully did not clear its member — submitResume's claimGate (turn-handlers.ts:211) runs after the enqueue, so a crash or Redis error there leaves it behind — and that resume has since gone terminal (which releases the gate-keyed idempotency key), a later pass claims the stale member, claimKey finds the key free, and submitResume creates a SECOND resume from the same paused turn: the continuation runs twice. Re-reading findPausedBySession after claimGate and skipping when this turn is already resumed, as the catch block does, closes the window.

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.

Fixed in 07aefee9, pushed before your approval landed — same finding RepoMan raised on this line, so both threads got the same change.

Your suggested shape, right after claimGate:

const already = await turns.findPausedBySession(paused.sessionId);
if (already?.paused.turnId === paused.turnId && already.resumed) continue;

Nothing to hand back on this path — the claimGate above already took the stale member out, which is where an answered gate belongs. New test does not resume a gate whose member was STRANDED by an answered resume builds that state directly (a finished resumeOf turn, with the gate key asserted released) and fails without the check.

One existing fixture had to move with it: does NOT hand the gate back when it was answered in the failing window seeded its answered resume before the pass, so this new pre-check short-circuited the test and no enqueue ever failed. It now creates the human resume inside a failing enqueue mock — the window it always meant to describe — and asserts the enqueue was actually reached, so it cannot silently pass that way again.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

Re-review at head c0ada03f, the single commit on top of 4237341a. It changes one line of prose: claimKey's shortcut: now names issue #989. I checked the pointer (rossoctl/moca#989 is open and its title matches the step-over window described) and that the sentence still describes the code; no executable line changed, so the previous pass's findings stand as written at this head.

Both open items are real, and I reproduced each at c0ada03f with throwaway probes against the in-memory Redis fake (deleted afterwards):

  • A same-key retry of a gated submission is 409 gate_pending, not 202 with the existing turn. Ungated control: the same {kind:'prompt', idempotencyKey:'k1'} twice answers 202 {"turnId":"t-id-2"} both times. The same body plus requireApproval: true answers 202 {"turnId":"t-id-2"} and then throws gate_pending on the retry. Inline, must-fix.
  • The deadline sweep can create a second resume from the same paused turn. With the prior resume still holding ${sid}:gate:0, the sweep resumes nothing (queue empty). With that resume terminal but its gate member left behind — what a crash or Redis error between enqueue and claimGate leaves — the sweep creates and enqueues a second resume, so two records share resumeOf the paused turn and the continuation runs twice. Inline, suggestion with the probe output.

One nit on the PR body: the version line still says 1.35.0 → 1.36.0, while docs/api/openapi.yaml at head is 1.37.0 and docs/reference/change-policy.md now names 1.37.0. The CHANGELOG carries both a ## 1.36.0 and a ## 1.37.0 section and main is still 1.35.0, so after merge the file jumps 1.35.0 → 1.37.0 and 1.36.0 is a changelog version that never appeared in info.version. Decide whether that is intended (two sections, one bump) and align the body.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (packages/control-plane/src/turn-handlers.ts, turn-store.ts, gate-sweep.ts), OpenAPI + CHANGELOG + change-policy, the #393 gate tests
Agent/IDE config (.claude/.vscode): none
Commits: 24, all signed-off: yes (DCO green)
CI status: pending at c0ada03f — 6 passed, 9 in progress (Docker-dependent jobs among them)

Verified by: two throwaway vitest probes at this head, run against test/helpers/fake-redis.ts and deleted afterwards — CONTROL ungated retry: 202 {"turnId":"t-id-2"}; GATED same-key retry: THREW gate_pending; LIVE-PRIOR resumed-count: 0 queue: []; TERMINAL-PRIOR resumed-count: 1 queue: ["t-id-3"] with [["t-orphan","done"],["t-id-3","queued"]] both resumeOf the paused turn; and the PR's own turn-gate-decision, gate-sweep and turn-store-gate suites, 44/44 at this head. Not run: the full packages/control-plane and harness suites — CI's check job covers both at this SHA.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

// A gated turn still `queued` or `running` holds the gate too, which is why this asks
// `findGateHolder` rather than reading `paused` alone: the first turn is unpaused for the whole
// of its run, and a `paused`-only read admitted a second gated turn through all of it.
if (asksForGate(parsed.envelope)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix. This guard runs before the idempotency claim (:388), and findGateHolder returns a gated holder that is queued or running as well as paused (turn-store.ts:402), so a client retrying the same gated submission with the same key never reaches claimKey.

Probe at c0ada03f (throwaway vitest on fakeRedis, deleted):

  • ungated control, {kind:'prompt', prompt:'hi', idempotencyKey:'k1'} twice → 202 {"sessionId":"id-1","turnId":"t-id-2"} both times;
  • the same body plus requireApproval: true → first 202 {"turnId":"t-id-2"}, retry throws gate_pending.

docs/api/openapi.yaml:2050 still promises "Resubmitting on a key whose turn is still non-terminal answers 202 with the EXISTING turn id" — text this PR does not touch — and no test retries on the same key (the gate_pending tests use k2/k3). A client that lost the first 202 therefore cannot tell "succeeded, here is your turn" from "rejected", and the default key is the session id, so this bites a plain retry with no key set either.

Suggested fix: compare the holder's idempotencyKey with parsed.idempotencyKey ?? rec.sessionId and let a same-key holder fall through to the idempotency path (202 with its turn id); refuse only a holder on a different key. Add the same-key retry test next to the k2/k3 cases.

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.

Confirmed and fixed in 07aefee9. Reproduced it first: with the guard unchanged, the new test replays a RETRY of the gated submission that opened the gate fails — the second identical submission throws gate_pending where openapi.yaml's "Resubmitting on a key whose turn is still non-terminal answers 202 with the EXISTING turn id" promises a replay. The default key being the session id is what makes this the ordinary retry rather than an edge case, as you said.

I took your fix with one addition, because the literal version has a hole. A paused holder's key is already gone: paused is terminal, so toTerminal released it before this submission arrived. A same-key fall-through there reaches claimKey, wins the key fresh, and opens exactly the second gated turn this guard exists to prevent. So the condition tests paused first:

if (holder && (holder.paused || holder.turn.idempotencyKey !== idempotencyKey)) {

and a retry on a paused gate still gets gate_pending — whose message already tells the client the right move (answer the gate, don't resend). That is its own test (refuses a same-key retry once that turn is PAUSED), next to the replay one and the k2 different-key case you pointed at.

idempotencyKey is now computed once above the guard rather than twice, and I added the exception to both places in openapi.yaml that promised the unconditional refusal — the requireApproval description and the 409 body — since the contract is what you measured the bug against.

}
// Claimed as late as possible: everything above is a read, and a claim that is not followed by
// a submission strands the gate.
if (!(await turns.claimGate(turnId))) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion. The member is claimed here and submitResume runs with no durable "already resumed" re-read, while the failure path below (:82) re-reads findPausedBySession and hands the member back only for an unresumed gate. submitResume calls claimGate (turn-handlers.ts:211) after enqueue, so a crash or Redis error there leaves the member behind; toTerminal then releases the gate-keyed idempotency key when that resume finishes, and a later pass finds the key free.

Probe at c0ada03f (throwaway vitest, deleted), same paused turn and ${sid}:gate:0 in both arms:

  • prior resume still holds the key → sweepGates returns 0, queue [];
  • prior resume terminal (finalize('t-orphan','done')), member still indexed → sweepGates returns 1 and enqueues t-id-3, leaving [["t-orphan","done"],["t-id-3","queued"]], both resumeOf the paused turn. The continuation runs twice — double spend and double side effects for one decision.

The catch block's guard cannot see this: there is no exception on the success path.

Suggested fix: after claimGate and before submitResume, re-read findPausedBySession(paused.sessionId) and continue when found?.paused.turnId === paused.turnId && found.resumed (the member is already out, so nothing to hand back), the same question the catch block asks.

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.

Good catch, fixed in 07aefee9, and the harm is worse than "a redundant resume": the stranded member outlives the resume that answered the gate, and toTerminal releases the gate-keyed idempotency key when it finishes — so nothing converges the next pass onto that turn, and submitResume builds a genuinely second resume from the same paused turn. The harness then takes decideSeed's no-pending-gate branch and re-derives continuationPrompt(lastDecision…), so it is the approved continuation that runs twice, not a fresh prompt. Double spend and double side effects for one decision.

Your suggested shape, verbatim, right after claimGate:

const already = await turns.findPausedBySession(paused.sessionId);
if (already?.paused.turnId === paused.turnId && already.resumed) continue;

Nothing to hand back — the claimGate above already took the stale member out, which is where an answered gate belongs. New test does not resume a gate whose member was STRANDED by an answered resume builds the state directly (a finished resumeOf turn, gate key asserted released) and fails without the check.

One fixture had to move: does NOT hand the gate back when it was answered in the failing window seeded its answered resume before the pass, so this new pre-check short-circuited it and no enqueue ever failed. It now creates the human resume inside a failing enqueue mock, which is the window that test always meant to describe — and it asserts the enqueue was actually reached, so it cannot silently pass that way again.

…d gate

Two review findings on the gate guard and the deadline sweep.

The one-open-gate guard ran before the idempotency claim and refused any
gated submission while a gate was open -- including the client's own
submission coming back, which the default session-id key makes the
ordinary retry. That contradicted the 202-on-a-live-key the API promises
and left such a client unable to tell "accepted" from "rejected". The
guard now compares the holder's key with this submission's and falls
through on a match. A PAUSED holder is still refused even on its own key:
`paused` is terminal, so `toTerminal` already released that key, and a
fall-through would win it fresh and open the second gated turn the guard
exists to prevent. The refusal already says to answer the gate instead.

The sweep claimed a due gate and submitted without re-reading whether it
had been answered. `submitResume` claims the gate member only after its
enqueue, so a crash in between strands the member on an answered gate --
and once that resume finishes, `toTerminal` releases the gate-keyed
idempotency key, so nothing converges the next pass onto it and it would
build a SECOND resume from the same paused turn: the approved
continuation running twice. A `findPausedBySession` re-read after
`claimGate` drops the stale member instead, the same question the catch
block already asks and for the same reason.

Tests: the same-key retry replay (and that a different key is still
refused), the paused-holder refusal, and the stranded-member pass.
`does NOT hand the gate back when it was answered in the failing window`
now creates the human resume inside a failing `enqueue`, which is the
window it always meant to describe.

Refs rossoctl#393
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: cwiklik <[email protected]>

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review at 07aefee9. This head is c0ada03f plus exactly one commit, 07aefee, and that commit fixes both findings from the 14:20 review (4237341a). CI is 18/18 green at this head and DCO is green on all 25 commits. Approving, which clears our CHANGES_REQUESTED.

Must-fix (a same-key retry of a gated turn was 409'd instead of 202'd with the existing turn) — fixed. idempotencyKey is hoisted above the guard, and the guard now refuses only when the holder is paused or sits on a different key. A same-key holder that is still queued/running falls through to claimKey, which replays 202 with that turn's id and enqueues nothing — the existing reservation is released on the not-fresh path, as before. The paused exemption is right and necessary: paused is terminal, so toTerminal has already released the key, and falling through on a retry of a paused turn would win it fresh and open exactly the second gated turn this guard exists to prevent; the 409 already tells the caller to answer the gate. The new test covers the plain retry on the default session-id key, the different-key refusal, and the paused-holder refusal.

Suggestion (the sweep submitted without the "already resumed" re-read its catch block makes) — fixed. sweepGates now re-reads findPausedBySession after claimGate and skips when this turn is resumed, so a stranded member on an answered gate is taken out rather than turned into a second resume. The new test creates and finalizes the resume before the pass and asserts no queue entry and an empty due index; the reworked "failing window" test now injects the human resume inside the failing enqueue, which is the window it always meant to describe.

Non-blocking — residual of the same window. The re-read can only see the session's newest paused turn. If the stranded resume has since paused at a gate of its own, findPausedBySession returns that newer turn, already.paused.turnId !== paused.turnId, and the pass still falls through to a second resume of the original paused turn (its gate key was released when the first resume went terminal). It needs the crash between enqueue and claimGate plus a further gate in the chain, so it is much narrower than what this commit closes and not a blocker; if you want it closed too, scan the session index for any non-failed turn with resumeOf === paused.turnId instead of relying on the newest paused.

Nit (carried) — the PR body's version claim is stale. The body says "API 1.35.0 → 1.36.0", but docs/api/openapi.yaml at head is 1.37.0, the CHANGELOG carries both a ## 1.37.0 and a ## 1.36.0 section, and main is 1.35.0. After merge info.version goes straight from 1.35.0 to 1.37.0, so 1.36.0 would be a changelog section that never existed as a version. Confirm the intended bump (a single 1.36.0, or keep 1.37.0 and explain the 1.36.0 section) and align the body.

Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane turn-handlers, turn-store, gate-sweep; harness gate path), OpenAPI + CHANGELOG + change-policy
Agent/IDE config (.claude/.vscode): none
Commits: 25, DCO green
CI: 18/18 green at 07aefee9

Not run here: the packages/control-plane suite (this checkout has no dependencies installed). Findings are from reading the head source, the diff, and the documented contract.

Assisted-By: Claude Code

…d doc block

Two review findings, both comment-only.

The `claimKey` shortcut named "a TTL shorter than the record's" as an
upgrade path for telling a stalled claimant from a crashed one. A TTL
that is allowed to fire does not tell them apart: it hands the key to
the next submission while the turn it names can still be running, which
is the duplicate fan-out §4.3 exists to prevent, and nothing downstream
refuses it -- `gate_pending` guards a gated submission, not a decision,
and an ordinary turn has only this claim. The note now names `claimedAt`
plus a grace that outlives the slowest turn as the discriminator, and
says a TTL only helps when read as that same age clock and never fired.
This block is the instruction the next person follows, so it must not
point at a change that widens the window.

`idempotencyHolder` was added in this PR between `releaseIdempotencyKeyIf`
and its doc comment, leaving the release contract -- compare-then-delete,
"the ONLY release", why a blind `del` is never allowed -- floating above
the wrong method, with the release reading as undocumented. Moved back
onto it; `claimKey`'s doc leans on exactly that contract.

Refs rossoctl#393 rossoctl#989
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: cwiklik <[email protected]>
@pdettori
pdettori merged commit 5cb4bd8 into rossoctl:main Nov 23, 2026
18 checks passed

@clawgenti clawgenti left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Summary

All checks pass. Ready for human review.

Re-review at 9137cc0, the first head since my review 6023545749 at c0ada03. Both functional findings from that review are fixed and pinned by tests:

  • A same-idempotencyKey retry of the gated submission that is still running now replays 202 with that turn's id instead of being refused gate_pending (turn-handlers.ts: the guard now refuses only a paused holder, or a holder on a different key), and the openapi text says so. The new test also pins the two neighbours: a different key is still gate_pending, and a same-key retry once the turn is paused is still refused.
  • The deadline sweep no longer builds a second resume for a paused turn that already has one (gate-sweep.ts: findPausedBySession(...).resumed after claimGate), which covers the crash/Redis-error window between enqueue and claimGate that the catch path could not see.

The two comment nits are also addressed in 9137cc0: claimKey's upgrade note now names claimedAt plus a grace and explains why a TTL that fires is not the discriminator, and releaseIdempotencyKeyIf's doc block is back on its method.

Verified at 9137cc0 against a local Redis 8.10.3: turn-store-gate, gate-sweep and turn-gate-decision 47/47 pass, tsc --noEmit clean. CI 18/18 green.

Author: cwiklik (CONTRIBUTOR — returning external)
Areas reviewed: TypeScript (packages/control-plane: turn handlers, turn store, gate sweep), docs/api/openapi.yaml, tests
Agent/IDE config (.claude/.vscode): none
Commits: 25, signed off: yes (DCO passes)
CI status: passing (18/18)

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

webchang added a commit to webchang/moca that referenced this pull request Nov 23, 2026
Upstream rossoctl#972, rossoctl#977, rossoctl#978, rossoctl#979, rossoctl#981, rossoctl#983, rossoctl#985, rossoctl#988 and rossoctl#990 (44 commits past 49cce28). No conflict.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Coding-agent subagents B7: gates v2 — gates on prompt/solve leaves, decision API, deadlines

4 participants