Skip to content

Commit 30772d5

Browse files
authored
fix(sessions): preserve context and lifecycle when forking chats (#132227)
* fix(sessions): preserve fork lifecycle ownership and context Preserve incognito storage, revalidate message-cut authority at commit, and keep late UI fork results scoped to their presentation. Carry prepared child identity and actual context through subagent cleanup and receipts. Verify native source cuts with canonical projection and preserve supervision connection and cleanup ownership. Document the separate canonical-descendant initialization limitation. * refactor(agents): remove unused subagent prompt task input * test(codex): validate native fork fixture request shapes * fix(codex): avoid inherited labels in native session forks * fix(test): align fork prompt fixtures and session type imports * refactor(agents): reuse subagent attachment result type
1 parent 7e2111e commit 30772d5

49 files changed

Lines changed: 3090 additions & 787 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/concepts/session-tool.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ See [Session state awareness](/concepts/session-state) for the full model: event
136136

137137
## Spawning sub-agents
138138

139-
`sessions_spawn` creates an isolated session for a background task by default. It is always non-blocking; it returns immediately with a `runId` and `childSessionKey`. Native sub-agent runs receive the delegated task in the child session's first visible `[Subagent Task]` message, while the system prompt carries only sub-agent runtime rules and routing context.
139+
`sessions_spawn` creates a separate session for a background task. Non-thread spawns start with isolated context by default; thread-bound spawns follow the configured context policy described below. It is always non-blocking; it returns immediately with a `runId` and `childSessionKey`. Native sub-agent runs receive their delegated task in a `[Subagent Task]` message appended after any forked history; inherited task envelopes are context, not the current child's assignment. The system prompt carries only sub-agent runtime rules and routing context.
140140

141141
Key options:
142142

@@ -145,7 +145,7 @@ Key options:
145145
- `runTimeoutSeconds` to override the configured child-run timeout; `0` disables it.
146146
- `thread: true` to bind the spawn to a chat thread (Discord, Slack, etc.).
147147
- `sandbox: "require"` to enforce sandboxing on the child.
148-
- `context: "fork"` for native sub-agents when the child needs the current requester transcript; omit it or use `context: "isolated"` for a clean child. `context: "fork"` is only valid with `runtime: "subagent"`. Thread-bound native sub-agents default to `context: "fork"` unless `threadBindings.defaultSpawnContext` says otherwise.
148+
- `context: "fork"` when the child needs the current requester transcript; this requires `runtime: "subagent"` and the same agent as the requester, whether the child is hidden or visible. Use `context: "isolated"` explicitly for a clean child. Omission means isolated context for non-thread spawns; thread-bound native sub-agents follow `threadBindings.defaultSpawnContext`, which defaults to `fork`.
149149
- `visible: true` to create a persistent dashboard session instead of a hidden sub-agent session. Visible spawns support an explicit sidebar `category`, model, working directory, same-agent transcript fork, and an optional [managed worktree](/concepts/managed-worktrees); see [Sub-agents](/tools/subagents#tool-parameters) for the exact compatibility limits. The accepted result is a receipt: it includes the child session key, run id, a Control UI `sessionUrl` (omitted when the Control UI is disabled), and an `owner` record naming the requesting agent. When acknowledging the spawn in a channel, put the session URL on the first line and `Owner: <label>` on the second. The spawned session is attributed to the requesting agent in the sidebar; see [Multi-user mode](/concepts/multi-user#agent-spawned-sessions).
150150

151151
Default leaf sub-agents do not get session tools. When `maxSpawnDepth >= 2`, depth-1 orchestrator sub-agents additionally receive `sessions_spawn`, `subagents`, `sessions_list`, and `sessions_history` so they can manage their own children. Leaf runs still do not get recursive orchestration tools.

‎docs/plugins/codex-supervision.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,14 @@ or clear the locked native binding. The `/codex model` query and `/codex fast`,
253253
`/codex permissions`, and `/codex threads` remain available. Start another
254254
ordinary session when you want a different model or fresh thread.
255255

256+
**Fork from here** can branch before a mirrored user message from the original
257+
native source. The child keeps that source's connection and model-locked harness,
258+
and the original source and parent Chat remain unchanged. Messages added after
259+
OpenClaw starts its canonical harness thread are not supported as fork points
260+
yet: those requests are rejected rather than rebuilding model history from an
261+
incomplete native transcript view. Choose an original mirrored source message
262+
when forking from OpenClaw.
263+
256264
Keep supervision enabled for this Chat. If supervision is disabled or its
257265
stored connection binding becomes unavailable or inconsistent, the turn fails
258266
closed instead of moving to an ordinary agent-home session.

‎docs/reference/session-management-compaction.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@ Overview docs first: [Session management](/concepts/session), [Compaction](/conc
1818

1919
Older installs may still have `sessions.json` files under the agent `sessions/`
2020
directory. Treat those files as legacy session-row migration inputs or explicit
21-
offline-maintenance targets. Gateway startup and `openclaw doctor --fix` import
22-
hot legacy rows and transcript history into the per-agent SQLite store
23-
automatically. Run `openclaw doctor --session-sqlite inspect
24-
--session-sqlite-all-agents`, then follow the [Doctor migration
25-
sequence](/cli/doctor#session-sqlite-migration), when you need explicit
26-
inspection or validation evidence. If a migration fails after legacy transcript
21+
offline-maintenance targets. Gateway startup does not import them. Stop the
22+
Gateway, back up its state, and use `openclaw doctor --fix` to import legacy rows
23+
and transcript history into the per-agent SQLite store. Run
24+
`openclaw doctor --session-sqlite inspect --session-sqlite-all-agents`, then
25+
follow the [Doctor migration sequence](/cli/doctor#session-sqlite-migration)
26+
for inspection and validation. If a migration fails after legacy transcript
2727
artifacts were archived, use the Doctor recovery mode from that sequence.
2828
Recovery uses migration manifests, restores only the affected archived support
2929
artifacts, prepares a sanitized GitHub issue report when requested, and does not
@@ -137,7 +137,8 @@ Each `sessionKey` points at a current `sessionId` (the SQLite transcript identit
137137
- **Control UI reconnect resume** preserves the currently visible session for one reconnect send when the Gateway receives the matching `sessionId` from an operator UI client. This is a one-shot signal; ordinary stale sends still create a new `sessionId`.
138138
- **System events** (heartbeat, cron wakeups, exec notifications, gateway bookkeeping) may mutate the session row but never extend daily/idle reset freshness. Reset rollover discards queued system-event notices for the previous session before the fresh prompt is built.
139139
- **Automatic parent fork policy** uses OpenClaw's active branch when creating a thread or subagent fork. If that branch is too large (over a fixed internal cap, currently 100K tokens), OpenClaw starts the child with isolated context instead of failing or inheriting unusable history. Sizing is automatic and not configurable; legacy `session.parentForkMaxTokens` config is removed by `openclaw doctor --fix`.
140-
- **Operator forks**: `sessions.create { parentSessionKey, fork: true }` creates a new session whose transcript branches from the parent's current state. Admission uses the selected child model's effective usable input capacity, falling back to the 100K safety cap when model capacity is unavailable. The fork is refused while the parent has an active run, inherits the parent's model selection unless one is passed explicitly, and marks the child `forkedFromParent` with fresh token counters.
140+
- **Operator forks**: `sessions.create { parentSessionKey, fork: true }` branches from the parent's current state. Admission uses the selected child model's effective usable input capacity, falling back to the 100K safety cap when model capacity is unavailable. A normal fork is refused while the parent has an active run; adding `forkFrom: "last-completed"` copies only through the last completed assistant message, excluding the in-progress tail. Unlike automatic parent forks, an operator fork over its capacity limit is rejected rather than accepted with isolated context. The child inherits the parent's model selection unless one is passed explicitly. The response marks it `forkedFromParent`, and token counters start fresh.
141+
- **Message forks**: `sessions.fork { sessionKey, entryId }` creates a child from the active-path prefix before the selected user message and returns that message to the composer for editing. The parent remains unchanged. Incognito forks retain the parent's in-memory storage class; restarting the Gateway removes both sessions. See [Control UI](/web/control-ui) for fork and rewind actions.
141142

142143
## Session store schema
143144

‎docs/tools/subagents.md‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -127,13 +127,15 @@ explicitly unsupported even though the ACP spawn and child are observable.
127127

128128
## Context modes
129129

130-
Native sub-agents start isolated unless the caller explicitly asks to fork
131-
the current transcript.
130+
Non-thread native sub-agents start isolated unless the caller explicitly asks
131+
to fork the current transcript. Thread-bound spawns follow
132+
`threadBindings.defaultSpawnContext`, which defaults to `fork`. Pass
133+
`context: "isolated"` explicitly when the child must start with clean context.
132134

133-
| Mode | When to use it | Behavior |
134-
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
135-
| `isolated` | Fresh research, independent implementation, slow tool work, or anything that can be briefed in the task text | Creates a clean child transcript. This is the default and keeps token use lower. |
136-
| `fork` | Work that depends on the current conversation, prior tool results, or nuanced instructions already present in the requester transcript | Branches the requester transcript into the child session before the child starts. |
135+
| Mode | When to use it | Behavior |
136+
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
137+
| `isolated` | Fresh research, independent implementation, slow tool work, or anything that can be briefed in the task text | Creates a clean child transcript. Default for non-thread spawns; keeps token use lower. |
138+
| `fork` | Work that depends on the current conversation, prior tool results, or nuanced instructions already present in the requester transcript | Branches the requester transcript into the child session before the child starts. |
137139

138140
Use `fork` sparingly. It is for context-sensitive delegation, not a
139141
replacement for writing a clear task prompt.
@@ -160,11 +162,13 @@ session to confirm the effective tool list.
160162
- **Thinking:** native sub-agents inherit the caller unless you set `agents.defaults.subagents.thinking` (or per-agent `agents.entries.*.subagents.thinking`). ACP runtime spawns also apply `agents.defaults.models["provider/model"].params.thinking` for the selected model. An explicit `sessions_spawn.thinking` still wins.
161163
- **Run timeout:** pass `runTimeoutSeconds` to set a timeout for a specific native, ACP, or visible sub-agent run. When omitted, OpenClaw uses `agents.defaults.subagents.runTimeoutSeconds` if configured; otherwise it falls back to `0` (no timeout). An explicit `0` disables the timeout for that run.
162164
- **Process lifetime:** a detached OpenClaw sub-agent has its own run lifecycle. A background task created inside an external CLI backend is different: it shares the parent CLI subprocess and stops if that parent reaches `agents.defaults.timeoutSeconds`.
163-
- **Task delivery:** native sub-agents receive the delegated task in their first visible `[Subagent Task]` message. The sub-agent system prompt carries runtime rules and routing context, not a hidden duplicate of the task.
165+
- **Task delivery:** native sub-agents receive their delegated task in a `[Subagent Task]` message appended after any forked history. Inherited task envelopes are context, not the current child's assignment. The sub-agent system prompt carries runtime rules and routing context, not a hidden duplicate of the task.
164166

165-
Accepted native sub-agent spawns include the resolved child model metadata
166-
in the tool result: `resolvedModel` contains the applied model ref and
167-
`resolvedProvider` contains the provider prefix when the ref has one.
167+
Accepted native sub-agent spawns report their actual initialized `context`
168+
(`fork` or `isolated`), including `isolated` when a requested fork exceeds the
169+
parent-context size cap. They also include resolved child model metadata:
170+
`resolvedModel` contains the applied model ref and `resolvedProvider` contains
171+
the provider prefix when the ref has one.
168172

169173
### Delegation prompt mode
170174

@@ -245,8 +249,8 @@ In `prefer` mode, hidden sub-agents are for internal legwork that the user does
245249
<ParamField path="sandbox" type='"inherit" | "require"' default="inherit">
246250
`require` rejects the spawn unless the target child runtime is sandboxed.
247251
</ParamField>
248-
<ParamField path="context" type='"isolated" | "fork"' default="isolated">
249-
`fork` branches the requester's current transcript into the child session. Native sub-agents only. Thread-bound spawns default to `fork`; non-thread spawns default to `isolated`. A visible fork must target the same agent as the requester.
252+
<ParamField path="context" type='"isolated" | "fork"'>
253+
`fork` branches the requester's current transcript into the child session. Native sub-agents only. Non-thread spawns default to `isolated`; thread-bound spawns follow `threadBindings.defaultSpawnContext`, which defaults to `fork`. Pass `isolated` explicitly to guarantee clean context. All native forks, hidden or visible, must target the same agent as the requester.
250254
</ParamField>
251255
<ParamField path="visible" type="boolean" default="false">
252256
Create a persistent dashboard session for work the user will watch or return to, or when they ask for a thread. Visible spawns support only `runtime: "subagent"` and always keep the created session.

‎extensions/codex/src/app-server/session-binding.test.ts‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,121 @@ describe("Codex app-server binding store", () => {
605605
});
606606
});
607607

608+
it.each([
609+
"absent",
610+
"cleared",
611+
"retired",
612+
"other generation cleared",
613+
"other generation active",
614+
"exact pending",
615+
"changed snapshot",
616+
"changed connection",
617+
"tracking successor",
618+
"materialized successor",
619+
"ordinary successor",
620+
])("guards failed-creation cleanup against an %s owner", async (owner) => {
621+
const { state } = createStateStore();
622+
const store = createCodexAppServerBindingStore(state);
623+
const identity = {
624+
kind: "session" as const,
625+
agentId: "main",
626+
sessionId: "creation",
627+
sessionKey: "agent:main:fork",
628+
};
629+
const expected = {
630+
sourceThreadId: "thread-fork",
631+
connectionFingerprint: "connection-one",
632+
lastTurnId: "turn-terminal",
633+
};
634+
const key = bindingStoreKey(identity);
635+
if (owner !== "absent") {
636+
const generation = owner.startsWith("other generation") ? "successor" : identity.sessionId;
637+
const cleared = owner.includes("cleared") || owner === "retired";
638+
state.register(
639+
key,
640+
cleared
641+
? {
642+
version: 1,
643+
state: "cleared",
644+
sessionId: generation,
645+
...(owner === "retired" ? { retired: true } : {}),
646+
}
647+
: {
648+
version: 1,
649+
state: "active",
650+
sessionId: generation,
651+
binding:
652+
owner === "ordinary successor"
653+
? { threadId: expected.sourceThreadId, cwd: "/repo" }
654+
: {
655+
threadId:
656+
owner === "materialized successor"
657+
? "thread-final"
658+
: expected.sourceThreadId,
659+
cwd: "/repo",
660+
connectionScope: "supervision",
661+
supervisionSourceThreadId: expected.sourceThreadId,
662+
preserveNativeModel: true,
663+
conversationSourceTransferComplete: true,
664+
model: "native-model",
665+
modelProvider: "native-provider",
666+
...(owner === "materialized successor"
667+
? {}
668+
: {
669+
pendingSupervisionBranch: {
670+
...expected,
671+
...(owner === "changed snapshot"
672+
? { lastTurnId: "turn-successor" }
673+
: {}),
674+
...(owner === "changed connection"
675+
? { connectionFingerprint: "connection-two" }
676+
: {}),
677+
...(owner === "tracking successor"
678+
? { cleanupThreadIds: ["thread-probe"] }
679+
: {}),
680+
},
681+
}),
682+
},
683+
},
684+
);
685+
}
686+
const before = state.lookup(key);
687+
const cleared = ["absent", "cleared", "retired", "exact pending"].includes(owner);
688+
await expect(
689+
store.mutate(identity, {
690+
kind: "clear",
691+
threadId: expected.sourceThreadId,
692+
expectedPendingSupervisionBranch: expected,
693+
}),
694+
).resolves.toBe(cleared);
695+
if (!cleared) {
696+
expect(state.lookup(key)).toEqual(before);
697+
return;
698+
}
699+
await expect(store.read(identity)).resolves.toBeUndefined();
700+
// Compensation is idempotent, but an ordinary thread-specific clear still needs its owner.
701+
await expect(
702+
store.mutate(identity, {
703+
kind: "clear",
704+
threadId: expected.sourceThreadId,
705+
expectedPendingSupervisionBranch: expected,
706+
}),
707+
).resolves.toBe(true);
708+
await expect(
709+
store.mutate(identity, {
710+
kind: "clear",
711+
threadId: expected.sourceThreadId,
712+
}),
713+
).resolves.toBe(false);
714+
await expect(
715+
store.mutate(identity, {
716+
kind: "clear",
717+
threadId: "different-thread",
718+
expectedPendingSupervisionBranch: expected,
719+
}),
720+
).resolves.toBe(false);
721+
});
722+
608723
it("round-trips account app policy context", async () => {
609724
const { state } = createStateStore();
610725
const store = createCodexAppServerBindingStore(state);

0 commit comments

Comments
 (0)