Repository navigation
sync up - #4
Open
tearsofphoenix wants to merge 10000 commits into
Open
sync up#4tearsofphoenix wants to merge 10000 commits into
tearsofphoenix wants to merge 10000 commits into
Conversation
* fix(agents): finish deletion when personal pins change Refresh cleanup preservation once when a personal pin publication invalidates precommit preparation. Keep deletion custody and target plans, revalidate current source and execution authority, and never replay unknown native outcomes. Allocate 58 regression-test lines for the real Gateway deletion race, including canonical preference publication and unchanged pin-protection coverage. Co-authored-by: vincentkoc <25068+vincentkoc@users.noreply.github.com> Co-authored-by: RomneyDa <6581799+RomneyDa@users.noreply.github.com> * fix(ci): align transcript reuse accounting expectations Reuse the already-landed upstream repair to unblock deletion CI. Custom state records hydrate normally without contributing context-byte accounting. (cherry picked from commit ed176db) Co-authored-by: vincentkoc <25068+vincentkoc@users.noreply.github.com> Co-authored-by: RomneyDa <6581799+RomneyDa@users.noreply.github.com> --------- Co-authored-by: vincentkoc <25068+vincentkoc@users.noreply.github.com> Co-authored-by: RomneyDa <6581799+RomneyDa@users.noreply.github.com> Co-authored-by: Vincent Koc <vincentkoc@ieee.org>
* feat: open shared sessions in their source Control UI * feat: open shared sessions in their source Control UI OpenClaw-Publication: a3826b6b-5899-8ff2-a1b5-84961c64219f * Merge remote-tracking branch 'origin/main' into land/open-original-203044 * origin/main: fix(ci): decouple boundary fixture from timing inventory (#203026) fix(ci): shard capable compatibility UI targets (#203042) perf(agents): restore selected subagent payloads once (#203039) fix: keep standalone context from completing QA tool steps perf(sessions): reuse sealed ownership for context projections (#203040) refactor(hooks): separate event predicates from hook registry (#203017) fix(ci): align update export audits with their consumers (#203030) fix: keep cold baseline checks within the existing heap limit * fix(session-share): accept the runtime config snapshot in the source link resolver The stored-session link resolver took a mutable config, so the plugin's readonly runtime snapshot failed production and test typechecks. Accept the snapshot type. Document the real Open original setup: allow the link command on the receiver Gateway, set the source Control UI origin, reinstall the source node with all three commands, then approve the widened surface. Move the section ahead of Security boundary and add a troubleshooting entry. Assert through the Gateway catalog list that a provider-supplied link survives streamed and final rows, and drop the menu unit test the browser fixture covers. * Merge remote-tracking branch 'origin/main' into land/open-original-203044 * origin/main: refactor(test): remove duplicate token startup wait case (#203087) fix: keep Plugin SDK declarations within the build limit fix(ci): remove unused hook type exports (#203074) fix(test): exercise the sign-in callback path guard (#203075) refactor(tts): separate caption eligibility from text helpers (#203068) test: reuse worker preload options (#203058) refactor(test): share Bun native-policy test launcher (#203064) fix(cron): a chat-created automation's failure notice reaches that chat (#203056) refactor(test): remove duplicate claw origin rejection case (#203067) refactor(channels): move chunk-mode lookup to streaming readers (#203047) refactor: separate skill queries from workspace discovery (#203045) fix: resume new chat turns in retained tasks after a restart refactor: separate usage pricing preparation from formatting (#203043) fix: avoid repeated filesystem probes before agent turns (#203057) perf(agents): preserve sealed history during endpoint compaction (#203037) fix(test): give deferred identity fixtures read scope (#203053) refactor(test): remove redundant channel catalog facade (#203052) refactor(cli): isolate daemon port presentation (#203020) refactor(cron): isolate CLI input parsing (#203031) * chore(plugin-sdk): record the approved session-discussion surface growth Open original adds two exports to openclaw/plugin-sdk/session-discussion: the stored-session Control UI path resolver and the session path parser. Raise the public export and callable budgets by two for them. Use neutral fixtures for the rejected-origin and rejected-query URL tests so the fixtures do not resemble credentials; the same rejections are covered. Co-authored-by: Vincent Koc <vincentkoc@ieee.org> Co-authored-by: vincentkoc <25068+vincentkoc@users.noreply.github.com>
* perf(infra): batch directory watch replies for catalog workers Forward each synchronous native-watch burst in one worker message, retaining every event and error in order. Reuse the channel batch buffer after synchronous message cloning to avoid per-chunk allocation. Preserve shared helper admission, retirement, recovery, and per-watch routing. * test(infra): type the encoded watch benchmark input
* fix(openai): plain ChatGPT sign-in steps on setup screens A local ChatGPT sign-in no longer opens with an "OpenAI Codex OAuth" note about redirect URLs and localhost:1455; it starts the browser sign-in directly. The paste fallback now explains itself in its own prompt (setup screens show only the newest step), uses plain wording, and waits 60 s instead of 15 s so it does not appear while someone is still signing in. * fix(openai): preserve ChatGPT paste fallback timing
…rn ends (#203113) ## Problem In a worktree session, the first turn starts a background exec with an exit wake and calls `sessions_yield`. When the command exits, the wake is refused before it starts with `Session changed while preparing its project; retry the task.` The exec result never reaches the agent. The chat then shows "This turn yielded, but no registered continuation can resume it. The run has ended." The user has to send another message to get the agent going again. Cause: the first turn of a session with a deferred checkout runs inside `runWithAgentWorkspaceReadiness` (#169136). The exec child's exit callback runs in that turn's async context, so it inherits the turn's workspace gate. After the turn yields and ends, the session-event wake reaches `admitReplyTurn`, which captures the inherited gate and calls its `assertCurrent()` in the store-writer phase. The retired run is no longer registered, so the check throws the ownership error, about 10 ms after admission starts. Nothing in the session changed. The production log matches: `lifecycle-admission failed reason=writer`, then the refused wake. Agent runs and follow-ups already clear this gate (#170791). Session-event wakes, queue and mailbox drains, and subagent announce/cleanup did not. ## Fix `runOutsideAdmittedTurnScopes` (renamed from `runOutsideAdmittedGenerationScopes`) is the single entry point for detached work that is re-admitted when it executes. It now also drops the inherited workspace gate, the same way it drops the inherited plugin generations. Every detached re-admission now runs under the gate of the turn it actually starts. The name change touches only its existing callers. A pre-start failure is not retried. A retry would have run in the same leaked context and failed the same way, and with the cause removed this failure no longer happens. A real session change before the wake (deleted chat, reset) keeps its existing behavior. ## Evidence - Regression test (`bash-tools.exec-background-followup.test.ts`): a real background exec started inside a turn's workspace gate. The gate retires before the command exits, and the test asserts that the wake turn runs and its prompt carries the exec output. Red on base with the production error, green with the fix. The rest of that file and the consumer tests (session-event, queue, mailbox, subagent announce, chat-send/agent-run readiness) pass. - Real Gateway, base vs head, from source. Isolated state, real model (OpenAI, embedded OpenClaw runtime). `sessions.create` with `worktree: true` and an initial message, so the checkout is deferred as in the incident. The agent runs `sleep 20; echo <marker>` in the background with an exit wake, then calls `sessions_yield`: - base: the wake fails with `session event execution failed source=exec ... Session changed while preparing its project`, then `completion delivery failed`. The transcript ends with "This turn yielded, but no registered continuation can resume it." - head: the wake turn runs, and the agent replies with the exact marker. No ownership errors. - `tsgo:core`, `check:test-types`, oxlint/oxfmt on the changed files. The `max-lines` finding on `session-event-handoff.ts` is inherited: the file has the same line count as on `main`. ## Merge danger Two-way door: no state, schema, config, or published contract changes, and a revert fully undoes it. Blast radius if wrong: detached wakes (exec, cron, restart, subagent completions) and queued follow-ups no longer see an inherited first-turn workspace gate. They admit against current session state, as agent runs and follow-ups already do. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
…zation (#203095) * refactor(agents): separate pure model references from runtime normalization * refactor(agents): erase type-only model reference imports
* refactor(feishu): separate message parsing from bot runtime * test(feishu): document bot dispatch isolation
…ades (#203130) ## Problem The Gateway's startup state upgrade copies state into a shadow, runs the Doctor chain there, and swaps the result in. To bound the copy, it leaves out current SQLite files larger than 64 MiB (`src/state/state-upgrade-tree.ts`, from #199929). Doctor, running in that shadow, then sees the registered main agent database as missing and removes its `agent_databases` row (`discoverAgentDatabaseMigrationTargets` in `src/infra/state-migrations.media-persistence-targets.ts`). The conservation check reports `openclaw.sqlite:agent_databases 5 -> 4`, but the swap keeps the result. Seen on a copy of a real state directory (Linux, no network). The main agent database (3.7 GB, already at the current schema) lost its registry row in every boot. The file and its sessions were intact: 1,187 sessions and 712,991 transcript events, and `sessions list` and `agents list` still worked. The registry is the only owner record for an agent database outside config, so an unconfigured agent drops out of discovery until something opens it again. ## Change - Doctor no longer unregisters an agent database only because its file is missing. It still reports `Skipped missing registered agent database <path>.` - The relative session store repair (runs in Doctor preflight, so also inside the shadow) no longer unregisters a missing source either. Its cleanup after a verified move is unchanged. - Real deletion keeps its own unregister path (`unregisterOpenClawAgentDatabases`). Runtime readers handle a registered row whose file is missing: the read-only opener returns `database-missing` (`openclaw-agent-db-readonly-open.ts`), session listing returns no entries, and auth lookup returns nothing. Only an explicit writable open creates a database, and that path does not come from registry discovery. Accepted edge case: a file that is really gone keeps its row and the warning, instead of being forgotten automatically. ## Evidence - New `src/state/state-upgrade.large-agent-db.test.ts` (database-worker lane): a registered, current agent database larger than 64 MiB keeps its row through `upgradeStateDirectory`, with no conservation mismatch and no pinned generation. - On `origin/main` 3eb60f7: `expected [] to deeply equal [ { agent_id: 'main', … } ]`. - With this change: passes. - Updated tests that asserted the removal: `state-migrations.media-persistence-targets.test.ts`, `agent-deletion-journal-initialization.test.ts`. - Focused run, 5 files and 49 tests passing: `state-upgrade.test.ts`, `agent-deletion-journal-initialization.test.ts`, `state-migrations.media-persistence-targets.test.ts`, `doctor-relative-session-store.test.ts`, and the new test. - Real-state boot, control on `origin/main` 3eb60f7: `agent_databases 5 -> 4`, main absent, pinned. Doctor took 99.8 s and the whole boot 168.5 s. - Real-state boot, with this change (built from `git archive` of this commit; the compiled `state-migrations.media-persistence-targets` chunk has the `Skipped` warning and no `Removed missing agent database registry entry`): `agent_databases 5 -> 5`, main present, conservation clean, not pinned. Doctor took 72.6 s and the whole boot 119.2 s, all exit 0. The log still shows `Skipped missing registered agent database` for the omitted shadow file. - Both runs used fresh copies of the same state; all 17 SQLite files passed `integrity_check` before boot. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
Preserve the existing requester restart reason in announce classification so unconsumed completed results remain pending for startup custody. Existing consumption receipts prevent replay; permanent refusals, explicit cancellation, and ambiguous sends retain their policies.
…int (#203139) Co-authored-by: Peter Steinberger <steipete@gmail.com>
…e a code (#202071) * fix: guide owners to secure access when a new Gateway can't make a setup code A loopback-only Gateway refuses device.pair.setupCode. The refusal now carries the DEVICE_PAIR_GATEWAY_LOOPBACK_ONLY error detail, and Connect a device shows Set up secure access: Tailscale Serve first, then trusted home network instructions with what gateway.bind lan opens and how to undo it, and Retry. Loopback stays the default; the dashboard changes no settings. Refs #202045 * fix: keep secure-access setup out of the Control UI boot bundles The loopback-only detail code moves to its own protocol module, the pairing state keeps the raw create failure for the dialog to classify, and the secure-access copy loads with the dialog. Boot JS sizes match main; the commands inside disclosures no longer get the setup-code box. * fix(ui): explain how to resume pairing after Gateway restart Co-authored-by: Solvely-Colin <211764741+Solvely-Colin@users.noreply.github.com> * fix(ui): clarify who can reach the Gateway through Tailscale Serve Co-authored-by: Solvely-Colin <211764741+Solvely-Colin@users.noreply.github.com> * fix(ui): keep secure access guidance on phone pairing --------- Co-authored-by: Solvely-Colin <211764741+Solvely-Colin@users.noreply.github.com>
…air (#203023) * fix: stop clean updates warning about skipped agent database path repair Update Doctor returned "Skipped agent database path repair during update Doctor" before reading the registry, so every successful update on every platform reported a warning and pointed at doctor --fix with nothing to repair. The repair now classifies registrations once: update Doctor and an active update run stop after the count and warn only when it is above zero, naming the count; standalone doctor --fix writes from the same result. The deferral is unchanged: nothing in agent_databases or on disk is rewritten or removed during an update. Production net 0 lines. * style: format the doctor database path repair test Co-authored-by: Vincent Koc <vincentkoc@ieee.org>
…203118) ## Problem On a fresh profile with no model chosen, signing in with OpenCode Go (Settings → Models → Add account → OpenCode Go → browser sign-in) ends on a dialog that says only "OpenCode Go (browser sign-in) is ready". It names no model and offers no "Start a new chat". The agent still has no primary model, so chat then shows "Set up a model". Two causes: 1. **A credential-only sign-in never chooses a model.** Nearly every browser and device sign-in (OpenCode Go, OpenCode, OpenAI, OpenRouter, Copilot, MiniMax and others) is declared `credentialOnly: true`. `src/gateway/server-methods/models-auth-login.ts` sends these to the credential wizard, which only saves the account. The dialog could name a model only from a later catalog read that looked for a `recommended` row. That read finished 2–4 s after the dialog appeared: in the incident log the dialog was closed at about +1.9 s and the catalog replies arrived at +3.9 s and +5.8 s. Even when the starter did appear, it only pinned the model on the new session, so the agent primary stayed unset. 2. **"Is a model available?" stood in for "has this agent chosen a model?"** #172826 decided both the setup prompt and the sign-in mode from `configuredModels.some(available)` (`login-controller.ts` `connectProvider`, `view-status.tsx` `needsModelSetup`). Any available catalog entry fails that check, for example a running local llama.cpp model or an installed OpenCode CLI. "Set up a model" then disappears even though the Models page still shows "Model: Select a model". Every other "Add account" button always opened in access-only mode. The predicate shipped in v2026.11.6. ## Fix - **Gateway (`models.authLogin`):** when a credential-only sign-in is started with the existing `selectModel: true` flag and the agent has no configured primary, it saves the credential as before, then: - reads the agent's catalog for that provider, refreshed so the new account's own models are listed; - picks the hosted catalog's recommended available model, else the account's first available model; - hands the saved profile to the existing saved-sign-in activation owner (`saved-auth:<profileId>`). That owner live-verifies the route, writes the primary and returns `modelActivation`. - The primary is read from config after sign-in (`resolveNativeModelPrimary`), so an operator's choice made before or during sign-in is never replaced. - If verification fails, the error says the sign-in was saved and names the next step. - If the account lists no available model, the result is the same as today, and the Gateway logs this non-outcome. - **Activation wizard body:** extracted into `runSetupActivation` in `system-agent-setup-wizard.ts`, so setup and sign-in share one implementation instead of two copies. - **Control UI:** one predicate everywhere, "this agent has a configured primary" (`resolveAgentModelPrimary`: the agent's model, else defaults; the same source as "Select a model"). - The Models page shows "Set up a model" until the agent has a chosen model. - Every Models-page entry point sends `selectModel` only for an agent without one. - `connectProvider(models)` and `needsModelSetup` are deleted. - A pasted secret still only saves. - The "no usable models" wording appears only when that is true. ## Engineering decisions (consulted Fable 5.2) - **Reused the saved-sign-in activation; did not reroute to the setup activation.** Sending credential-only choices into the setup activation would drop the secure browser callback. It would also run each provider's non-credential-only sign-in path, which may return no starter model, so a good sign-in would end in an error. That is a regression for OpenAI, Copilot, MiniMax and the rest. - **When there is no recommendation, fall back to the first available model.** Without the hosted catalog nothing is marked recommended, and stopping there would strand a first-time user (UX rule: no stranded user). The provider's catalog order picks the model. - **Primary write shape:** the activation owner pins the account (`provider/model@profile`) on the agent entry. It may also write the Gateway's current implicit route into `agents.defaults.model`, as it already does for setup. That implicit route goes away with the separate "no invented default model" change. ## Impact - A first-time user who signs in with OpenCode Go sees "<model> is ready for your agent." and "Start a new chat with <model>" in the same render. The agent's primary is set, and the new chat answers. - An agent that already has a primary keeps it: the sign-in only saves the account, as today. - No protocol or schema change: `selectModel` already exists on `models.authLogin`. ## Evidence **Real Gateway E2E, new `ui/src/e2e/provider-browser-login-first-model.real-gateway.e2e.test.ts`.** Real HTTPS Gateway, real browser callback sign-in (fixture provider), fresh profile, plus an available local model like llama.cpp. The test checks: - the local model is listed and available, yet "Set up a model" shows; - browser sign-in completes, and the dialog names the model and offers the starter within 1 s of "ready"; - the agent primary is `browser-login-fixture/ready@browser-login-fixture:default`; - Start a new chat, then send "Write a limerick about OpenClaw.", and the reply arrives; - the page never shows "Set up a model" or "Couldn't load models from openai". Results: - head: passes; - 346078f (the incident build): fails ("Set up a model" never appears); - the existing `provider-browser-login.real-gateway` E2E passes on head. Its fixture now saves an OAuth account, like OpenCode Go's Console sign-in. Before (346078f), 6 s after "ready":  After:  Before and after, Models page with only a local model available:   **Regression tests (red on merge base `a48440bbdf3e`, green on head):** - `models-auth-login.test.ts` "a credential-only sign-in selects the account's recommended model only without a primary": the no-primary case fails on base and the explicit-primary case passes on both. - `model-providers-page.login-select-model.test.ts` "a browser sign-in selects the first model only for an agent without one": the no-primary case fails on base, and the explicit-primary case (no takeover) passes on both. **Gates:** `ocx test` over `ui/src/pages/model-providers`, `ui/src/pages/model-setup`, `ui/src/lib/agents`, `models-auth-login.test.ts` and `test/vitest-ui-e2e-config.test.ts`; `pnpm tsgo:ui`, `pnpm tsgo:core`, `pnpm check:test-types`, oxfmt and oxlint on changed files. **Not covered here:** the real OpenCode Console approval needs a human; it is next, on a fresh profile. ## Merge danger - **Two-way door.** A revert restores the old behavior. Primaries written by the new path are ordinary config that the user can change. - **Blast radius:** first sign-ins through the Control UI for agents with no configured primary. Agents with a primary are unaffected. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
…r a config republish (#202781) Co-authored-by: VACInc <3279061+VACInc@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Move Code Mode and Tool Search to Agent defaults → Tools, keeping Auto eligibility, explicit model/agent choices and Node/QuickJS selection intact. Make Templates normally available under Customize without writing a missing default into saved config. Preserve explicit opt-outs and the existing review, installation, consent and publication authority checks. The cached archived/deleted-parent paint assertion remains a separately documented pre-existing test failure, not a claimed repair or green CI result. Co-authored-by: vincentkoc <25068+vincentkoc@users.noreply.github.com> Co-authored-by: fuller-stack-dev <263060202+fuller-stack-dev@users.noreply.github.com> Co-authored-by: Patrick-Erichsen <20157849+Patrick-Erichsen@users.noreply.github.com>
Retain raw item pages only for reusable pull-request and commit overviews. Complete reader documents keep the rendered projection without an unused full API body. Preserve overview reuse, access checks, output bytes, and request counts.
…n its own part (#203174) Root cause: src/shared/assistant-answer-text.ts:24 picks only text blocks that carry a signature as the answer, which is meant for OpenAI Responses item ids. Since #170534 (first shipped in 2026.11.5) it also picks empty signed blocks. Gemini 3 sends its thought signature on a separate empty part after the answer, so the selected answer is `""`, the turn is marked empty rather than silent, and the `NO_REPLY` text is delivered. Fixes #203131 Thanks @Avi711 for the clear report and trace. ## What Problem This Solves With Gemini 3 on a `google-generative-ai` provider, a reply of exactly `NO_REPLY` reaches the chat as the text "NO_REPLY" instead of ending the turn silently. It happens in direct chats and in automations that announce their result. 2026.8.2 stayed silent. ## User Impact Gemini 3 replies of exactly `NO_REPLY` end the turn silently again, in direct chats and in announced automations. Normal Gemini answers are delivered as before. ## Why This Change Was Made Signed-block selection now applies only to OpenAI Responses messages, where a text signature is an output item id. A Gemini thought signature is not an item id, so Gemini answers use all of their text blocks. The Google stream reader still keeps the signature-only part as its own block. That keeps the next request byte-identical: the signature is replayed as its own empty part, as Gemini sent it. Attaching the signature to the previous text block would change those replayed bytes. Responses answer selection is unchanged. ## Evidence Real Gateway (`ocx src`, isolated profile state) with the QA channel recording deliveries and a local `google-generative-ai` fixture that streams `{"text":"NO_REPLY"}` and then `{"text":"","thoughtSignature":"..."}`. Base is the merge base 423ae09. | Check | Base | This PR | |---|---|---| | Direct chat, exact `NO_REPLY` | "NO_REPLY" delivered | nothing delivered | | Announced automation, exact `NO_REPLY` | "NO_REPLY" delivered (`deliveryStatus: delivered`) | nothing delivered (`not-delivered`) | | Normal answer with trailing signature part, 2 turns | delivered once per turn | delivered once per turn | | Next request replays the signature | `[{"text":"Here is…"},{"text":"","thoughtSignature":"Q2lN…Sw=="}]` | identical bytes | The new regression test fails on base (`disposition: 'empty'`, expected `'silent'`) and passes here; its OpenAI Responses row (signed empty item still wins) passes on both. Observed proof lines: #203174 (comment) Merge danger: two-way door. No stored state, config or published contract changes; a revert fully restores the old behavior. Blast radius: answer text selection for non-Responses messages that carry text signatures (Google Gemini), which now use all of their text blocks. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
…registry (#203516) ## What Problem This Solves #203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call; it now only checks Stop and carries the caller receipt's session fences. The `sessions_*` tools and the subagent registry still captured it and called it again at each step. Those calls are dead weight. Some of them also used "the capture returned a function" to mean "this is an admitted agent run". ## Why This Change Was Made Admission checks permission one time, when work starts. This PR removes the leftover capture from the session tools and the subagent registry: - `sessions-list-tool.ts`: the capture and its call in `finalize`; the tool signal check stays. - `sessions-tool.ts` (`assign_owner`), `sessions-tool-control.ts` (`captureSessionStopCaller`, `stopSessionTool`): the admitted-run gate reads `caller.operationalRunInstance`, which is the condition the capture tested. The tool signal check stays at each step. - `sessions-operator-authority.ts`: the `sessions.patch` capture is removed from the composed control source. - `sessions-send-communication.ts`: the capture is removed from `assertSource`, which already checks the tool call's `signal` and closes on abort. The approval gate reads `caller.operationalRunInstance`. - `sessions-send-tool.delivery.ts`, `sessions-send-tool.steering.ts`: the steering guard still uses the guarded (V2) injection for an admitted run. Stop reaches it through `assertSendCurrent` (the communication assertion, which is signal-bound). - `sessions-send-followup.ts`, `sessions-send-followup-custody.ts`: the follow-up checks are the prepared custody (`request.custody.assertCurrent`) only. - `sessions-send-resume.ts`, `gateway/session-subagent-resume.ts`: a live admitted caller has no `assertCurrent`. A host-retained replay keeps its retained source assertion. `requirePausedChild` runs `caller.assertCurrent?.()`; admission is decided once in `captureSessionsSendResumeCaller` (the only producer of this caller). - `subagent-registry-public-api.ts`, `subagent-registry-requester-claim.ts`: the registry writes keep the state-worker source check and the continuation custody. Session write fences are not dropped. Every sessions tool write goes through the in-process Gateway caller (`in-process-gateway.ts`, PR 1d), which still composes the caller's receipt into `sessionMutationCommitGuard`. The removed captures were all sync closures (Stop only) or duplicated that composed fence. No new export, name, hook, flag or guard. Production: 13 files, +43 / −108. Accepted edge cases (no code for them): - `acknowledgeSubagentResultForRequesterTurn` and `claimSubagentYield` no longer check Stop before their registry write. These are internal bookkeeping writes for a result the run already has (mark delivered, record the yield), not user-visible effects. - `prepareSessionsSendFollowup` no longer checks the tool Stop during its preparation reads. The dispatch that follows stays signal-fenced through the communication assertion. ### Changed tests - `sessions-tool.self-archive.test.ts`, `agent-tools.session-owner.test.ts`: `sessions.assignOwner` no longer carries `assertDispatchCurrent`. - `sessions-send-communication.test.ts`: the mocked caller now has an `operationalRunInstance` (that is what "admitted" means now); the removed capture mock is gone. No test asserted a mid-run refusal through these callers, so no test was deleted. ## User Impact None visible. An admitted session tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict. ## Evidence - Pre-push: one `ocx test` run with fail-fast off over 41 files (every direct importer of a changed source, plus importers of the test-support files that import them). After the test fixes, everything is green except: - `agent.test.ts` ("honors owner cancellation while explicit recipient session routing is pending", "does not deliver prepared identity after the client loses authority") and `question.communication.test.ts` ("retains creator/admin rights without treating assigned responsibility as authority"): also red on the merge base `6ff7a062e54e`. - `server.plugin-reload-send-revocation.product.test.ts`: it expects "Operator access was revoked; start a new user turn.", which no production code emits since #202513. On head the revoked replay is still refused with 0 effects; the notice says "Restart recovery operator authority changed; start a new user turn.". On the base it timed out under host load. - `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean. - Head E2E: Q, R and S pass (#203516 (comment)). Local review on the final head: patch correct, zero findings. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
## What Problem This Solves #203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call. Its Gateway-side callers still captured it and called it again at every step. That is dead weight: after #203487 the call only checks Stop, and most of these callers already check Stop through their own request signal or commit guard. ## Why This Change Was Made Admission checks permission one time, when work starts. This PR removes the leftover capture from the Gateway-side callers, so the per-step re-check path is gone there. Removed (capture and its calls): - `server-methods/themes.ts`, `tools-github.ts`, `users-personal-file.ts`, `environments.session.ts`, `request-authorization.ts` (startup exemption for admitted runs); - `session-access-authority.ts`, `session-runtime-authority.ts`; - `server-plugin-in-process-dispatch.ts` (`runWithInProcessGatewaySessionMutation`); - `server-plugin-in-process-authority.ts` (continuation capture); - `github-publication-auto-fix.ts`; - `plugins/service-session-work.ts`. Where a caller used "capture returned a function" only to mean "this is an admitted agent run", it now reads `caller.operationalRunInstance`, which is the same condition the capture tested. `resolveSessionRuntimeAuthority` now returns nothing when no runtime identity exists (the caller-only branch was a Stop check only). Stop still applies at every changed site: - In-process Gateway methods (themes, GitHub read, personal file, environments, auto-fix, session mutation) still call `sessionMutationCommitGuard` / `resolved.assertContextCurrent`, which keeps the caller's Stop and receipt fence (see below). - `tools-github` and `environments.session` already combine `caller.approvalSignals` into their signal. - Service session work keeps Stop through `captureAmbientGatewayOperatorAuthority().assertInvocationCurrent`. - The continuation capture now checks `caller.approvalSignals` directly at the same point. Kept on purpose (cut less): two sites carry the capture's receipt fence into session commit guards, so they keep it until PR 6 removes the lease at `captureAdmittedRunActiveAssertion`: - `resolveInProcessGatewayDispatch().assertContextCurrent` (`server-plugin-in-process-authority.ts`); - `captureOperatorToolGatewayAuthority` / `captureAmbientGatewayOperatorAuthority` (`operator-invocation-authority.ts`, left unchanged). The receipt fences the writing run (lease held, same run instance), which the session owner's `sessionMutationAuthorization` does not cover; an abort signal cannot replace it. No new export, name, hook, flag or guard. ## User Impact None visible. A tool call that was admitted keeps running to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict. Gateway methods during startup still accept admitted agent runs. ## Evidence - Pre-push: one `ocx test` run with fail-fast off over 113 files (the touched sources' own tests, every direct importer of a changed file, importers of the 12 touched `*.test-support.ts` dependencies, and every test that names `captureGatewayToolCallerAssertion`): 112 files green. `server.private-completion.test.ts` timed out one case under host load (22.9 s wait) and cascaded into its sibling case; alone it passes 27/27. - `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean. - No test asserted a refusal through these callers, so no test was deleted. - Production: 11 files, +43 / −91. `config/session-identity-allowlist.txt`: `request-authorization.ts` 7 → 6 (the removed refusal string was a counted pin). - Real Gateway E2E (one-admission journey) on the final head `f3c8465e7234`: Q (revoke while queued → refused visibly), R (revoke while running → finishes), S (Stop → cancels) all pass: #203503 (comment) - Local review on the final head: patch correct, zero findings. - CI: every red job is MAIN-ALSO, with per-test base evidence in #203503 (comment) (#203512, #203527). Co-authored-by: Ayaan Zaidi <hi@obviy.us>
…3520) Root cause: `src/cli/daemon-cli/status.config.ts:99` and `src/cli/update-cli/status.ts:333` validate the config as written with `validateConfigObjectRaw`, skipping `applyImplicitAgentRosterDefaults`, which the normal snapshot load applies first (`src/config/io.snapshot.ts:252`). The schema rule "agents.entries must contain at least one configured agent" is written for the loaded view, so a config without `agents.entries` fails it only in these two readers. Fixes #203505 Thanks @woodmanlegion for the report and the clear trace of the two readers. ## Problem A config with no `agents.entries` is supported since #112678: the normal load adds `{ main: {} }` in memory. `openclaw models set openai/gpt-5` in an empty profile writes exactly that shape. `openclaw config validate` and `openclaw gateway status --deep` say the config is valid, but `openclaw gateway status` (fast path) and `openclaw update status` mark it invalid and send the user to `doctor --fix`, which finds nothing. ## Fix The two fast readers now run the existing `applyImplicitAgentRosterDefaults` before `validateConfigObjectRaw`, the same order the snapshot load uses. No second implementation, no schema change, no config write: the file is unchanged and real config errors still report as before. Callers of the raw validator checked: - `gateway status` fast path (`readFastStatusConfig`): had the gap, fixed. - `update status` (`readSourceConfigBestEffort` + raw check): had the gap, fixed. Other callers of `readSourceConfigBestEffort` do not validate. - Doctor repair, heartbeat repair, setup native runtime: validate `snapshot.sourceConfig` or a loaded config, already normalized. ## Evidence Built CLI in a secretless `node:24.22.1` container, empty profile per scenario, `openclaw models set openai/gpt-5`, then the four commands. Full output: #203520 (comment) | Scenario | Build | gateway status | update status | config validate | gateway status --deep | |---|---|---|---|---|---| | defaults only (no `entries`) | main | invalid | invalid | valid | valid | | defaults only (no `entries`) | this PR | valid | valid | valid | valid | | explicit `entries.main` | main / this PR | valid | valid | valid | valid | | `ownership: "explicit"`, no entries | main / this PR | invalid (same message) | invalid | invalid | invalid | | `gateway.port: "not-a-port"` | this PR | invalid (port issue only) | invalid | invalid | invalid | On main the port scenario also lists the false `agents.entries` line next to the port issue in the two fast commands; this PR drops only that line. The config file hash is unchanged after every run. Tests: two existing fast-read cases (`status.gather` fast config read, `update status` remote JSON) now carry a defaults-only `agents` section; both fail on main and pass here. Size: production +4/-2, tests +3/-0 against the merge base; no new helper, flag or state. ## Merge danger Two-way door: read-only diagnostics, no state or config written; a revert fully restores the old output. Blast radius: the config-validity lines of `openclaw gateway status` (fast path) and `openclaw update status`. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
…launcher copies (#203529) Homebrew's periodic `brew cleanup` removes dangling symlinks and empty directories below its prefix, including the relative launcher copies a package activation anchor retains under lib/node_modules. Remount settlement bound those roots and failed with ENOENT on <anchor>/launchers, so `openclaw update repair` could never settle the operation. Settlement never republishes them: an absent root is now accepted, a present one must still match its recorded identity. Refs #197910
…d it (#203521) ## Problem Every queued, scheduled, replayed or resumed start re-admits its saved requester through `src/gateway/operator-run-recovery.ts`, which runs `prepareOperatorAdmission` + `decideOperatorAdmission`. `decideOperatorAdmission` only narrows the saved scopes to the current role, and it refuses only when no scope is left. So a requester whose role changed to read-only before the start was admitted with `["operator.read"]`. #203468 closed this for the queued `/followup` path only. Audit on `main` (requester's role changed before the start): | Start | Creation grant | Read-only on `main` | |---|---|---| | Queued chat, `/followup`, collected batch, Goal successor | write | refused (#203468 per-path check) | | Restart replay of a queued chat input | write | refused later by `chat.send` method scopes | | Restart completion wake | write | refused later by `agent` method scopes | | System turn, restart resume | write | refused (`prepareSessionPrincipalRunAccess`) | | Worker environment provision resume | admin (`environments.create`) | **starts** | | Plugin service session work | the run that accepted it | **starts** | | Cron agent turn, command, script | cron | **starts** | | Cron conversation event | cron | **starts** at the event target (refused later only by #203468's write check, which also refused cron-only creators) | | Native stream source | cron | **starts** | | Scheduled plugin command | cron | **starts** | | In-run continuation | (started run) | admitted, must stay admitted | ## Fix One private admission body, two exported start entries that differ only in the grant they require now: - `restoreGatewayQueuedOperatorRecovery` / `restoreGatewayOperatorSource`: the requester must hold `operator.sessions.write` (write, admin and own-session write satisfy it; what a live `chat.send` needs). - New `restoreScheduledAutomationOperator`: the requester must hold `operator.cron` (write and admin satisfy it; what creating an automation needs). - Refusal uses the existing `GatewayOperatorRecoveryAuthorizationError`. Channel senders (`channelRecoverySource`) are exempt, as before. `captureGatewayOperatorContinuation` uses the private body without a start grant: a started run finishes. Each call site picks its entry by the grant that authorized creating the work: - Automation entry: cron runs (`cron-operator-source.ts`), native stream sources (`cron-stream-source-authority.ts`), cron conversation events (`session-event-target.ts`; only cron supplies a deferred operator source there), scheduled plugin commands (`plugin-command-scheduled-run.ts`), and the queued follow-up of a cron conversation event (`queue/lifecycle.ts`, when `scheduledAutomation` is set). - Write entry: queued chat and `/followup` (`queue/lifecycle.ts` otherwise), restart replay, completion wake, system turns, worker provisioning resume. - Plugin service session work is the one site whose work can come from either a chat turn or a cron run, and it stores only the run's snapshot. It reads the grant from that snapshot: a snapshot that held `operator.sessions.write` needs write now; one that held only `operator.cron` needs cron or write now. No new state. - #203468's per-path check in `queue/lifecycle.ts` is deleted; the shared entries cover that path. ### Decisions - Option 2 of the design review: the entry name carries the start kind. No parameter or flag, and no exported generic entry, so a start with no stated kind cannot be written. - `decideOperatorAdmission` is unchanged: it cannot tell a start from a continuation from its facts. - Accepted edge case: service work that a cron run started for a writer later moved to a cron-only role is refused visibly at its next start, because its snapshot held write. Every other automation from that writer keeps starting through the automation entry. - Completion wakes and system turns stay on the write entry even when a cron run caused them: on `main` they already needed write (`agent` method scopes, `prepareSessionPrincipalRunAccess`), so no cron-only creator loses anything. - The sandbox stream keeps its own `operator.write` check (`cron-stream-sandbox-authority.ts` calls `decideOperatorAdmission` directly). - Production code is not net negative (+117/−89, +28): the cause is the missing grant at start, and the automation entry plus the per-site choice is the minimum for it. The admission body is now shared instead of duplicated. - Tests that asserted a read-only next start was admitted with `["operator.read"]` now assert the refusal (`operator-run-recovery.test.ts` publication case, `operator-run-recovery.access-policy.test.ts`, `remote-control-ui-ingress.integration.test.ts` viewer recovery). ## Evidence - New table test `src/gateway/operator-run-recovery.start-grant.test.ts` (24 rows). Each start kind goes through the entry its producer uses, with the saved-source shape it stores: - every chat-like kind is refused when the writer becomes read-only and when the writer becomes cron-only; - every automation kind is admitted for a cron-only creator and refused when its creator becomes read-only; - an in-run continuation and a read-only channel sender stay admitted. - Head: 24/24 pass. Base `8d1e59c2fddc` (with `restoreScheduledAutomationOperator` aliased to the unchecked queued restore that base's automation sites use): 17 fail (all 12 chat-like rows and the 5 automation read-only rows), 7 pass (5 cron-only admits, continuation, channel). - The `/followup` rows fail at the shared entry on base; end to end, base refused read-only there through #203468's check, which this PR moves into the shared entry. - `service-session-work.test.ts`: work accepted with `operator.write` or `operator.sessions.write` restores through the write entry; work accepted with only `operator.cron` restores through the automation entry. - Before push, one `ocx test` run over the touched tests plus every test importing a changed source (53 files). Reds outside this PR, each also red on base `8d1e59c2fddc`: `cron.scheduled-policy-adoption.integration.test.ts` (3 owner-origin cases, "No model is configured"), and the intermittent `operator-admission.table.test.ts > principal > before-start` flake. `ci-changed-node-test-plan.source-owners.test.ts` needed the new file committed and passes after the commit. `tsgo:core` and `tsgo:core:test` pass; oxfmt/oxlint clean. - E2E (`one-admission-e2e`: isolated Gateway, trusted-proxy Control UI clients, real model turn) on `2fb4824f6db4` and again on the final head `5a06fa530986`, all pass: - R (revoke while running → finishes): `state: final`, `toolEnds: 3`, `toolEndsAfterRevoke: 3`. - Q (revoke while queued → refused visibly): `providerRequestsWithQueuedMarker: 0`, `visibleRefusalInTranscript: true`. - S (Stop → cancels): `state: aborted`. - Local ClawSweeper review: round 1 (`2fb4824f6db4`) and round 2 (`5a06fa530986`) findings are answered in `Rejected review findings:` comments (the accepted service-work edge case; restart system turns and completion wakes, which already needed write on `main`). - CI: the only failure caused by this PR (round 1, a read-only recovery fixture in `operator-run-authority.principal.test.ts`) is fixed. The remaining reds also fail on `main` (#203496, #203542); see the `Maintainer override:` comment. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
…#203536) Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it. ## What Problem This Solves Each attempt (a new turn, a subagent settle, `sessions_send`, a retry) loads history through `selectBoundedModelRequests` with a byte cap of `contextTokenBudget × 8`. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes `history_changed`/`history_shorter`, and the full replay hits only instructions and tools. The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts. On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are `request=1`, the first request of an attempt. ## Why This Change Was Made Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction. - `resolveEmbeddedSessionContextLimits` returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires. - Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt. - The `contextTokenBudget` plumbing that existed only for this cap is removed (`prepareRecoverySession`, `readCompactionTranscriptBytes`, `readPreflightTranscriptContextMessages`). - Unchanged: `selectBoundedModelRequests` and its fallbacks (quarter-cap steps, #191146 trailing prompt, #201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps `toolResultOverflow: "omit"` (#184704). With the larger guard, it keeps every result body in every case that fit before. - Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing). Accepted edge cases, without code: - A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps. - On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact. - Plugin harnesses that use `resolveAgentHarnessHistoryLimits` (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up. ## Evidence **Regression step on every transport.** The step is in the prefix-stability journey (`test/prompt-cache-prefix-stability.test-support.ts`). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one. - Base `8d1e59c2fddc`: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two `message 0` breaks each. - This head: green on all 5. - Mutation: the head with the old `budget × 8` cap restored is red again. **Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and `response.completed` usage were captured. | req | base status | base input / cached | head status | head input / cached | |---|---|---|---|---| | 1-6 | first, then `continued` | 17096/0 … 18214/18099 | same | same | | 7 (turn 3, request=1) | `history_shorter`, msg 1 moved, 10 items sent in full | 17959 / **16430** | `continued`, 2 items sent | 18853 / 18211 | | 8-10 | `continued` | … 18853/18738 | `continued` | … 19747/19632 | | 11 (turn 5, request=1) | `history_shorter`, msg 1 moved, 13 items sent in full | 18598 / **16430** | `continued`, 2 items sent | 20386 / 19744 | | 12 | `continued` | 19237/18030 | `continued` | 21025/19818 | 16430 is the instructions+tools prefix alone. Base logged `historyRewrite(message 0 (user) differs ...)` twice, and head logged it zero times. Tests: the touched test files and every test file that imports a changed source (31 files), `pnpm check:changed`, oxfmt and oxlint. ## What Changes for Users Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently. ## Merge danger Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
…Ubuntu 26.04 (#203538) * fix: keep the Linux installer from hanging at the NodeSource step on Ubuntu 26.04 Quiet installer steps hide their output in a log, but still handed the user's terminal to the command as stdin. Under sudo-rs with use_pty (the Ubuntu 25.10+ default), a terminal stdin plus redirected output leaves the NodeSource setup script's apt install stopped by SIGTTOU in sudo's pty, so a downloaded-and-run installer sat at "Downloading NodeSource setup script" forever. curl | bash was unaffected because quiet steps already isolated stdin there. Quiet steps now always run the command with /dev/null stdin, as the non-spinner npm install already did, and the spinner npm install path matches. Password prompts still reach the terminal through /dev/tty. Refs #203460 * fix: keep the Homebrew bootstrap interactive on the terminal Homebrew asks for the admin password and RETURN on the terminal, so it is not a quiet step: with /dev/null stdin it switches to NONINTERACTIVE and sudo -n, which fails on a Mac without cached sudo. Run it with the installer's interactive stdin policy and visible output instead. Refs #203460 * fix: isolate stdin for verbose quiet steps too With --verbose and gum, run_with_spinner still captures output, so the NodeSource sudo step hit the same terminal-stdin hang. Refs #203460 Co-authored-by: Peter Steinberger <steipete@gmail.com>
…epair (#203528) A managed node runtime consumes shared state but may not repair it. When client credential preparation reported a required migration or an optional metadata upgrade, startup still took Doctor maintenance and reached the schema-repair guard, so the supervisor retried every few seconds forever with advice to update an installation that was already current. The managed runtime now defers an optional credential metadata upgrade and keeps running on its existing credentials. A required repair refuses before maintenance with the owner's real next step, openclaw doctor --fix with the installation that owns the state. The repair guard names the same command instead of an update. Refs #203489 Co-authored-by: Peter Steinberger <steipete@gmail.com>
…e optional dependencies (#203539) 2026.11.5 and 2026.11.6 published @openclaw/memory-lancedb with its whole runtime closure bundled, so the tarball carried only the release host's linux-x64-gnu LanceDB binding and npm never installed the right one on macOS arm64, Linux arm64 or Windows; Doctor then refused with "Cannot find native binding". #182335 replaced the package's bundleRuntimeDependencies=false opt-out with an explicit apache-arrow bundle to ship the patched Arrow copy. That patch was retired in 9dc69b2, so restore the opt-out and drop the stale bundle: the package is back to the 2026.11.4 shape (about 150 KB, bindings and Arrow resolved by npm at install time). Refs #203211 Refs #203429 Co-authored-by: Wang Rui <55612496+wr-web@users.noreply.github.com> Co-authored-by: Peter Steinberger <steipete@gmail.com>
## What Problem This Solves Fixes #203512. Since #203487, Stop does not cancel an MCP loopback tool call from a CLI-backed turn (Claude CLI and other CLI runtimes). If the user stops the turn while a message action waits on a channel lookup, the action still finishes: `test/cli-message-authority.integration.test.ts > stops the reaction lookup after abort retirement` gets `isError: false`. ## Why The MCP loopback server rebuilds the tool caller from the CLI grant (`src/gateway/mcp-http.ts`). That caller had no `approvalSignals`. The turn's abort signal reached the tool only through the receipt boolean `isGrantAndLineageCurrent` → `isMcpLoopbackClientGrantCurrent`. That boolean also checks the grant row, the admitted run's delegated authority and the capture, so it mixes run lifecycle with permission. #203487 removed the synchronous receipt boolean from `captureGatewayToolCallerAssertion` as an authority re-check. Stop was lost with it. ## Fix - `resolveMcpLoopbackClientGrant` now returns the grant's existing `abortSignal`, which is the CLI turn's abort signal. The MCP caller passes it as `approvalSignals`, the lifecycle channel that `captureGatewayToolCallerAssertion` already checks. The permission part of the receipt stays out of the synchronous check, as #203487 intended. - Removed: the MCP `cronAuthorityCheck` pass-through (grant field, mint copy, resolved field, caller field) and `bindActiveCronAuthorityCurrentness`. #203487 removed the only reader of the identity `cronAuthorityCheck`, so this chain had no reader left. - No new export, name, flag or guard. Production: +3 / −17. ## Sweep of #203487, #203503 and #203516 - I traced every production caller that sets `receiptAuthority` (`agent-tools.caller`, embedded `attempt-gateway-tools`, `settled-turn-finalization`, harness `tool-authority.runtime`, `plugin-native-subagent`, `scheduled-owner-tool-guard`, `cron-tool`, `node-claude-skill-runtime`, worker `placement-turn-claim-events` and `worker-turn-tool-surface`, plugin `hooks`). Each one still delivers Stop through `approvalSignals` or through the tool's own execute signal. The MCP loopback was the only caller where the receipt carried Stop alone. - The 1b and 1c call sites run inside in-process Gateway dispatch. That dispatch still runs the caller assertion (`in-process-gateway.ts`, `server-plugin-in-process-authority.ts`), or the tool's own signal covers them. No other instance was found, so this PR has one fix and one test. ## User Impact When you stop a CLI-backed turn, a running message action is cancelled before its write. The tool result reads "The message turn has ended. Start a new turn to retry." A permission change in the middle of a call still does not interrupt a started call (#203487). ## Tests - `test/cli-message-authority.integration.test.ts` "stops the reaction lookup after abort retirement": red on main (`isError: false`). Green on head, with no PATCH or PUT after Stop. The expected text is now the message route's "message turn has ended". Before #203487 the text was the generic "authority is no longer active", which #203487 removed. - `test/cron-message-read.integration.test.ts` (claude-cli, disabled before 429): Stop now reaches the tool, so the result text is the message route's "message turn has ended". The regex now accepts it. The single PATCH and the absent retry are unchanged. - `cron-creator-authority-context.test.ts`: the two lines that read the deleted helper are removed. The revocation assertion on the creator stays. ## Evidence - Pre-push: one `ocx test` run with fail-fast off over the touched tests and every test importing a changed file (60 files). Green except `mcp-http.async-scope` "keeps each CLI grant's own ceiling" and `cron.scheduled-policy-adoption.integration` ×3, both red on main before this PR (see #203503 override), plus `cron-message-read` (updated above, then green 9/9). - `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean. - Real Gateway E2E on the final head `7e1c3b07ffde`: R, Q and S (Stop → cancels) pass (#203551 (comment); first head: #issuecomment-7081968622). - Local review on the final head `7e1c3b07ffde`: patch correct, zero findings. - Session-identity allowlist: `cron-creator-authority-context.ts` shrinks from 41 to 39. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
…203433) A stalled sandbox Git read kept a bound autoreview call pending past its own review budget with no error, progress, or reviewer request (#203402): timeoutSeconds only limited each reviewer process, so helper capture and delivery had no deadline. When timeoutSeconds is supplied it now bounds the whole call - helper capture, prepared-pass admission, reviewer passes, and delivery. On expiry the call ends with an error naming the stalled phase, helper subprocesses are aborted through the same signal, and a non-abort helper kill failure cannot replace the budget error. An omitted timeoutSeconds keeps the parent lifetime, the helper's per-pass timer, and the watchdog allowance exactly as before.
…database error (#203530) * fix(gateway): release the owner lease while late reads still borrow state An in-process restart whose startup outlived its stop budget keeps serving shared-state reads into the final lock release. The release sealed the cached state handle by closing it, which refuses live borrowers, so the release threw "state database still has active native borrowers" and turned the planned restart exit into "Gateway failed to start". The seal is an optional clean-close proof. Skip it while a read still borrows the handle; the lease row is still released and the next startup validates. Refs #203517 * fix(state): skip the release seal when any aliased handle is borrowed
…203561) ## What Problem This Solves #203487 made `captureGatewayToolCallerAssertion` stop re-checking permission in the middle of a started tool call. Its synchronous call now only checks Stop (`approvalSignals`); its prepared form carries the caller receipt's session fences. Agent-side callers still captured it just to call it synchronously, and some used "the capture returned a function" to mean "this is an admitted agent run". ## Why This Change Was Made Admission checks permission one time, when work starts. This PR removes the capture where it was only a synchronous Stop check: - `agent-tools.before-tool-call.approval.ts`, `bash-tools.exec-approval-request.ts`, `harness/gateway-question.ts`, `tools/agents-wait-tool.ts`: the capture only fed watchdog `isCurrent` callbacks. They keep their tool/request signal check where they had one. Exec approval has no signal in scope; its watchdog wait ends with the run's attempt, and the approval wait ends with `run-aborted`. - `openclaw-plugin-tools.ts` (node MCP elicitation): the gate is `caller.operationalRunInstance`; Stop is the same signal the elicitation registers with (tool signal + caller `approvalSignals`). - `tools/computer-tool-bindings.ts`: the gate is the existing `operationalRunInstance` check; Stop is `params.signal` / `request.signal`. - `tools/personal-instructions-tool.ts`, `tools/presence-tool-authority.ts`: the gate reads `caller.operationalRunInstance`; personal instructions checks the tool signal. **Kept on purpose (cut less):** where the capture is composed into a session source assertion or passed whole as one, it still carries the receipt's prepared session fence to the write. The brief says that fence must not be dropped, so these stay unchanged: - `tools/in-process-gateway.ts`: composes it into `sessionMutationCommitGuard` for every in-process Gateway write (#203516). - `tools/message-tool-execution.ts` / `message-tool-turn-authority.ts`, `tools/media-generate-background-shared.ts`, `tools/agent-step.ts`, and plugin tool `assertInvocationCurrent` in `openclaw-plugin-tools.ts`. Replacing the capture with `captureGatewayToolReceiptAssertion` would bring back the "agent tool caller authority is no longer active" refusal on the synchronous path, and copying the 1a body would make a second implementation (Fable 5.2 consult: keep the carrier). PR 1e, when it deletes the declaration, must move the body to the remaining fence carriers as one implementation. No new export, name, hook, flag or guard. Production: 8 files, +30 / −69. Accepted edge case (no code for it): exec approval's watchdog `isCurrent` no longer checks Stop itself (no signal in scope); Stop still ends the run's watchdog attempt and the approval wait. ### Changed tests None. No test asserted a mid-run refusal through the removed calls. ## User Impact None visible. A started agent tool call runs to the end; Stop still cancels it; writes to a replaced or locked session still fail with the session conflict. ## Evidence - Pre-push: one `ocx test` run, fail-fast off, over 146 files (direct importers of every changed source, importers of test-support files that import them, and every test that names `captureGatewayToolCallerAssertion`), then the repaired and re-touched set (37 files) again on the final tree. Green except: - `slack-download-read-authority.integration.test.ts` "rejects revoked output ... after result (revoke: claim)": also red on the merge base `cc7b482f887b` (run there with `ocx test`); not this PR. - `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt and oxlint on the changed files: clean. `check:lifetime-check-ratchet`: OK, no growth. `check:changed` SQLite worker ratchet OOMs locally on its 4 GB heap (known, whole-repo scan); CI covers it. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
* feat(cron): size automation run slots from the agent limit Automation ran at most eight jobs at a time on every host. Its run slots now come from the agent concurrency limit, which it shares with conversations: the limit minus the conversation turns in progress, and never under eight. Conversations never wait for automation. The Gateway works the slots out from the conversation lane each time the run queue decides what may start. The cron lanes are as wide as the agent limit so they fit what the queue admits; hook dispatch keeps its width. While a run is queued or a fired condition waits for a slot, the scheduler looks again within a minute, because a conversation turn ending raises no automation event. Refs #196859 * feat(cron): back automation off when a provider or memory pushes back Automation's run limit adapts. When a provider rate-limits a model request or turns it away as overloaded, or the Gateway is critically short of memory, and automation holds more than eight agent sessions, it may hold half as many runs. While runs wait and nothing has pushed back for about a minute it adds one slot, about one a minute, until the limit is whole. A reduction lapses after an hour without pushback. The signals already exist: the lifecycle events that model attempts publish on the agent event bus, and the memory pressure channel. The finished run is no use as a signal, because the runtime retries rate-limited requests itself and the run ends ok. Conversations are never limited, and runs in flight are not stopped. Refs #196859 * fix(cron): resume a fired condition's payload when a conversation frees a run slot * feat(cron): keep eight automation runs unless cron.dynamicConcurrency is on * refactor(cron): look again for free slots only with dynamic concurrency; move the owner recheck out * refactor(cron): compute the backoff ceiling from time since pushback; drop the memory-pressure trigger * fix(cron): start the quiet minute again on pushback that cannot lower the ceiling * feat(cron): size automation from the agent limit and free memory, with no setting cron.dynamicConcurrency is gone. Automation always shares the agent concurrency limit with conversations: the limit minus the conversation turns in progress, never under eight because of conversations. Provider pushback still halves it, down to eight. Free memory can hold it lower, down to one run at a time. The host reads free memory (reclaimable cache counts as free; under a container or cgroup limit, at most that limit minus the Gateway's resident memory, because the cgroup's own usage includes page cache) and passes how many runs it could hold at 256 MiB each. The queue worker, which counts the run slots in use, lets automation take at most half of the memory open to it: free memory plus what its running runs hold. Runs that use less than the estimate leave memory free, so later drains admit more; drains in quick succession cannot add up past what free memory could hold. Running runs are never stopped. While a run waits for a slot the scheduler looks again within a minute, since a conversation turn ending, memory being freed or the backoff stepping up raises no automation event. The cron lanes are always as wide as the agent limit. Refs #196859 * fix(cron): count exec commands in memory admission; keep cron tests off host memory Memory admission measured a container limit minus the Gateway's resident memory and left out the commands jobs run, so sixteen jobs that each ran a 256 MiB exec command in a 4 GiB cgroup were all admitted and then killed by the kernel or the exec memory guard. Admission now subtracts what the exec memory owner sees watched commands hold, and on Linux keeps jobs within the exec memory budget's remaining room. It reads the budget through the owner, which sizes it then if no command has yet, so the first burst of jobs already leaves their commands room. Cron tests read the test machine's free memory, so on a loaded host a case that needs two runs at once got one and timed out. The cron test project now stands in plenty of free memory for every case, the way it already fakes clocks; memory cases set their own readings. Refs #196859 * fix(cron): count jobs at the memory their recent exec commands held Admission counted every job at 256 MiB until its command started and showed up as used. When several runs ended at once, each ending started a new job before the earlier jobs' commands appeared, so jobs whose commands held about 400 MiB were admitted past the exec memory budget and the exec memory guard killed one. The exec memory owner now remembers the most one watched command has held in the last ten minutes, and admission counts each job at that figure when it is above 256 MiB. A burst then leaves the next commands room before they start; one unusual command stops holding later work back once ten minutes pass. Refs #196859 * fix(exec): keep the largest command of the whole window, not one peak The exec memory owner kept one peak sample. When it expired, the figure dropped to nothing even though smaller commands within the last ten minutes were still recent, so cron admission fell back to 256 MiB per job: after a 768 MiB command and a 384 MiB one three minutes later, twelve small jobs widened from one at a time to six. It now keeps the samples of the window in decreasing order of size, so when the largest expires the next largest recent one takes its place. Refs #196859 * fix(cron): cap automation at half of open memory, not counting running jobs Memory admission counted every running job as holding the per-run figure. A job that had just started, before its command showed up as used, was counted on top of free memory that had not dropped yet, so drains in quick succession raised the limit each time until runs filled all of free memory at the figure instead of half of it. When four runs ended at once, five jobs started where three fit, and the exec guard killed the largest command. The run slots now come straight from memory: half of what is open to automation (free memory plus what running exec commands hold, and at most the cgroup limit less the Gateway and the exec budget), divided by the figure, at least one. The count no longer depends on how many jobs are running, so the spare half holds however often the queue drains. The host folds this into the run slots it already passes, which removes the separate free-memory field from the queue and scheduler workers. A burst of large commands after a quiet period, before any recent command sets the figure, can still exceed the exec budget; the exec guard stops the largest command. That is named in the code and docs. Refs #196859 * fix(cron): count other cgroup residents in memory admission Under a container memory limit, admission took the limit minus the Gateway's resident memory as open memory, and host free memory on Linux is host-wide. Neither saw another process in the same cgroup: with an 8 GiB limit, a 512 MiB Gateway and a 5 GiB peer, fifteen 256 MiB jobs were admitted into the 2.5 GiB that was left, and the cgroup could OOM. The host memory owner reads what the Gateway's cgroup v2 has left: for its own cgroup and every visible ancestor with a memory limit, the limit minus what the cgroup holds, less inactive file cache, which the kernel reclaims first. Admission uses that, plus what running exec commands hold, as open memory. Where the files cannot be read, as on cgroup v1, the limit minus the Gateway's own memory stays as before. Refs #196859 * fix(cron): count hook turns in provider backoff Backoff measured the sessions in flight from the automation lane alone. Hook turns run in their own lane but share automation's budget and its providers, so with eight automation runs and eight hook turns active a provider rate limit saw eight sessions, held, and left admission at the whole agent limit instead of halving sixteen. While hooks are on, the lane group's active count includes both, and backoff uses it. Refs #196859 * test(cron): stub the exec memory budget in the cron memory fixture On Linux the exec budget comes from the test host's cgroup, so in a 2 GiB container admission capped at three runs and cases waiting for four or more timed out. The fixture now reads no exec budget, as off Linux; cases about exec memory set their own reading. * test(cron): keep the cgroup peer case off the test host's cgroup root The case fakes the cgroup files below the root, but the walk also reads /sys/fs/cgroup/memory.max, which in a memory-limited container is that container's limit: at 4 GiB it admitted four runs instead of five. * test(cron): stub free memory where run slots read it Under Bun on macOS, readHostFreeMemoryBytes now reads Mach VM statistics directly, so stubbing process.availableMemory no longer reached run slots. * fix(cron): scope automation backoff to the resolved provider * fix(cron): recover provider slots when default capacity opens * fix(cron): restore requester authority on session readmission
update-cli.ts imported check-release statically, so every openclaw update command loaded its plugin status and state graph at registration. Load it in its action like the other subcommands, and run the foreground handoff test on a package install now that Git installs use prepared releases.
…ne-time admission (#203534) * test(update): drop the OCM mid-request authority refusal case Authority is checked once at admission since #203488, so a started OCM update no longer refuses when the caller's transport authority changes. Cover the refusal that remains mid-request (Stop), assert the commit-guard, scope and Git-target refusal messages, and drop the unused authority callback from the update.run test harness. * test(update): pin the OCM Git-target refusal code
…203554) sessions_yield arms wake-capable background commands through awaitExecsForYield, but the claim only returned a bare true, so the embedded runner had no record that this turn's yield owned an exit wake. A turn that yielded on such a command with no final text ended with the 'Turn yielded without a continuation source' host notice even though the command's exit resumed the session. Report the armed wake from the rechecked claim, carry it through the yield callback into attempt state, and count it in hasRunContinuationEvidence. A tool result that merely says running is still not evidence. Co-authored-by: VACInc <3279061+VACInc@users.noreply.github.com>
Result: plugin harnesses (Codex app-server, Agents API, Muse) now read session history with the same guard as the embedded runner. Their history keeps everything since the latest compaction and only grows between compactions. Follow-up to #203536. ## What Problem This Solves `resolveAgentHarnessHistoryLimits` (Plugin SDK) still computed its own byte cap: `contextTokenBudget × 8`. Each Codex hook/continuity read, Agents API prompt-hook read and Muse session transfer therefore cut the oldest turns once history passed 8 bytes per budget token. Reasoning, images and tool payloads reach that size far below the token budget. Each new attempt reread and cut the history again, so it was rewritten outside compaction. This is the same class #203536 fixed for the embedded runner. ## Why This Change Was Made - `resolveAgentHarnessHistoryLimits` now returns `resolveEmbeddedSessionContextLimits({})` (16 MiB / 10,000 events) plus its existing `toolResultOverflow: "omit"`. There is one owner for the bound, and the duplicate budget-based computation is gone. - The export keeps its name and signature. Its `contextTokenBudget` argument is still accepted, but it is **deprecated and ignored** (documented in the doc comment and in `docs/plugins/sdk-agent-harness/attempt-runtime.md`). - Bundled callers stop passing it. Codex drops the `contextTokenBudget` argument from `readCodexMirroredSessionHistoryMessages` / `readMirroredSessionHistoryMessages`. Agents API drops the limits from its history-reuse scope key: the limits are now constant, so a budget change no longer forces a fresh read. Muse calls it with no argument. - No schema, protocol or dependency change. Tests that asserted the removed budget cut are deleted or rewritten: - Codex `session-history.test.ts`: the budget-128 cut and budget-512 omission tests are replaced by the regression test below. - `run-attempt.bounded-continuity.test.ts`: the "assistant-only bounded suffix" case is kept. Its user turn is now larger than the 16 MiB guard, so it still covers the fallback past the guard. - Agents API: the "new budget" retry case is removed, and the pinned `maxBytes: 256_000` assertion is removed. ## Evidence Regression test through the Codex harness history consumer (`readCodexMirroredSessionHistoryMessages`): 1.3 MB of history, which is past the old default-budget cut and far below compaction. Two consecutive reads with a new turn appended between them. - Base `2754763da236`: red, `expected … to have a length of 43 but got 25` (the oldest turns were cut). - Head: green. All 43 messages are returned, and the second read extends the first one exactly. - Mutation: head with the harness cap set back to `128_000 × 8` is red again (the same 25-message cut). Tests: the touched test files plus every test file that imports a changed source (25 files), oxfmt/oxlint on the changed files, and `pnpm check:changed`. ## What Changes for Users Codex, Agents API and Muse sessions with reasoning, screenshots or large tool output keep their whole history (and the provider cache prefix) until compaction. Before, old turns dropped silently on each attempt. ## Merge danger Two-way door. A revert restores the budget-based cut. Third-party plugins that pass a budget get the shared guard; their call still compiles. Co-authored-by: Ayaan Zaidi <hi@obviy.us>
## What Problem This Solves
Exec approvals were checked twice for one command. The worker commit (`execApprovals.commitAuthorizations`) checks the command against the current policy row. After that, `retainExecApprovalsCurrentRead` kept a per-database policy view that the launch guard read again right before spawn. A policy write that landed between the commit and the spawn refused a command that was already admitted ("Exec approval changed before execution", "Exec approval policy is unavailable or changing before execution"). Under the one-admission rule, a policy change applies to the next command; a command that has started finishes.
## Fix
- `src/infra/exec-approvals-store.ts`: delete `retainExecApprovalsCurrentRead`, the `currentPolicies` map and its publication/lifecycle bookkeeping.
- `prepareExecApprovalsCurrentRead` returns the policy it read at preparation, through the existing prepared-snapshot cache, which a publication still clears for the next reader.
- The launch guard from `commitExecAuthorizations` keeps Stop (`signal.throwIfAborted()`) and the caller's own `assertCurrent`, and returns the committed file.
- `src/infra/exec-approvals-authorization.ts`: `commitExecAuthorizationLocked` no longer runs `assertCurrentUsageAuthorization` again on the file it just committed. The worker already ran that check inside the commit transaction.
- `scripts/check-lifetime-check-ratchet.mts`: remove `retainExecApprovalsCurrentRead` (it is gone) and `createPluginRuntimeCapabilityLease` from `LIFETIME_CHECK_CALLS`.
### Classification
| Name | Class | Action |
|---|---|---|
| `retainExecApprovalsCurrentRead` (#169584) | authority. It re-read the exec policy, which is the permission for the command, after the worker commit had admitted it. It refused while a policy write was pending or after one committed. | deleted |
| `createPluginRuntimeCapabilityLease` (#133297, "scope HTTP routes to account lifetimes") | resource lifetime fence. Its only `revoke()` callers are channel account stop (`server-channels.ts`), plugin service stop (`services.ts`), plugin CLI scheduler close (`cli-service-scheduler.ts`) and shutdown drain. It never reads role, scopes, profile or grants. It retires HTTP routes, listeners and schedulers that a stopped account or service still holds. | code kept; name removed from the ratchet list |
Kept: Stop on the launch guard, the worker commit check against the current row (it protects the usage/grant write), and the DB-lifecycle fences inside the shared-state reads.
Not in scope (accepted for now): `plugin-node-host.ts` still compares the node exec **config** (`resolveNodeExecConfigPolicy`) at launch. The ratchet does not list it; it can go in a later PR.
## User Impact
- If you tighten exec approvals while a command is between approval and spawn, that command now runs. The next command uses the new policy. Before this change, the command failed with "Exec approval changed before execution".
- Stop still cancels the launch.
- A policy change made before the worker commit still refuses the command.
## Tests
Deleted or flipped. Each one asserted a refusal after the commit had admitted the command, which this change removes:
- `bash-tools.exec-authorization.integration.test.ts`: "revalidates … after asynchronous shell preparation" ×3, "rechecks policy after deferred supervisor admission", the PTY fallback `revoked=true` case. Added "finishes an admitted launch when policy is revoked during supervisor admission" (real exec tool → supervisor).
- `invoke-system-run.test.ts`, `invoke-agent-cli-claude.test.ts`: the revoke cases now expect the admitted launch to finish (real node `system.run` / Claude CLI entry points).
- `plugin-exec-policy.test.ts`: approvals tightened after the invocation started → the launch is allowed. A config change is still refused.
- `agent-tools.browser-loopback-current.e2e.test.ts`: deleted the approvals-revocation case. The abort (Stop) and config cases stay.
- `exec-approvals-store*.test.ts`, `operator-approval-store.worker.test.ts`: the pending-write / committed-change refusals are replaced by "the prepared read keeps its admitted policy; a fresh preparation sees the write".
## Evidence
Pre-push: one `ocx test` run of the 78 importer/touched files (continue-on-failure); the remaining reds there (`server-methods/exec-approvals.test.ts` ×4, `agents-mutate.test.ts`, `bash-tools.exec-gateway-approval.e2e.test.ts` hook-token reload) fail the same way on the merge base `1a0a24dcd2cf`. Touched tests rerun green (202 cases). `pnpm tsgo:core`, `pnpm tsgo:test`, oxfmt, oxlint, lifetime ratchet pass. Head E2E and CI follow in comments.
- Head E2E (Q/R/S pass): #203572 (comment)
- Local review rejected finding: #203572 (comment)
Co-authored-by: Ayaan Zaidi <hi@obviy.us>
Co-authored-by: vyctorbrzezowski <51521767+vyctorbrzezowski@users.noreply.github.com>
Port the release repair from #203571 while preserving main registerAwaiting plumbing and native exec trailing newlines. Extend the existing required-wait owner only for canonical process poll calls, retaining exact continuation without command relaunch. Co-authored-by: RomneyDa <6581799+RomneyDa@users.noreply.github.com> Co-authored-by: vincentkoc <25068+vincentkoc@users.noreply.github.com>
) * fix(update): chat-requested managed updates no longer leave the Gateway stopped The managed update helper checks the chat requester's owner authority while the Gateway still serves. With a live owner, that check reads shared state natively through the state-read worker, which retains the idle reader for 30 minutes. The helper then waits while the candidate Doctor takes exclusive migration access and, on failure, database rollback takes removal exclusion; the retained WAL reader's shared lock made both refuse, leaving the Gateway stopped. Release worker-held connections at the state path after each requester authority capture. * test(update): isolate the requester reader-release check from the run fixture's own handle * fix(update): release requester-check readers only in the update helper Draining every worker read at the state path from the shared requester capture could cancel the updater's in-flight progress reads and could replace a deferred authority error. Release readers only at the helper's own entry points, after the check settles, preserving the check's failure alongside any release failure. * fix(update): give the helper's requester identity entry its own name The export-name-collision check rejects a second behavior under prepareManagedUpdateRequesterIdentity. The handoff helper imports the releasing entry from the same installed runtime before the update command starts, so renaming it is a same-version contract. * refactor(update): keep the installed daemon requester export name Keep prepareManagedUpdateRequesterIdentity as the daemon-cli export the handoff helper imports, and give the underlying capture its own internal name instead, so the export-name check sees one behavior per name without changing the installed contract.
…round runs (#203568) ## What Problem This Solves On OpenAI Responses, a background run on a conversation could reset that conversation's request chain. Examples are a skill review fork, memory flush, a `/btw` side question or a compaction summary. The background run reached the transport with the conversation's `sessionId`. It replaced the conversation's continuation baseline with its own request. The conversation's next request then failed the prefix check (`history_changed`). It sent the full history instead of a `previous_response_id` delta. On a busy production host this pattern cost about 14-19M uncached tokens per day (1.75-2.5% of input). ## User Impact After a background run, the conversation's next request continues with `previous_response_id` and sends only the new input. Background runs keep the conversation's prompt-cache key, so they still read the cached prefix. Nothing changes in config or stored data. ## Why This Change Was Made `options.sessionId` did two jobs at the transport: - **Affinity:** the prompt-cache key, the `session_id` / `x-client-request-id` headers and the replay fence. A background run needs these. - **Ownership:** the key of the HTTP continuation slot, the Responses WebSocket pool and its continuation, and the ChatGPT WebSocket pool, continuation and SSE fallback latch. A background run must not touch these. The change separates the two jobs: - `sessionId` now carries **affinity only**. Every caller still sends the same value. - **Ownership** moves to a branded `ProviderStateScope`, passed as the symbol-keyed stream option `PROVIDER_STATE_SCOPE` (`packages/ai/src/session-resources.ts`). Every mutable store keys on the scope, and a store cannot take a plain string. - **Without a scope there is no mutable state.** The request sends full input on its own connection. Forks, memory flush, `/btw` and compaction summaries get this with no code at their call sites. - **Only lane admission mints a scope.** `claimRunProviderState` (`session-bootstrap.ts`) runs right after the writer claim in `lane-controller.ts`. It mints a scope for runs that write the conversation and none for detached runs. The scope reaches the attempt stream and the worker inference runtime (worker-placed turns). - An oxlint `no-restricted-imports` rule allows `claimConversationProviderState` only in `session-bootstrap.ts`. **Removed:** `cleanupProviderSessionResourcesOnDispose` and its two opt-outs. `AgentSession.dispose()` freed provider state by the transcript's session id. In a fork that id is the parent's id, so the embedded runner had to turn the cleanup off. Provider state no longer belongs to dispose. **Kept on purpose:** - **The prompt-cache tracker key stays as it is.** The tracker is fed the run's own `attempt.sessionId`. A fork's id is `internal-session-effects-<runId>`, so forks never shared the parent's tracker. The planned tracker re-key would change nothing, so it was dropped. - **`cleanupSessionResources(forkSession.sessionId)` in `session-fork-run.ts` stays.** It frees the fork's own tracker entries. **Production LOC:** +128 / −40 including the 28-line oxlint rule; TypeScript alone is +100 / −40 (net +60). The growth is the scope type, threading the scope to the attempt and worker paths, re-keying the stores, and the import guard that keeps minting in one place. This is the real number, not padded. ## Evidence **Prefix journey (#201723): new step "background fork between two parent turns", run on all five transports.** A local test plugin starts a real fork through `api.runtime.subagent.runForkedTurn` between two target turns. The fork's requests are classified apart from the parent's. The step asserts two things: 1. The fork's system prompt and tool list are byte-equal to the parent's. 2. On openai-responses, where the fake provider opts into continuation, the parent's first request after the fork carries the parent's own last response id. | Transport | base 8d1e59c | head | |---|---|---| | openai-responses | **red**: `expected undefined to be 'resp_2'` (the parent sent full input) | green | | anthropic-messages, openai-completions, google-generative-ai, bedrock-converse-stream | not run on base. These lanes hold no continuation state, so the step checks fork system/tool bytes and that parent history only appends. | green | **Transport guard:** the new test "preserves the writer continuation when a scope-less caller shares its session affinity" in `openai-responses-client.continuation.integration.test.ts`. **Mutations.** Each mutation ran in a scratch copy of head against the guard test and the openai-responses journey: | Mutation | Result | |---|---| | (a) The HTTP continuation slot falls back to keying on `options.sessionId` when no scope is present | **red**: the guard test and the journey both fail | | (b) Detached runs also get a scope | **survived**: the scope keys on the run's own `sessionId`. Every detached caller uses a private id (`internal-session-effects-<runId>`), so a fork's state stays isolated anyway. The detached rule only stops background runs from holding sockets and slots they never reuse. | | (c) The attempt does not pass its scope to the stream | **red**: the journey fails (the parent loses continuation) | **Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, SSE, code mode, the bundled skill-workshop background review. A scratch-only patch captured every request body and its `response.completed` usage. The driver and model are the same on base and head. Rows around the fork: | request | base: previous_response_id / items / tools / input / cached | head d8c1b56: previous_response_id / items / tools / input / cached | |---|---|---| | #15 parent, last request before the fork | yes / 4 / 7 (2b9cd1ba) / 19701 / 18530 | yes / 4 / 7 (2b9cd1ba) / 19711 / 18537 | | #16 skill-review fork | no / 29 / 6 (ccf4c23c) / 15040 / 0 | no / 29 / 6 (ccf4c23c) / 15047 / 0 | | #19 parent, next request after the fork | no / 33 / 7 (2b9cd1ba) / 20800 / 18943 | yes / 2 / 7 (2b9cd1ba) / 20814 / 18950 | | #20 parent | yes / 1 / 7 (2b9cd1ba) / 20972 / 19799 | yes / 1 / 7 (2b9cd1ba) / 20990 / 19810 | | #22 parent (T3) | yes / 3 / 7 (2b9cd1ba) / 21809 / 20969 | yes / 3 / 7 (2b9cd1ba) / 21830 / 20987 | - The parent's request after the fork changed from **full history (33 items, no `previous_response_id`) to a continuation (2 items)**. Request bytes for the whole run fell from 670,893 to 617,450. - On this short conversation, both versions read about the same number of cached tokens (base 18,943, head 18,950). A full replay of the same conversation still hits OpenAI's cache. The token loss on the production host comes from long conversations, where the full replay misses beyond instructions and tools. That number is measured after landing. - The fork itself still lists 6 tools instead of the parent's 7 (hosted `web_search` is missing), so it reads 0 cached tokens. A separate PR in this series fixes that. <details><summary>Tests changed</summary> - 15 packages/ai transport test files: the writer-contract tests now pass a scope. Each still asserts the same continuation, socket and SSE-latch behavior. - `src/agents/sessions/*` and `attempt-session.test.ts`: fixtures no longer set the removed dispose flag. </details> Co-authored-by: Ayaan Zaidi <hi@obviy.us>
The raw config validator ran the agents.entries roster rule on the file as written, while every loaded reader adds the implicit `main` agent first. A config written by `openclaw models set` (agents.defaults, no entries) was reported invalid by `gateway status` and `update status`, and the new `update check-release` refused it as config-invalid, while `config validate` accepted it. The raw validator now applies the implicit roster default itself, so every caller validates the same view. Refs #203505
… this Mac (#202614) * fix(macos): ask for Local Network access only when looking for nearby gateways * docs: clarify macOS prompts for direct LAN connections Co-authored-by: Vyctor H. Brzezowski <51521767+vyctorbrzezowski@users.noreply.github.com> Co-authored-by: Vyctor H. Brzezowski <krzyszchweski@gmail.com>
…ating (#203486) * fix(update): settle a dead pnpm update's plugin recovery from the installation that replaced it * fix(update): finish a begun commit from a later build and report settlement without naming its outcome * fix(update): keep a begun commit's refusal when the original version is installed again * fix(update): resume a begun commit only when the installed build shows the original core gone * test(update): an unreadable recorded package directory keeps today's refusal * test(update): run the unsearchable-parent case as its own root-skipped test
…der rate limits (#202602) * fix(cli): report host live-session refusals as host limits, not provider rate limits * test(agents): type the CLI capacity cooldown fixture * test(agents): require Error rejections in the CLI capacity fixture
…tate database (#203578) * fix(update): refuse migrating updates while a node service keeps the state open Refs #203457 * docs(update): explain the node-service migration refusal Refs #203457 * fix(update): match the node service's own state directory by filesystem identity A default node service omits the state selector and must not inherit the updater's; path aliases name one directory. Refs #203457 * fix(update): refuse every activation while a node service keeps the state open Update Doctor takes native exclusion of openclaw.sqlite on every activation, including patch updates without a schema change (#203457 reported 2026.11.5 -> 2026.11.6, both schema 36). Refuse whenever a running, kind-marked node service resolves to the same state directory, not only for pending migrations. Refs #203457 Co-authored-by: Peter Steinberger <steipete@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Describe the problem and fix in 2–5 bullets:
If this PR fixes a plugin beta-release blocker, title it
fix(<plugin-id>): beta blocker - <summary>and link the matchingBeta blocker: <plugin-name> - <summary>issue labeledbeta-blocker. Contributors cannot label PRs, so the title is the PR-side signal for maintainers and automation.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause (if applicable)
For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write
N/A. If the cause is unclear, writeUnknown.Regression Test Plan (if applicable)
For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write
N/A.User-visible / Behavior Changes
List user-visible changes (including defaults/config).
If none, write
None.Diagram (if applicable)
For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write
N/A.Security Impact (required)
Yes/No)Yes/No)Yes/No)Yes/No)Yes/No)Yes, explain risk + mitigation:Repro + Verification
Environment
Steps
Expected
Actual
Evidence
Attach at least one:
Human Verification (required)
What you personally verified (not just CI), and how:
Review Conversations
If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.
Compatibility / Migration
Yes/No)Yes/No)Yes/No)Risks and Mitigations
List only real risks for this PR. Add/remove entries as needed. If none, write
None.