Skip to content

refactor(agents): run background session work as a fork of the stored session - #190158

Merged
obviyus merged 2 commits into
mainfrom
feat/session-fork-tools
Nov 1, 2026
Merged

obviyus merged 2 commits into
mainfrom
feat/session-fork-tools

Conversation

@obviyus

@obviyus obviyus commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Skill Workshop is moving from core into the bundled skill-workshop plugin. Its background review cannot move as it is:

  • The generic machinery (source-session fences, detached admission, hidden run, locked model, yielding to foreground work) lives inside Workshop files.
  • The review replays the finished turn's whole run context (foregroundPromptContext, including live per-turn capabilities) into the background run, although it uses only the turn's identity and policy facts.
  • The runner carries a Workshop-only skillWorkshopReviewOf parameter and a Workshop-only lane.

Fix

  • New core owner src/agents/session-fork-run.ts: a background agent run over a bounded copy of one session's conversation, through one completed transcript entry.
    • prepareSessionFork refuses before any model call unless every fork tool passes current policy, and returns the session's durable workspace.
    • runSessionFork owns the fences, detached admission, hidden run registration, locked model, yielding to foreground work and the usage diagnostic. The code moved verbatim from Workshop. The caller's settlement (Workshop: change feed and Learned notice) runs inside the same detached admission, so a graceful restart waits for it, as before.
    • Run context: agent dir, sandbox key and delivery channel come from the stored session. The turn's requester identity (sender, owner flag, group, channel; src/agents/session-fork-requester.ts) is carried explicitly, because the session never records who sent a turn. Both admission and the run re-resolve policy for that requester against the current config, so a sender-specific revocation made while a review is queued stops it before any provider call.
    • Forks mark themselves through the existing inputProvenance field (internal_system, sourceTool: "session_fork", sourceSessionKey). Tools and model-call urgency read that instead of skillWorkshopReviewOf, so tool contexts get no new field.
  • Workshop review keeps only its own decisions: eligibility, prompt, the feature switch, the change feed and the Learned notice. It receives only the requester projection of the turn context, never its live capabilities. review-run.ts is deleted.
  • Removed: skillWorkshopReviewOf.
  • Lane: getSkillWorkshopReviewLane becomes getBackgroundOwnerLane(owner). Workshop's lane name is unchanged (background:core:skill-workshop).
  • Docs: the harness side-effects page now says what the turn context is used for (it also drops a stale prompt-cache claim).

No schema, protocol or stored-data change. No new SDK exports, and harnesses change nothing. The plugin-facing subagent.forkSession additions ship with the plugin cutover that uses them.

Impact

  • One core owner serves background session work; Workshop becomes its first user.
  • No intended behavior change: the review runs with the same requester policy as before, re-checked against current config.

Evidence

All end-to-end cases below run a real Gateway with real embedded foreground turns, a fixture model provider, and config changes through config.patch.

Check Result
E2E: a sender-42 channel ingress turn (agentCommandFromIngress) queues a review; tools.toolsBySender["id:42"].deny = ["skill_workshop"] is added before it runs → no review model call, no change, skill file unchanged. The allowed counterpart learns normally pass; the revoked case fails when the requester is not carried
E2E turn gate: tools.deny: ["skill_workshop"] during the turn, lifted before the review → nothing queued (trace: the turn's toolNames lacks the tool) pass
E2E fork gate: the turn could call the tool; it is denied before the queued review runs → no review model call, no change (trace: fork policy check refuses) pass
E2E: the channel notice send is held open after the skill change commits and the model run ends → Gateway root work stays active (a graceful restart waits); it drains after the send settles. Unit counterpart holds the notice callback pass; both fail when settlement runs outside the admission
Unit: the source group's policy (from the session key) and wildcard sender rules refuse a fork (session-fork-run.test.ts) pass
Existing review suites: yield to foreground work; source fences for permission, reset, replacement, deletion, rewrite, membership and rewind; canonical worktree workspace; cleanup after failure; grouped notices and undo; channel notice with Undo; propose mode pass
gateway-workshop-learning.e2e (bounded request, skill_workshop-only tool list, patch and announce) pass
All *.workshop-contract suites (existing cases unchanged; four new cases added) pass
pnpm check:changed pass, except the production dead-export scan, which flags allowProviderModels and materializeSessionRepositoryWorkspaceOnGateway in files this PR does not touch
Touched suites in total 28 files, 311 tests pass
git diff --check pass

One test was deleted: it asserted the review saw the foreground turn's tool schemas, which the review stopped doing when it began limiting the model to skill_workshop.

@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: codex extensions: copilot extensions: agentsapi size: XL labels Nov 1, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 1, 2026
@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR moves background Workshop execution into a shared session-fork runner that carries requester identity and reads stored session context.

Example: Sender 42 queues a Workshop review before an operator denies skill_workshop for id:42.

  • Before: Workshop-specific execution carries the foreground context to preserve the sender's policy.
  • After: The shared fork carries requester identity explicitly and refuses the queued review before a provider call.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The extraction is coherent and the earlier blocker is fixed; behavioral confidence rests on recorded Gateway harness results rather than a separately captured live deployment.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (not_applicable): The recorded production-path Gateway harness exercises sender-42 ingress, current-policy revocation through config.patch, refusal before provider or skill effects, source invalidation, and held notice settlement; ordinary external media proof is exempt for this collaborator-authored PR.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Workshop's background execution is coupled to core Workshop files and retains foreground context beyond the completed turn.
Reason: The collaborator-authored direction supports the plugin cutover with one shared execution owner and an explicit requester projection, without a new public API or configuration option.

Merge readiness

✅ Ready for maintainer review

This PR remains useful, and the latest commit resolves the earlier settlement-lifetime finding; no additional production defect was found.

Priority: P2
Reviewed head: 9b8df19b81dcae50b6955bc734a6c14cd545bd3d

Before merge

None.

Findings

None.

Agent review details

How this fits together

Completed agent turns schedule background reviews; the fork runner reads bounded transcript context, applies requester policy and source fences, runs the embedded agent, and retains admission through Workshop notification settlement.

flowchart TD
  A[Completed foreground turn] --> B[Workshop scheduler]
  B --> C[Requester policy preparation]
  C --> D[Session fork runner]
  E[Stored session and transcript] --> D
  D --> F[Embedded agent and Workshop tool]
  F --> G[Change feed and Learned notice]
Loading

Technical review

Best possible solution:

Keep the shared fork owner and admitted settlement callback, then complete the required current-head CI gate.

Do we have a high-confidence way to reproduce the issue?

This is a behavior-preserving refactor; the supplied Gateway regressions cover its requester-policy and settlement invariants, and no target code was executed during review.

Is this the best way to solve the issue?

The extraction gives generic background execution one owner, removes the replaced Workshop runner and parameter, and preserves Workshop-specific scheduling and notification decisions.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against c3fca6737b29.

Provenance checked

  • Source-session fences and effect authority keeps the original intent (3302551: Move authority preparation off the Gateway thread while retaining source validation at effects.)
  • Bounded context, restricted tools, foreground yielding and retry limits keeps the original intent (9a6c6b1: Prevent background reviews from competing with foreground work under provider token saturation.)
  • Foreground context and cache-prefix documentation changes intended behavior with a stated reason (a901d33: Carry foreground context to share its prompt-cache prefix; later bounded-review work intentionally replaced that request shape.)
  • Shared background lane capacity keeps the original intent (2409cd6: Share background capacity while preserving serial execution for each owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +131, Tests +160, Docs +1, Other -1. Total +291 across 24 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 13 609 478 +131
Tests 9 265 105 +160
Docs 1 5 4 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 24 879 588 +291

Review metrics

Metric Value Why it matters
Production versus test changes Production +609/-478; tests and support +265/-105 Production growth supports explicit requester projection and shared fork ownership; test growth covers policy revocation and settlement lifetime.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove merge-risk: 🚨 message-delivery: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a useful internal extraction supporting the Workshop plugin cutover without an established urgent user regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-01T08:00:28.661Z sha 184d20b :: needs real behavior proof before merge. :: [P1] Preserve sender revocation when admitting queued reviews | [P3] Remove the generated agent database
  • reviewed 2026-11-01T10:48:27.936Z sha 343309a :: needs changes before merge. :: [P2] Keep review cleanup inside detached work admission
  • reviewed 2026-11-01T10:55:10.394Z sha 343309a :: needs changes before merge. :: [P2] Keep review cleanup inside detached work admission

Reviewed November 1, 2026, 6:28 AM ET / 11:28 UTC (Revision 4).

@obviyus

obviyus commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Nov 1, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 1, 2026
@obviyus

obviyus commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 1, 2026
@obviyus

obviyus commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override (approved by @obviyus): land past the unrelated check-lint-core-2 failure and its derived openclaw/ci-gate status.

  • Failing job: check-lint-core-2 (run 41301212249). Running the same stripe locally (node --import tsx scripts/run-oxlint-shards.mts --only=core --split-core --core-stripe=2/5) reports eslint(max-lines) errors in src/agents/sessions/session-manager-core.ts (701), src/agents/sessions/session-manager.ts (705) and src/state/agent-database-startup.ts (708).
  • This PR does not touch any of those files; all three are byte-identical to origin/main at 5620b17, so main fails the same stripe.
  • Every other required check is green, and the hosted ClawSweeper review is ready on this exact head (9b8df19).

@obviyus
obviyus merged commit 22c1060 into main Nov 1, 2026
164 of 168 checks passed
@obviyus
obviyus deleted the feat/session-fork-tools branch November 1, 2026 11:38
@obviyus

obviyus commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 22c1060 (maintainer override for the unrelated check-lint-core-2 max-lines failure on main).

  • Problem: Workshop owned the generic background-fork machinery and replayed the whole foreground turn context into its review.
  • Fix: one core owner, session-fork-run.ts, runs background work as a fork of the stored session, carries only the turn's requester identity, re-checks its current policy before running, and settles the caller's cleanup inside the same detached admission. skillWorkshopReviewOf is gone.
  • Proof: real-Gateway e2e for sender revocation while queued, the turn and fork gates, restart waiting for the notice, and all source fences; each new test fails on the defect it guards.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 2, 2026
… session (openclaw#190158)

## Problem

Skill Workshop is moving from core into the bundled `skill-workshop` plugin. Its background review cannot move as it is:

- The generic machinery (source-session fences, detached admission, hidden run, locked model, yielding to foreground work) lives inside Workshop files.
- The review replays the finished turn's whole run context (`foregroundPromptContext`, including live per-turn capabilities) into the background run, although it uses only the turn's identity and policy facts.
- The runner carries a Workshop-only `skillWorkshopReviewOf` parameter and a Workshop-only lane.

## Fix

- **New core owner `src/agents/session-fork-run.ts`:** a background agent run over a bounded copy of one session's conversation, through one completed transcript entry.
  - `prepareSessionFork` refuses before any model call unless every fork tool passes current policy, and returns the session's durable workspace.
  - `runSessionFork` owns the fences, detached admission, hidden run registration, locked model, yielding to foreground work and the usage diagnostic. The code moved verbatim from Workshop. The caller's settlement (Workshop: change feed and Learned notice) runs inside the same detached admission, so a graceful restart waits for it, as before.
  - **Run context:** agent dir, sandbox key and delivery channel come from the stored session. The turn's requester identity (sender, owner flag, group, channel; `src/agents/session-fork-requester.ts`) is carried explicitly, because the session never records who sent a turn. Both admission and the run re-resolve policy for that requester against the current config, so a sender-specific revocation made while a review is queued stops it before any provider call.
  - Forks mark themselves through the existing `inputProvenance` field (`internal_system`, `sourceTool: "session_fork"`, `sourceSessionKey`). Tools and model-call urgency read that instead of `skillWorkshopReviewOf`, so tool contexts get no new field.
- **Workshop review** keeps only its own decisions: eligibility, prompt, the feature switch, the change feed and the Learned notice. It receives only the requester projection of the turn context, never its live capabilities. `review-run.ts` is deleted.
- **Removed:** `skillWorkshopReviewOf`.
- **Lane:** `getSkillWorkshopReviewLane` becomes `getBackgroundOwnerLane(owner)`. Workshop's lane name is unchanged (`background:core:skill-workshop`).
- **Docs:** the harness side-effects page now says what the turn context is used for (it also drops a stale prompt-cache claim).

No schema, protocol or stored-data change. No new SDK exports, and harnesses change nothing. The plugin-facing `subagent.forkSession` additions ship with the plugin cutover that uses them.

## Impact

- One core owner serves background session work; Workshop becomes its first user.
- No intended behavior change: the review runs with the same requester policy as before, re-checked against current config.

## Evidence

All end-to-end cases below run a real Gateway with real embedded foreground turns, a fixture model provider, and config changes through `config.patch`.

| Check | Result |
| --- | --- |
| E2E: a sender-42 channel ingress turn (`agentCommandFromIngress`) queues a review; `tools.toolsBySender["id:42"].deny = ["skill_workshop"]` is added before it runs → no review model call, no change, skill file unchanged. The allowed counterpart learns normally | pass; the revoked case fails when the requester is not carried |
| E2E turn gate: `tools.deny: ["skill_workshop"]` during the turn, lifted before the review → nothing queued (trace: the turn's `toolNames` lacks the tool) | pass |
| E2E fork gate: the turn could call the tool; it is denied before the queued review runs → no review model call, no change (trace: fork policy check refuses) | pass |
| E2E: the channel notice send is held open after the skill change commits and the model run ends → Gateway root work stays active (a graceful restart waits); it drains after the send settles. Unit counterpart holds the notice callback | pass; both fail when settlement runs outside the admission |
| Unit: the source group's policy (from the session key) and wildcard sender rules refuse a fork (`session-fork-run.test.ts`) | pass |
| Existing review suites: yield to foreground work; source fences for permission, reset, replacement, deletion, rewrite, membership and rewind; canonical worktree workspace; cleanup after failure; grouped notices and undo; channel notice with Undo; propose mode | pass |
| `gateway-workshop-learning.e2e` (bounded request, `skill_workshop`-only tool list, patch and announce) | pass |
| All `*.workshop-contract` suites (existing cases unchanged; four new cases added) | pass |
| `pnpm check:changed` | pass, except the production dead-export scan, which flags `allowProviderModels` and `materializeSessionRepositoryWorkspaceOnGateway` in files this PR does not touch |
| Touched suites in total | 28 files, 311 tests pass |
| `git diff --check` | pass |

One test was deleted: it asserted the review saw the foreground turn's tool schemas, which the review stopped doing when it began limiting the model to `skill_workshop`.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 17, 2026
…00545)

## What Problem This Solves

Background work that reads a chat, such as Skill Workshop's learning review or a plugin reviewer, runs as a hidden "fork" of that chat. Forks that could use tools sent a cut-down request instead of the chat's own, so they paid full price for the whole conversation every time instead of reading it from the provider's prompt cache. They also stopped whenever anything else on the Gateway started (a cron job, a turn in another chat), and a Workshop review was silently cut off after two minutes.

## User Impact

- Background reviews and plugin forks read the conversation from the provider's prompt cache. In the live probe below, the first request of a fork with tools read 98% of its input from cache on Anthropic and OpenAI (was 0%); tool-free forks on OpenAI went from 0% to 99%.
- A fork keeps running when other chats or cron jobs run.
- Skill Workshop reviews run for the agent's own run timeout instead of two minutes.
- Reviews now see the full conversation, not a 32 KiB excerpt.

## Why This Change Was Made

OpenClaw had two session forks:

- `subagent.forkSession` (tool-free, #170146) replayed the parent's prepared request, so the provider cache hit. It ran its own 3-call model loop beside the agent runner.
- `runSessionFork` / `subagent.runForkedTurn` (tools, #190158, #190950) built a fresh, cut-down request: a 32 KiB / 64-event excerpt with tool results dropped, `promptMode: "minimal"`, only the caller's tools listed, a 16,384-token context budget, 2,048 output tokens, low thinking, a 120 s ceiling (`Math.min(timeoutMs, 120_000)`), and it aborted whenever any session on the Gateway started a run.

Every one of those clamps came from #173889 (a Skill Workshop rate-limit fix) and moved verbatim into the generic owner.

Now there is one fork primitive: `runSessionFork` in `src/agents/session-fork-run.ts`. `forkSession`, `runForkedTurn` and Skill Workshop all fork through it.

- **Same request as the parent.** While the parent's run is live, each fork request replays its last prepared request byte for byte and appends the fork's own items (`embedded-agent-runner/session-fork-request.ts`, the replay moved from the old `forkSession` loop). After the run settles, the fork reads the session's `openclaw.system-prompt` checkpoint and its own requests send that pinned system prompt verbatim (no prompt-update delta) and the pinned tool definitions in their order. It also sends the parent's `promptCacheKey` and the session's thinking level.
- **Tools listed, gated at run time.** The session's tools stay in the request. Only the caller's tools run, through the existing `toolExecutionAllow` gate; others return "`<tool>` is not available in this background run." A tool-free fork is an empty allow list plus `tool_choice: none` (Anthropic, OpenAI Responses, Chat Completions).
- **Clamps deleted:** the context excerpt, `promptMode: "minimal"`, `bootstrapContextMode: "lightweight"`, `contextTokenBudget: 16_384`, `maxTokens: 2_048`, `thinkLevel: "low"`, the narrowed `toolsAllow`, `codeModeOverride`/`disableToolSearch`/`forceMessageTool` overrides, and `Math.min(timeoutMs, 120_000)`. Output tokens follow the session; `runForkedTurn` gains an optional `maxTokens`.
- **Global yield deleted.** Runs in other sessions (cron included) no longer stop a fork. No new cancellation code.
- **Duplicate path deleted:** `embedded-agent-runner/session-fork.ts`, `session-fork-context.ts`, `tool-result-projection-replay.ts`, `runBtwSessionFork`, the built-in `toolCalls: "deny"` branch in `btw.ts`, the now-unproduced `uncachedSuffixMessage` / `independentResponsesRequest` transport markers, and the two perf scripts that only measured the deleted fork owner (`session-fork-retention-measure.mjs`, `responses-continuation-measure.mjs`). `btw.ts` keeps only harness dispatch for `forkSession`: Codex sessions still run Codex's own tool-free side question; built-in sessions call `runSessionFork`; CLI runtimes stay refused.
- **The fork reads the chat as the chat does.** It keeps its source conversation's channel history window (`dmHistoryLimit` and the like): the run resolves the limit from the policy key (`sandboxSessionKey`), which only a fork sets apart from its own key. A fork without an explicit entry anchors at the last message, because the leaf can be the prompt checkpoint. A tool call still running at the anchor reads as pending ("still running"), not failed, and only the unfinished calls of a partly finished batch get that placeholder; the source transcript is never written.

Safety checks kept: requester policy before any model call (`prepareSessionFork`), plugins grant only their own tools (#190950), detached admission and restart drain, plugin authority before each tool call and before `onSettled`, hidden run, never writing the source transcript, source checks for reset/replace/delete/rewrite, locked model with no fallbacks or transient retries.

Changed on purpose:
- A fork lists every session tool instead of only its own (execution is still gated).
- Background forks no longer yield to other sessions' runs. Skill Workshop's 15/30/60-minute rate-limit backoff is unchanged and still protects interactive capacity.
- A built-in tool-free fork now writes cache for its own suffix (~300 tokens in the probe below); the old loop opted its question out of Anthropic cache checkpoints.
- A tool-free fork whose anchored turn no longer holds its input still runs; a fork with tools still refuses, because sender-specific tool policy needs the turn's requester.

Accepted edge case: if a parent's turn crashed after its prompt checkpoint and before any reply, an idle-parent fork cannot see that checkpoint and sends its own rebuilt prompt (no cache hit). A running parent is replayed from its live request, and a completed turn ends with a reply after the checkpoint.

Left out on purpose:
- Codex `thread/fork` adapter (`extensions/codex/harness.ts:577`): unchanged, still reached through `btw.ts` for Codex-session `forkSession`.
- Plain `/btw` with tools (`commands-btw.ts`, `tui/embedded-backend.ts`): unchanged.
- CLI runtimes: forks stay refused.

### Plugin SDK impact

`plugin-sdk-impact` on ClawHub (2026-11-17, 2,657 eligible releases; 2,235 complete, 420 partial, 2 failed): **0** static references to `runtime.subagent.forkSession` and **0** to `runtime.subagent.runForkedTurn`. Coverage is incomplete, so this is not proof of no use. Bundled callers (source search): Advisor (`forkSession`) and Skill Workshop (`runForkedTurn`). The `forkSession` signature is unchanged; `runForkedTurn` gains an optional `maxTokens`. No export added or removed.

## Evidence

**Byte match on real providers.** Tier: source (`ocx src` scratch Gateways, isolated profile). A recording proxy captured every provider request. Each provider: two parent turns (one `ls` tool call), then one `runForkedTurn` (tools `[]`) and one `forkSession` through the plugin runtime. Digests are SHA-256 prefixes of `snapshotProviderPrefix` segments (`scripts/e2e/lib/anthropic-cache/prefix-stability.mts`). OpenAI Responses sends the system prompt as the first input item, so its `system` digest is `null` and the system prompt is checked as history item 0.

Anthropic `claude-sonnet-5-5`, parent last request (after run): system `e18e68ef17d925ff`, tools `33603f8641deb7e5` (13), cache key `b8ccb287386e0e54`. The system digest differs between runs (each run uses a new scratch workspace); "same" compares fork and parent within one run.

| Fork, first request | Before: system / tools / key / history | Before: cacheRead | After: system / tools / key / history | After: cacheRead / input |
|---|---|---|---|---|
| `runForkedTurn` | differs / differs (0 tools) / same / 7 of 7 | **0** (cacheWrite 2,810) | same / same / same / 7 of 7 | **19,141** / 19,446 |
| `forkSession` | same / same / same / 7 of 7 | 19,141 | same / same / same / 7 of 7 | 19,141 / 19,446 |

OpenAI `gpt-5.6-luna`, parent last request: tools `4481fd05f2c1d4c6` (12), cache key `975dd83e68fb404a`.

| Fork, first request | Before: tools / key / history | Before: cacheRead | After: tools / key / history | After: cacheRead / input |
|---|---|---|---|---|
| `runForkedTurn` | differs (0 tools) / same / 0 of 9 | **0** | same / same / 9 of 9 | **11,332** / 11,605 |
| `forkSession` | same / same / 9 of 9 | **0** (request dropped `text.verbosity`) | same / same / 9 of 9 | **11,530** / 11,605 |

**Tests** (vitest-source):
- `gateway-plugin-forked-turn.e2e`: the fork's first request now extends the parent's last request (system, tools, cache key, history) and its other fields (output limit, reasoning, instructions) equal the parent's. The reload-drain case now runs a turn in another session while the fork's model call is held, and the fork still settles `ok`. The mock model calls the plugin's tool through `dispatch_action`, because the fork now lists the session's tool catalog.
- `session-fork-request.test.ts`: replay ordering and ID spelling, transport handles, continuation fallback, `tool_choice` per API, replay skip when the parent lacks the fork's tool or lists a hosted tool, caller output limit.
- Unchanged assertions: `agent-tools.prefix-stability`, `session-fork-run`, Advisor, Skill Workshop suites.
- `server-plugin-subagent-runtime.fork-transport`: a `forkSession` on a Telegram DM with `dmHistoryLimit: 1` and a compacted history sends the session's pinned system prompt, drops history outside the parent's window, and sends nothing for another operator's session.
- `session-manager-model-context-limits`: a still-running call in a partly finished batch reads as pending while the finished call keeps its real result, and the source transcript is unchanged.
- Contract assertions updated because the contract changed: the e2e "fork sees only the caller's tool" and "system message differs by design" checks; `btw` deny tests now pass `sessionFork`; three Codex WebSocket tests of the deleted fork loop and two tests of the deleted fork context builder are removed.

**Size:** 51 files, +1,099 −3,438 (net −2,339). Production +776 −1,990; tests +222 −1,274; docs +101 −174.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…enclaw#200545)

## What Problem This Solves

Background work that reads a chat, such as Skill Workshop's learning review or a plugin reviewer, runs as a hidden "fork" of that chat. Forks that could use tools sent a cut-down request instead of the chat's own, so they paid full price for the whole conversation every time instead of reading it from the provider's prompt cache. They also stopped whenever anything else on the Gateway started (a cron job, a turn in another chat), and a Workshop review was silently cut off after two minutes.

## User Impact

- Background reviews and plugin forks read the conversation from the provider's prompt cache. In the live probe below, the first request of a fork with tools read 98% of its input from cache on Anthropic and OpenAI (was 0%); tool-free forks on OpenAI went from 0% to 99%.
- A fork keeps running when other chats or cron jobs run.
- Skill Workshop reviews run for the agent's own run timeout instead of two minutes.
- Reviews now see the full conversation, not a 32 KiB excerpt.

## Why This Change Was Made

OpenClaw had two session forks:

- `subagent.forkSession` (tool-free, openclaw#170146) replayed the parent's prepared request, so the provider cache hit. It ran its own 3-call model loop beside the agent runner.
- `runSessionFork` / `subagent.runForkedTurn` (tools, openclaw#190158, openclaw#190950) built a fresh, cut-down request: a 32 KiB / 64-event excerpt with tool results dropped, `promptMode: "minimal"`, only the caller's tools listed, a 16,384-token context budget, 2,048 output tokens, low thinking, a 120 s ceiling (`Math.min(timeoutMs, 120_000)`), and it aborted whenever any session on the Gateway started a run.

Every one of those clamps came from openclaw#173889 (a Skill Workshop rate-limit fix) and moved verbatim into the generic owner.

Now there is one fork primitive: `runSessionFork` in `src/agents/session-fork-run.ts`. `forkSession`, `runForkedTurn` and Skill Workshop all fork through it.

- **Same request as the parent.** While the parent's run is live, each fork request replays its last prepared request byte for byte and appends the fork's own items (`embedded-agent-runner/session-fork-request.ts`, the replay moved from the old `forkSession` loop). After the run settles, the fork reads the session's `openclaw.system-prompt` checkpoint and its own requests send that pinned system prompt verbatim (no prompt-update delta) and the pinned tool definitions in their order. It also sends the parent's `promptCacheKey` and the session's thinking level.
- **Tools listed, gated at run time.** The session's tools stay in the request. Only the caller's tools run, through the existing `toolExecutionAllow` gate; others return "`<tool>` is not available in this background run." A tool-free fork is an empty allow list plus `tool_choice: none` (Anthropic, OpenAI Responses, Chat Completions).
- **Clamps deleted:** the context excerpt, `promptMode: "minimal"`, `bootstrapContextMode: "lightweight"`, `contextTokenBudget: 16_384`, `maxTokens: 2_048`, `thinkLevel: "low"`, the narrowed `toolsAllow`, `codeModeOverride`/`disableToolSearch`/`forceMessageTool` overrides, and `Math.min(timeoutMs, 120_000)`. Output tokens follow the session; `runForkedTurn` gains an optional `maxTokens`.
- **Global yield deleted.** Runs in other sessions (cron included) no longer stop a fork. No new cancellation code.
- **Duplicate path deleted:** `embedded-agent-runner/session-fork.ts`, `session-fork-context.ts`, `tool-result-projection-replay.ts`, `runBtwSessionFork`, the built-in `toolCalls: "deny"` branch in `btw.ts`, the now-unproduced `uncachedSuffixMessage` / `independentResponsesRequest` transport markers, and the two perf scripts that only measured the deleted fork owner (`session-fork-retention-measure.mjs`, `responses-continuation-measure.mjs`). `btw.ts` keeps only harness dispatch for `forkSession`: Codex sessions still run Codex's own tool-free side question; built-in sessions call `runSessionFork`; CLI runtimes stay refused.
- **The fork reads the chat as the chat does.** It keeps its source conversation's channel history window (`dmHistoryLimit` and the like): the run resolves the limit from the policy key (`sandboxSessionKey`), which only a fork sets apart from its own key. A fork without an explicit entry anchors at the last message, because the leaf can be the prompt checkpoint. A tool call still running at the anchor reads as pending ("still running"), not failed, and only the unfinished calls of a partly finished batch get that placeholder; the source transcript is never written.

Safety checks kept: requester policy before any model call (`prepareSessionFork`), plugins grant only their own tools (openclaw#190950), detached admission and restart drain, plugin authority before each tool call and before `onSettled`, hidden run, never writing the source transcript, source checks for reset/replace/delete/rewrite, locked model with no fallbacks or transient retries.

Changed on purpose:
- A fork lists every session tool instead of only its own (execution is still gated).
- Background forks no longer yield to other sessions' runs. Skill Workshop's 15/30/60-minute rate-limit backoff is unchanged and still protects interactive capacity.
- A built-in tool-free fork now writes cache for its own suffix (~300 tokens in the probe below); the old loop opted its question out of Anthropic cache checkpoints.
- A tool-free fork whose anchored turn no longer holds its input still runs; a fork with tools still refuses, because sender-specific tool policy needs the turn's requester.

Accepted edge case: if a parent's turn crashed after its prompt checkpoint and before any reply, an idle-parent fork cannot see that checkpoint and sends its own rebuilt prompt (no cache hit). A running parent is replayed from its live request, and a completed turn ends with a reply after the checkpoint.

Left out on purpose:
- Codex `thread/fork` adapter (`extensions/codex/harness.ts:577`): unchanged, still reached through `btw.ts` for Codex-session `forkSession`.
- Plain `/btw` with tools (`commands-btw.ts`, `tui/embedded-backend.ts`): unchanged.
- CLI runtimes: forks stay refused.

### Plugin SDK impact

`plugin-sdk-impact` on ClawHub (2026-11-17, 2,657 eligible releases; 2,235 complete, 420 partial, 2 failed): **0** static references to `runtime.subagent.forkSession` and **0** to `runtime.subagent.runForkedTurn`. Coverage is incomplete, so this is not proof of no use. Bundled callers (source search): Advisor (`forkSession`) and Skill Workshop (`runForkedTurn`). The `forkSession` signature is unchanged; `runForkedTurn` gains an optional `maxTokens`. No export added or removed.

## Evidence

**Byte match on real providers.** Tier: source (`ocx src` scratch Gateways, isolated profile). A recording proxy captured every provider request. Each provider: two parent turns (one `ls` tool call), then one `runForkedTurn` (tools `[]`) and one `forkSession` through the plugin runtime. Digests are SHA-256 prefixes of `snapshotProviderPrefix` segments (`scripts/e2e/lib/anthropic-cache/prefix-stability.mts`). OpenAI Responses sends the system prompt as the first input item, so its `system` digest is `null` and the system prompt is checked as history item 0.

Anthropic `claude-sonnet-5-5`, parent last request (after run): system `e18e68ef17d925ff`, tools `33603f8641deb7e5` (13), cache key `b8ccb287386e0e54`. The system digest differs between runs (each run uses a new scratch workspace); "same" compares fork and parent within one run.

| Fork, first request | Before: system / tools / key / history | Before: cacheRead | After: system / tools / key / history | After: cacheRead / input |
|---|---|---|---|---|
| `runForkedTurn` | differs / differs (0 tools) / same / 7 of 7 | **0** (cacheWrite 2,810) | same / same / same / 7 of 7 | **19,141** / 19,446 |
| `forkSession` | same / same / same / 7 of 7 | 19,141 | same / same / same / 7 of 7 | 19,141 / 19,446 |

OpenAI `gpt-5.6-luna`, parent last request: tools `4481fd05f2c1d4c6` (12), cache key `975dd83e68fb404a`.

| Fork, first request | Before: tools / key / history | Before: cacheRead | After: tools / key / history | After: cacheRead / input |
|---|---|---|---|---|
| `runForkedTurn` | differs (0 tools) / same / 0 of 9 | **0** | same / same / 9 of 9 | **11,332** / 11,605 |
| `forkSession` | same / same / 9 of 9 | **0** (request dropped `text.verbosity`) | same / same / 9 of 9 | **11,530** / 11,605 |

**Tests** (vitest-source):
- `gateway-plugin-forked-turn.e2e`: the fork's first request now extends the parent's last request (system, tools, cache key, history) and its other fields (output limit, reasoning, instructions) equal the parent's. The reload-drain case now runs a turn in another session while the fork's model call is held, and the fork still settles `ok`. The mock model calls the plugin's tool through `dispatch_action`, because the fork now lists the session's tool catalog.
- `session-fork-request.test.ts`: replay ordering and ID spelling, transport handles, continuation fallback, `tool_choice` per API, replay skip when the parent lacks the fork's tool or lists a hosted tool, caller output limit.
- Unchanged assertions: `agent-tools.prefix-stability`, `session-fork-run`, Advisor, Skill Workshop suites.
- `server-plugin-subagent-runtime.fork-transport`: a `forkSession` on a Telegram DM with `dmHistoryLimit: 1` and a compacted history sends the session's pinned system prompt, drops history outside the parent's window, and sends nothing for another operator's session.
- `session-manager-model-context-limits`: a still-running call in a partly finished batch reads as pending while the finished call keeps its real result, and the source transcript is unchanged.
- Contract assertions updated because the contract changed: the e2e "fork sees only the caller's tool" and "system message differs by design" checks; `btw` deny tests now pass `sessionFork`; three Codex WebSocket tests of the deleted fork loop and two tests of the deleted fork context builder are removed.

**Size:** 51 files, +1,099 −3,438 (net −2,339). Production +776 −1,990; tests +222 −1,274; docs +101 −174.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…00545)

Background work that reads a chat, such as Skill Workshop's learning review or a plugin reviewer, runs as a hidden "fork" of that chat. Forks that could use tools sent a cut-down request instead of the chat's own, so they paid full price for the whole conversation every time instead of reading it from the provider's prompt cache. They also stopped whenever anything else on the Gateway started (a cron job, a turn in another chat), and a Workshop review was silently cut off after two minutes.

- Background reviews and plugin forks read the conversation from the provider's prompt cache. In the live probe below, the first request of a fork with tools read 98% of its input from cache on Anthropic and OpenAI (was 0%); tool-free forks on OpenAI went from 0% to 99%.
- A fork keeps running when other chats or cron jobs run.
- Skill Workshop reviews run for the agent's own run timeout instead of two minutes.
- Reviews now see the full conversation, not a 32 KiB excerpt.

OpenClaw had two session forks:

- `subagent.forkSession` (tool-free, #170146) replayed the parent's prepared request, so the provider cache hit. It ran its own 3-call model loop beside the agent runner.
- `runSessionFork` / `subagent.runForkedTurn` (tools, #190158, #190950) built a fresh, cut-down request: a 32 KiB / 64-event excerpt with tool results dropped, `promptMode: "minimal"`, only the caller's tools listed, a 16,384-token context budget, 2,048 output tokens, low thinking, a 120 s ceiling (`Math.min(timeoutMs, 120_000)`), and it aborted whenever any session on the Gateway started a run.

Every one of those clamps came from #173889 (a Skill Workshop rate-limit fix) and moved verbatim into the generic owner.

Now there is one fork primitive: `runSessionFork` in `src/agents/session-fork-run.ts`. `forkSession`, `runForkedTurn` and Skill Workshop all fork through it.

- **Same request as the parent.** While the parent's run is live, each fork request replays its last prepared request byte for byte and appends the fork's own items (`embedded-agent-runner/session-fork-request.ts`, the replay moved from the old `forkSession` loop). After the run settles, the fork reads the session's `openclaw.system-prompt` checkpoint and its own requests send that pinned system prompt verbatim (no prompt-update delta) and the pinned tool definitions in their order. It also sends the parent's `promptCacheKey` and the session's thinking level.
- **Tools listed, gated at run time.** The session's tools stay in the request. Only the caller's tools run, through the existing `toolExecutionAllow` gate; others return "`<tool>` is not available in this background run." A tool-free fork is an empty allow list plus `tool_choice: none` (Anthropic, OpenAI Responses, Chat Completions).
- **Clamps deleted:** the context excerpt, `promptMode: "minimal"`, `bootstrapContextMode: "lightweight"`, `contextTokenBudget: 16_384`, `maxTokens: 2_048`, `thinkLevel: "low"`, the narrowed `toolsAllow`, `codeModeOverride`/`disableToolSearch`/`forceMessageTool` overrides, and `Math.min(timeoutMs, 120_000)`. Output tokens follow the session; `runForkedTurn` gains an optional `maxTokens`.
- **Global yield deleted.** Runs in other sessions (cron included) no longer stop a fork. No new cancellation code.
- **Duplicate path deleted:** `embedded-agent-runner/session-fork.ts`, `session-fork-context.ts`, `tool-result-projection-replay.ts`, `runBtwSessionFork`, the built-in `toolCalls: "deny"` branch in `btw.ts`, the now-unproduced `uncachedSuffixMessage` / `independentResponsesRequest` transport markers, and the two perf scripts that only measured the deleted fork owner (`session-fork-retention-measure.mjs`, `responses-continuation-measure.mjs`). `btw.ts` keeps only harness dispatch for `forkSession`: Codex sessions still run Codex's own tool-free side question; built-in sessions call `runSessionFork`; CLI runtimes stay refused.
- **The fork reads the chat as the chat does.** It keeps its source conversation's channel history window (`dmHistoryLimit` and the like): the run resolves the limit from the policy key (`sandboxSessionKey`), which only a fork sets apart from its own key. A fork without an explicit entry anchors at the last message, because the leaf can be the prompt checkpoint. A tool call still running at the anchor reads as pending ("still running"), not failed, and only the unfinished calls of a partly finished batch get that placeholder; the source transcript is never written.

Safety checks kept: requester policy before any model call (`prepareSessionFork`), plugins grant only their own tools (#190950), detached admission and restart drain, plugin authority before each tool call and before `onSettled`, hidden run, never writing the source transcript, source checks for reset/replace/delete/rewrite, locked model with no fallbacks or transient retries.

Changed on purpose:
- A fork lists every session tool instead of only its own (execution is still gated).
- Background forks no longer yield to other sessions' runs. Skill Workshop's 15/30/60-minute rate-limit backoff is unchanged and still protects interactive capacity.
- A built-in tool-free fork now writes cache for its own suffix (~300 tokens in the probe below); the old loop opted its question out of Anthropic cache checkpoints.
- A tool-free fork whose anchored turn no longer holds its input still runs; a fork with tools still refuses, because sender-specific tool policy needs the turn's requester.

Accepted edge case: if a parent's turn crashed after its prompt checkpoint and before any reply, an idle-parent fork cannot see that checkpoint and sends its own rebuilt prompt (no cache hit). A running parent is replayed from its live request, and a completed turn ends with a reply after the checkpoint.

Left out on purpose:
- Codex `thread/fork` adapter (`extensions/codex/harness.ts:577`): unchanged, still reached through `btw.ts` for Codex-session `forkSession`.
- Plain `/btw` with tools (`commands-btw.ts`, `tui/embedded-backend.ts`): unchanged.
- CLI runtimes: forks stay refused.

`plugin-sdk-impact` on ClawHub (2026-11-17, 2,657 eligible releases; 2,235 complete, 420 partial, 2 failed): **0** static references to `runtime.subagent.forkSession` and **0** to `runtime.subagent.runForkedTurn`. Coverage is incomplete, so this is not proof of no use. Bundled callers (source search): Advisor (`forkSession`) and Skill Workshop (`runForkedTurn`). The `forkSession` signature is unchanged; `runForkedTurn` gains an optional `maxTokens`. No export added or removed.

**Byte match on real providers.** Tier: source (`ocx src` scratch Gateways, isolated profile). A recording proxy captured every provider request. Each provider: two parent turns (one `ls` tool call), then one `runForkedTurn` (tools `[]`) and one `forkSession` through the plugin runtime. Digests are SHA-256 prefixes of `snapshotProviderPrefix` segments (`scripts/e2e/lib/anthropic-cache/prefix-stability.mts`). OpenAI Responses sends the system prompt as the first input item, so its `system` digest is `null` and the system prompt is checked as history item 0.

Anthropic `claude-sonnet-5-5`, parent last request (after run): system `e18e68ef17d925ff`, tools `33603f8641deb7e5` (13), cache key `b8ccb287386e0e54`. The system digest differs between runs (each run uses a new scratch workspace); "same" compares fork and parent within one run.

| Fork, first request | Before: system / tools / key / history | Before: cacheRead | After: system / tools / key / history | After: cacheRead / input |
|---|---|---|---|---|
| `runForkedTurn` | differs / differs (0 tools) / same / 7 of 7 | **0** (cacheWrite 2,810) | same / same / same / 7 of 7 | **19,141** / 19,446 |
| `forkSession` | same / same / same / 7 of 7 | 19,141 | same / same / same / 7 of 7 | 19,141 / 19,446 |

OpenAI `gpt-5.6-luna`, parent last request: tools `4481fd05f2c1d4c6` (12), cache key `975dd83e68fb404a`.

| Fork, first request | Before: tools / key / history | Before: cacheRead | After: tools / key / history | After: cacheRead / input |
|---|---|---|---|---|
| `runForkedTurn` | differs (0 tools) / same / 0 of 9 | **0** | same / same / 9 of 9 | **11,332** / 11,605 |
| `forkSession` | same / same / 9 of 9 | **0** (request dropped `text.verbosity`) | same / same / 9 of 9 | **11,530** / 11,605 |

**Tests** (vitest-source):
- `gateway-plugin-forked-turn.e2e`: the fork's first request now extends the parent's last request (system, tools, cache key, history) and its other fields (output limit, reasoning, instructions) equal the parent's. The reload-drain case now runs a turn in another session while the fork's model call is held, and the fork still settles `ok`. The mock model calls the plugin's tool through `dispatch_action`, because the fork now lists the session's tool catalog.
- `session-fork-request.test.ts`: replay ordering and ID spelling, transport handles, continuation fallback, `tool_choice` per API, replay skip when the parent lacks the fork's tool or lists a hosted tool, caller output limit.
- Unchanged assertions: `agent-tools.prefix-stability`, `session-fork-run`, Advisor, Skill Workshop suites.
- `server-plugin-subagent-runtime.fork-transport`: a `forkSession` on a Telegram DM with `dmHistoryLimit: 1` and a compacted history sends the session's pinned system prompt, drops history outside the parent's window, and sends nothing for another operator's session.
- `session-manager-model-context-limits`: a still-running call in a partly finished batch reads as pending while the finished call keeps its real result, and the source transcript is unchanged.
- Contract assertions updated because the contract changed: the e2e "fork sees only the caller's tool" and "system message differs by design" checks; `btw` deny tests now pass `sessionFork`; three Codex WebSocket tests of the deleted fork loop and two tests of the deleted fork context builder are removed.

**Size:** 51 files, +1,099 −3,438 (net −2,339). Production +776 −1,990; tests +222 −1,274; docs +101 −174.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 2a7ca16)

Release adaptation: preserve the baseline removal of the session identity allowlist; the remaining fork owner and callers apply unchanged. Follow-up disposition: source bounded owner history reviewed; focused prefix and fork proof required on this lane.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit f080b30127abe414dbf9a4fbe0be2b550139fa10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant