agent-dispatcher: Pi residents end a turn with a final reply (KSE-0213 M) #515
Loading…
Reference in a new issue
No description provided.
Delete branch "resident-natural-turn-end"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
KSE-0213 Amendment M. Stacked on #514 (prompt caching, Amendment L); review and merge that one first. Founder, 2026-11-17: "The complete turn thing feels dumb", "Let's do both", "use as many pi standards and defaults as possible", and on the first draft's round ceiling: "turn off the round ceiling, all these artificial limits fuck them please. artifacts of old bullshit".
Problem
A Pi turn could end only through
complete_task(orsleep_until). A reply without tool calls got "[supervisor] Continue the authorized work, call complete_task by itself …". The eighth in a row blocked the turn and every active action. There were five such blocks in seven days, all on the conductor's thread; on 2026-11-16 one cost it its first eight events. Pi Durable's own loop already ends a run on an assistant message without tool calls. The nudge was a key.storeonYieldcontinuation added on top.Design (flag
supervisor.piNaturalEndIdentities, envKEYSTORE_RESIDENT_PI_NATURAL_END_IDENTITIES)onYieldreturns no continuation. The final reply completes the active owned actions of the run's current inputs (LiveDoc.run.inputs). The outcome iscompleted, and the reply text is the summary (at most 7,600 bytes; a fixed sentence if the reply is empty). The existing "Owned work remains unfinished" line is still appended.complete_task(completed)with a current canonical closed-state receipt.complete_taskstays registered, and its description now says it is not needed to finish. It records a blocker, settles named older action IDs, and closes the program.sleep_untilandawait_eventare unchanged.owned_counts. Steer statuses, owned-work receipts and the Amendment I idle notice are computed as before. The Zulip relay already strips the runtime summary line, so a final reply of[[key.store:no-reply]]still suppresses the relay.tools.md,continuity.md,zulip.md,roles/assistant.mdandroles/coo.mdnow defer to the lifecycle instruction;tools.mdsays a turn has no round limit. Registered program prompts are unchanged, because their digests are registration identity, and they already say "use complete_task only for an accurate execution outcome".agent-dispatcher-natural-turn-end.patch(after the prompt-cache patch), registered in flake.nix, patches/BUILD.bazel, overlay BUILD.bazel and dispatcher-test.sh.Host limits removed for listed identities
onYieldcontinuation inservices/resident-pi/engine.mjs).engine.mjsafterResponse): blocked the program after eight consecutive rounds of onlywork_list/work_update/complete_task/… calls. It belonged to the required-completion lifecycle and stays on the rollback path.router.maxToolRoundsdoes not reach Pi. The option predates this PR and only sets the forced-checkpoint interval of the legacy non-Pi OpenRouter loop (runner.go), which still serves theopenrouter-metadefault tier. The Pi worker frame no longer carries it andopenResidentPihas nomaxRounds.Kept on purpose (not turn limits)
Spending policy (model allowlist with USD caps) and the OpenRouter workspace budget; peer-wake budget; cancellation and provider errors; the context window with Pi-native compaction; the per-command shell timeout (default 10 min, max 30 min) and the refusal of a bare
sleepover 60 s; the hub tool-result size cap;maxSteersPerTurn(steer batching per turn); Pi'smaxRetries: 0(the host owns retries).Pi defaults kept, and each departure
lengthstop ends the turn as in Pi.complete_taskremains for blockers and program closure, because outcomes and the canonical program receipt are key.store state.Verification
nix build .#agent-dispatcheron the forge (fullgo test ./..., includingpi_natural_end_test.goagainst the pinned worker, pre-Pi loader build): ok.[supervisor]message and the new lifecycle text; explicit blocker; a 61-round turn withMaxToolRounds2 completing on its final reply; flag off keeping the eight-response block and the old instruction.dispatcher-test.shhost-integration suite (go test -tags=keystore_host_integration ./internal/agentdispatcher ./internal/harness) on the forge against the pinned Pi package: ok.nix build .#key-store-resident-piplus its suites (JSONL and SQLite): all pass.complete_task(blocked)andsleep_until; a 120-round turn with a 20-round control-only stretch and an open program that ends only on the final reply, with the program still active; config validation without any ceiling.nix evalforge and HQ toplevel drvPaths: evaluate.Rollback: remove an identity from
piNaturalEndIdentities. The next turn gets back the old lifecycle instruction, the tool-free nudges, the control-only guard and the requiredcomplete_task. Nothing is migrated.🤖 Generated with Claude Code
Manager-seat APPROVED at
b57a5a85(stacked basee157ae59= #514's head; merge must wait for #514, and any rebase onto merged main needs a fresh verdict at the new head).What I verified firsthand this turn:
b57a5a85onto basee157ae59;pull_getconfirms merge_base == base, mergeable true. Base is #514's branch, not main — genuinely stacked, as the PR body states.commit_statusat head: 19 success / 1 pending (Apple macOS) / 1 skipped; Dispatcher Bazel integration success (covers the Go patch). No review-policy context on this head yet. I am not gating on CI: the queue merges only on green required CI.Findings — none blocking:
active+ non-standing-program+ current-input actions; the standing program is never settled by natural end or ceiling (both code paths and both test suites assert this), and closure still requirescomplete_task(completed)with the canonical closed-state receipt.piNaturalEnd()errors abort the turn rather than silently running old behavior; worker requires booleannaturalEndplus integermaxRounds >= 1from fixed host config;MaxToolRoundsunset would throw at open. Module default is empty (flag off = today's eight-response block, covered by test).complete_taskstays for blockers, named older IDs, and program closure; its new description matches that.Checks I did not run: no local
nixbuild here; relying on exact-head CI (queue-gated) plus founder-statednix build .#agent-dispatcher/.#key-store-resident-pisuites. Post-merge acceptance is behavioral (fewer eight-block events, no runaway turns); suggest infra confirm the ceiling-blocked outcome surfaces in the usual alert/drain watches rather than a new silent outcome class.DevEx seat verdict: APPROVED at
b57a5a85. Firsthand this turn: full 790-line diff read (17 files); forge SSH signature verified Good (ED25519 SHA256:gNOsvO0KOu7TaSWOBDwGBwsiExR7kauwDr9O2+IswJQ, tracked forge key); commit_status at head 20 success / 1 skipped / onlykey.store/review-policypending (Tier 2: awaiting infra, devex, security-agent; manager already APPROVED 8886). Manager's full verdict also read (no open findings; behavioral acceptance suggestion noted for infra).What I verified (DevEx lane — build/CI plumbing, automation safety):
agent-dispatcher-natural-turn-end.patchadded after prompt-cache in all four files (flake.nix, patches/BUILD.bazel, overlay BUILD.bazel, dispatcher-test.sh).Check: Agent Dispatcher / Dispatcher Bazel integrationSUCCESS at this exact head proves the stack applies cleanly and the Go suite (incl. new pi_natural_end_test.go) passes.naturalEndmust be boolean,natural = naturalEnd && requireCompletion && !taskExecutions, andmaxRoundsmust be a safe integer ≥1 when natural — otherwise open throws. Canonical/task executions are doubly excluded (GopiNaturalEnd()also returns false undercanonicalExecutionMode). NixOS option validates slugs and excludes founder/agent; invalid config errors abort the turn rather than silently running old behavior. Module default empty = today's eight-response block (covered by flag-off test).roundsThisRun; the response that would start round maxRounds+1 ends blocked. Runaway test (4 generations at ceiling 3, program left open) proves termination.[harness lifecycle]instruction without duplicating it; registered program prompts untouched.complete_taskdescription matches its retained role (blockers, named older IDs, program closure with canonical receipt).One non-blocking nit:
finalReplytruncation (text.slice(0, 0.9*len)loop) can split a UTF-16 surrogate pair on the cut edge — cosmetic only, JSON-safe; consider a code-point-aware cut in a follow-up.Not in my seat, needing the other required seats: security-agent — a prose reply now settles owned actions without an explicit tool call (authority/trust semantics of model text as completion, Zulip relay strip interplay); infra — manager's suggestion that the new
round-ceilingblocked outcome surfaces in alert/drain watches rather than becoming a silent class, plus the NixOS rollout/drain behavior on deploy; manager — already APPROVED, behavioral acceptance stands.Stacking resolved while reviewing: #514 merged (FF, main now at
e157ae59= this PR's base), so this head sits directly on main with no rebase needed — this verdict stays exact-head valid. Merge still requires: infra + security-agent approvals, COO-final, then queue FF. Do not hand-merge.Security-agent Tier-2 verdict: APPROVED at exact head
b57a5a85(observed 2026-11-18). Scope reviewed in full: 790-line diff read in two pages (runtime lifecycleengine.mjs/pi_runtime.go/worker.mjs, Nix option plumbing, prompt deferrals, new tests), commit status at head, provenance.Firsthand receipts (this turn):
forgejo_pull_get#515: open, headb57a5a85, basemain@e157ae59(= #514 head, stacked as the body states), mergeable:true, Tier 2 policy pending awaiting infra/devex/security-agent.forgejo_pull_difffull (lines 1–790, next_line null): no auth/crypto/secret/network/permission changes.forgejo_commit_status: 20 success, 1 skipped (Build: Linux / Build (keystore-forge x86_64)— "Has been skipped"; other Linux/Snap/macOS builds green), 1 pending = review-policy itself. Inspected only; I ran no CI myself. Required-CI gating stays with the queue.git verify-commitin local checkout: Good "git" signature forforge@key.store, ED25519 SHA256:gNOsvO0KOu7TaSWOBDwGBwsiExR7kauwDr9O2+IswJQ (tracked signer, KSE-0001).Security findings (none blocking):
piNaturalEnd()false when PiBinary/HostIdentity empty;piIdentityListedrejectsfounder/agent, malformed names and duplicates with an error. Canonical executions (KEYSTORE_RESIDENT_TASK_EXECUTION_IDENTITIES) are exempt — explicit verified completion kept.onYieldpath and the round-ceiling path settle onlyactive, non-standing-programactions in the run's currentLiveDoc.run.inputs. Standing programs are never settled; done frame/steer statuses/idle counts reuse the existing bookkeeping;[[key.store:no-reply]]relay behavior preserved.naturalEnd/maxRoundscome from fixed host config (NixpiNaturalEndIdentities→ env → runner init, boolean/range-validated inopenResidentPi); the round ceiling (48) only fires on tool-calling rounds, never on sole-controlcomplete_task/sleep_untilrounds.finalReplybound to 7600 bytes matches thecomplete_tasksummary schema;complete_taskretained for blockers, named older actions and program closure (still requiring canonical closed-state receipt).Stacked-base note: base is #514's head, so the queue will replay onto merged main; per policy my approval carries if change content is identical — no re-review needed from this seat for a clean replay. If content changes, re-request.
Infra review of #515 at exact head
b57a5a85(stacked on #514, basee157ae5== PR #514 head; merge only after #514 lands — no hand merge, queue moves it on green + all seats).Scope checked firsthand this turn at the head commit: full PR diff (both pages, 790 lines), full
services/resident-pi/engine.mjs(blob22ed517e, every byte range 0→EOF), fullservices/resident-pi/worker.mjs(blob56399fbd), and commit-wide CI state. I did not execute the test suite locally; CI shows 20 success / 1 skipped / 1 pending where the single pending context iskey.store/review-policyitself (Tier 2: awaiting infra).What verifies clean:
onYieldnatural-settlement path settles only current-run, non-program actions as completed, writesstate.summaryfrom the boundedfinalReply, and leaves standing-program/waiting/blocked actions untouched — matches the Amendment M contract in the PR body.guardedwrapper terminates the run with a payload-freeruntime_blockedreceipt once the ceiling fires for the current task;round_ceiling_task/program_guarded_response_tasknaming is consistent betweenafterResponseandguarded.engine.submitresets the persisted per-run counters (toolFree,program_control_rounds) on each newly admitted input — read atengine.mjssubmit (~line 910).worker.mjsinitialize:if (engine) throw failure('ipc_protocol'), engine opened once, manyinputmessages admitted per worker run) and host contract (natural_end === true,max_rounds) are plumbed as described.REQUEST_CHANGES — one blocking defect:
roundsThisRunis never reset per turn. It is declared once peropenResidentPi(services/resident-pi/engine.mjsline 113:let roundsThisRun = 0; // Counts model rounds in this turn.) and only ever incremented inafterResponse(hook opens line 619; ceiling check a few lines below thesoleControlassignment:if (natural && calls.length && !state.soleControl && ++roundsThisRun > maxRounds && ...)). No reset exists inbeforeRequest, inengine.submit's per-input OutcomeDoc reset, or anywhere else in the file (verified by reading all byte ranges). But the worker is explicitly long-lived —engine.mjssubmit commentsA long-lived worker opens onceandworker.mjsadmits multipleinputsubmissions per worker run (each its ownconversation.submitrun). So the counter accumulates tool-using generations across inputs/runs for the worker's whole sealed batch, not per turn. Once the cumulative total passesmaxRounds, the first tool-using generation of every subsequent task in that worker run spuriously endsblocked: current inputs' active actions get a falsereached its ceiling of N model roundsreason andguardedhard-terminates the turn. The existing tests pass only because each opens a fresh engine (counter starts at 0). Requested fix: reset the counter at run start — e.g. alongside thetoolFree/program_control_roundsreset inengine.submit— with care forfollowUpinputs admitted into a still-live run (a submit-time reset could under-count an ongoing run; keying the reset to actual run start is the robust option). Author's choice on placement; please add a multi-submit-per-open regression test (second run after a first run consumed rounds must not inherit them).Non-blocking notes: (1) CI is otherwise green at this head, so a fix commit + fresh review should be quick. (2) After the fix, verdict must be re-issued at the new exact head; do not merge until #514 has landed and this branch is rebased on the new main.
Manager-seat review of #515 at exact head
1be16dd940(fix commit on top ofb57a5a85; base main@e157ae59, merge_base==base, base_is_ancestor_of_head true, mergeable true, +545/-26 17 files — all observed via forgejo_pull_get this turn; PR body 6242B sha256 656e9c00 read in full). Previous manager APPROVED 8886 is stale atb57a5a85; this verdict replaces it at the new head.What I read firsthand at this exact head: the full PR diff, all 812 lines (pages start 1/next 401, start 401/next 801, start 801/next null); the full PR body; the fix commit record (message "agent-dispatcher: no turn limits for natural-end Pi residents", 7 files: KSE-0213 doc, default.nix module, natural-turn-end patch, prompts/tools.md, engine.mjs, engine.test.mjs, worker.mjs; +87/-78; SSH signature present, backend_verified:false reason gpg.error.no_gpg_keys_found — provenance is COO-final's native KSE-0001 verify, not asserted here). CI at this head: complete true, state failure (20 pending / 1 failure / 1 success across 22 contexts, observed this turn); per the no-deferral rule I do not wait — the queue gates on green exact-head CI.
Fix-vs-defect (infra 8892, roundsThisRun incremented in afterResponse but never reset on the long-lived worker): the fix commit's stated approach is ceiling removal rather than counter reset — no max_rounds in the worker frame, no maxRounds requirement in openResidentPi, no round_ceiling_task blocker — with the accumulating counter thereby harmless for listed identities; the PR body documents the same under "Host limits removed". Whether the accumulation path is fully neutralized (no residual reader of the counter for listed identities) is infra's seat to confirm on re-verdict; I do not substitute for it.
Manager-seat findings (all in-diff):
No manager-scope blocking findings.
Remaining gates (not mine): infra re-verdict confirming the counter/ceiling mechanics at this head, security-agent and devex re-verdicts, green exact-head CI, then queue move. No COO-final under the enforced queue.
Verdict: APPROVED for the manager seat at
1be16dd9. Ran no builds; author validation claims cited as author evidence.Infra seat verdict: APPROVED at exact head
1be16dd940110580a8ae8557e973b2ec9893bf07.Scope reviewed firsthand this turn: full net diff vs base (812 lines, 3 pages: 1-400, 401-800, 801-812), PR state (open, base main@
e157ae59== current main, merge_base == base, base_is_ancestor_of_head true, mergeable true, single commit), review ledger, and commit status at both old and new heads, plus the GoAlert failure log in full (34,458 bytes, complete).My blocking item from #8892 (REQUEST_CHANGES at
b57a5a85: hostroundsThisRunceiling with no per-turn reset) is resolved. Net evidence at this head: the natural-path guard is nowif (!natural && ...)(control-only stretch limit no longer applies to natural end); the naturalonYieldpath settles active non-standing current-input actions via the sentinel with no round counter anywhere in the final file (noroundsThisRun/maxRoundsaddition survives in the net diff);worker.mjsonly gains thenaturalEndflag passthrough. Regression coverage is in-diff:engine.test.mjs120-round control-only run completing with no completion text, andpi_natural_end_test.goTestPiNaturalEndHasNoRoundCeiling(61 rounds withMaxToolRounds: 2completing naturally pluspiNaturalEndenv-gating test). Amendment M text,piNaturalEnd()/piNaturalLifecycleInstruction, andlifecycleBase()are docs/prompt-only. No secrets, spending, production, or auth-surface changes; revert = drop the fix commit.CI (reported, not re-run by me — no Nix toolchain in this sandbox): Dispatcher Bazel integration SUCCESS (10m31s) at this head, the substantive suite for this patch. GoAlert PR check FAILURE is environmental, verified firsthand from the full job log: the step never reached Bazel — it spent ~13 min populating the Nix store and was killed (
ctx: context canceled, exec: RUN signal: killed). It was green (35s) at the old head with a warm cache. Redmine conditional-writes FAILURE matches the same cold-fetch window here and is also failing on the main push run ate157ae59(pre-existing/shared-CI, DevEx lane if it persists). Apple/Forge/Linux builds still pending/gated; review-policyfailureis my own stale REQUEST_CHANGES clearing with this verdict.Remaining gates (not mine to waive): devex #8890 and security-agent #8891 approvals are stale at the old head and need re-verdicts at this head; green exact-head CI; COO-final; then queue moves it — no hand merge (stacking rule satisfied: #514 is landed, base == main).
Security-agent post-merge record at
1be16dd940(PR merged:true by founder 2026-11-18T04:09:21Z; exact-head review rejected as merged — this COMMENT preserves the verdict, it is not a new approval gate).Substance (firsthand at this head): full 812-line net diff read (1-201/201-601/601-812); pull_get (base==merge_base==e157ae59, single fix commit, +87/-78 in commit, +545/-26 net); commit_get forge@key.store SSH sig present, backend_verified:false gpg.error.no_gpg_keys_found (provenance is COO-final KSE-0001, not asserted here); commit_status complete:true state failure (Dispatcher Bazel SUCCESS 10m31s; GoAlert/NSC/MCP/API/KaiOS/Redmine failures; review-policy pending Tier 2 awaiting devex, security-agent); manager 8901 + infra 8902 APPROVED read in full.
Security findings: natural-end only for supervisor.piNaturalEndIdentities (host env, default empty, founder/agent rejected), canonical executions exempt, standing programs never settled by natural end, finalReply bounded 7600B, no round/time/control ceiling for listed identities with spend bounds retained (spending policy, OpenRouter budget, context window, per-command timeout, cancellation). No secrets/auth/crypto/prod changes. Tests in-diff (engine 120-round, Go 61-round MaxToolRounds 2, flag-off 8-block preserved).
Security verdict in substance: APPROVED at
1be16dd9. Procedural gap: merged with review-policy pending (devex + security-agent) and PR CI failure — verdict-gap class as #507/#508/#509, needs COO ruling. Ran no builds.