Repository navigation
fix(sessions): preserve context and lifecycle when forking chats - #132227
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 11:18 PM ET / August 29, 2026, 03:18 UTC. ClawSweeper reviewWhat this changesThe branch preserves context, lifecycle fencing, incognito storage identity, and upstream Codex linkage when users or agents fork chats. Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readinessNo introduced defect was found in the inspected Gateway, SQLite, UI, subagent, or Codex-plugin paths. The pull request remains necessary because fetched main does not contain its head; the final merge review cannot be completed until the pinned Codex app-server contract is directly available for inspection. Priority: P1 Review scores
Verification
How this fits togetherFork requests enter through the Gateway, which authorizes and fences the lifecycle before it copies a child session into SQLite for chat or subagent continuation. Codex-backed sessions also request an upstream app-server fork and attach the resulting thread to OpenClaw supervision. flowchart LR
A[Chat or subagent fork request] --> B[Gateway authorization]
B --> C[Lifecycle fence]
C --> D[SQLite child session]
C --> E[Codex app-server fork]
D --> F[Chat or agent continuation]
E --> F
Before merge
Agent review detailsSecurityNone. PR surfaceSource +153, Tests +2137, Docs +13. Total +2303 across 49 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Make the pinned Codex app-server source available for direct contract inspection, then refresh the merge review against the exact head. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: the branch contains real Gateway/SQLite boundary scenarios for the reported locked-history, incognito, and revoked-authority fork cases, though this read-only review did not execute them. Is this the best way to solve the issue? Unclear: local owner-boundary inspection found no introduced defect, but the upstream Codex contract required by the changed path could not be directly inspected. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 383a293b32d9. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
|
Addressing the incognito finding and both rank-up moves: I independently traced the candidate's producers and the pinned Codex source. I am not accepting this as a reachable P1 in the supported flow; restoring the old flag would reinstate a test-only path, not repair ordinary Codex-backed incognito forks. The distinction is Codex-backed versus upstream-linked. The Gateway selects native forking only when an upstream-link row exists. Without a link it uses the local message-cut owner. The caller cannot independently choose an incognito child: its storage class comes from the source. Ordinary Codex-backed incognito sessions take that local path; their real UI/provider flow, prefix, draft, child continuation, parent preservation, and reload passed. The real SQLite boundary tests additionally verify the absence of durable incognito rows and their loss on memory-store close. Native catalog adoption generates a deterministic durable harness key and creates it without an incognito option. The other production link writer is the native fork itself. Its real runtime creator does not forward incognito, and the underlying creator rejects an incognito-shaped key without that flag. Patch, alias, migration, and binding-import paths did not supply a supported linked-incognito producer. The removed mock changed only the child key on a durable-source fixture and replaced this real creator. For the dependency-source rank-up: I personally read sibling Codex at Qualification: trusted plugins have broad SDK mutation capabilities; I am not claiming they cannot manually manufacture inconsistent state. I found no documented supported producer or shipped migration contract for the state alleged here. A concrete such path would change this disposition. The ephemeral-restoration rank-up is skipped for that reason; pinned dependency inspection is complete. Durable original-source forks, including repeated creation and continuation after a Gateway/app-server restart, also passed live. Separately, CI identified a type-only barrel cycle and stale generated prompt fixtures. Those are being corrected; this comment is not a claim that the PR is ready to merge before CI is green. |
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.
754cfd5 to
e91f79a
Compare
|
Land-ready at Exact-head CI run 33230038980, attempt 1 completed successfully; The body contains the full command list and inspected before/after recordings. Local proof includes the successful full build, 687 earlier integrated tests, 193 subsequent native/UI tests, 95 naming/import/adoption tests, 55 CI-correction regressions, and 83 tests for the required main integration; these are overlapping runs, not unique-test totals. Real isolated UI/provider proof covers both incognito runtimes, retained-pane response ordering, nested fork tasks, repeated named native forks, and continuation after Gateway/app-server restart. The final owned corrections are type-only/golden artifacts, while native code is unchanged across rebase. Representative final integration commands: node scripts/run-vitest.mjs src/config/sessions/session-accessor.parent-fork.test.ts src/auto-reply/reply/session-fork.test.ts src/auto-reply/reply/session-parent-fork-prepare.test.ts src/sessions/model-overrides.test.ts src/agents/subagents/spawn/subagent-spawn-gateway.test.ts src/agents/subagents/spawn/subagent-spawn.fork-cleanup.test.tsnode scripts/run-vitest.mjs src/gateway/server.sessions.create.test.ts -t 'fork|model-selection-locked'node scripts/run-vitest.mjs src/gateway/server.sessions.create.test.ts -t 'retains the 100K fallback|clamps configured capacity'node --import ./scripts/tsx.mjs scripts/generate-prompt-snapshots.ts --checknode --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.tsKnown limits and discarded attempts remain explicit in the body. Canonical native descendant initialization is not silently enabled; no new schema/config/protocol/dependency or startup-budget change is included. Production is net +13 after removing duplicate context, cleanup, and type structure. Proceeding through |
|
Merged via squash.
|
…nclaw#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
Closes #131954 — message-level incognito forks returned an unreadable child.
What Problem This Solves
Fixes an issue where users choosing Fork from here could remain in the parent without an error when the parent was incognito. The same fork-lifecycle audit found delayed results overwriting a newer session selection/draft, failed forked subagents leaving copied history behind, and native Codex forks rejecting unchanged text or losing their source connection.
Live verification also exposed a named-thread failure: Codex correctly inherited the source name, but the importer reused it as a unique OpenClaw label already owned by the parent. This PR fixes that collision without renaming native threads or weakening label uniqueness.
Why This Change Was Made
Forking now carries the facts actually committed by its owners—storage class, verified transcript boundary, current mutation authority, prepared child generation, and effective context—instead of reconstructing them from requested options or stale state. Native source forks use the existing supervised materializer to apply real tools/instructions; failure compensation preserves successor ownership and tracks native artifacts even when a tracking write throws.
The repair removes duplicate context branches, a separate CAS-cleanup loop/error marker, an unreachable linked-native-incognito specialization, and an unused prompt parameter. No SQLite schema, configuration option, dependency, protocol-version, or startup-budget changes.
User Impact
Incognito children open, retain the correct prefix, and remain in memory. Old fork responses cannot steal focus or replace a newer draft. Failed child creation cleans up only its own generation. Local transcript copies respect harness locks and revalidate captured mutation authority at commit. Spawn results expose actual
context, and nested children follow their current assignment rather than an inherited task envelope. Native catalog user prompts, verified source cut points, secondary-home routing, and native model ownership are preserved.Explicit limitation: messages newly added to an adopted Codex Chat's canonical thread are not yet supported as descendant fork points. Native model history can contain injected messages absent from projected turns; reconstructing a child from that view would lose history. Correct support requires a separately accepted child-initialization/subscription/readiness/cleanup lifecycle. This PR preserves original-source forks and documents the boundary rather than adding unapproved persistent state or claiming that resume applied configuration. Duplicate names when adopting distinct native sources remain a separate naming-policy follow-up; existing adoption behavior is unchanged.
Evidence
Implementation and review were AI-assisted. I inspected the owner/caller/sibling paths and the pinned Codex
rust-v0.150.1source (90854393966b21e9ebfd21b122334eb09a20c93d), including exclusivebeforeTurnId, history projection/injection, fork configuration/subscriptions, and inherited thread names. Independent Codex review found two cleanup leaks; both received failing regressions and owner-level fixes. The complete repair and subsequent naming follow-up reviews are clean, with no actionable P0–P2 findings.Current candidate:
e91f79ae416db8b498edba3d5bfaf7f90d4ceafe, based on inspected main710a38588f8b9ffe88c0cb0b883967009c8c725f. Full-build and live-runtime proof ran atb2877cda37cdc9e76e95e916aa01657747f47acc. Subsequent corrections are a type-only import, generated prompt fixtures, and duplicate attachment-type removal. An actual documentation conflict required the latest rebase; native plugin code is unchanged across it. The combined main/repair owner paths received the additional focused verification below.context: "fork"; grandchild's task omits the remembered word, but its own response isapricot LEAF_TASK_COMPLETE. Verified the child tool call/result and grandchild transcript, not only the root's claim.label already in use; both pass afterward. Six import/fork/adoption suites: 95 passed. The test runtime explicitly models label uniqueness; actual SDK creation is proven by the live UI flow.pnpm buildpassed in 30m 19.4s. Startup JS: 344,957 B against 345,947 B enforcement limit.e91f79ae416db8b498edba3d5bfaf7f90d4ceafe;openclaw/ci-gateis green.CI follow-up: the first exact-head run found a type-only sessions-barrel cycle and stale generated prompt artifacts. The import now points to the same defining type module; its emitted JavaScript is byte-identical. The prompt artifacts were regenerated from the corrected source guidance, without weakening assertions or budgets. Both cycle checks, the snapshot check, and 55 focused model/storage/fork/prompt tests passed; independent review of this follow-up is clean.
The required rebase preserves main's model-aware operator fork capacity, the fixed 100K automatic/subagent fallback, and the newly captured Gateway resolver. 83 additional focused tests passed across capacity selection/clamping/fallback, same/cross-store parent forks, locks, last-completed cuts, rejecting resolver ownership, and all prepared-child cleanup cases. All seven prompt artifacts remain current; the rebased Madge graph has zero cycles. The incoming resolver argument exposed a 701-line spawner; reusing its existing attachment-result type removed ten lines instead of weakening the guard. The integration review is clean. One local operator-suite setup timeout produced a secondary teardown error; its unchanged retry passed, and the test-resource cleanup problem is recorded separately.
The native-incognito review finding and both rank-up moves are addressed in the source-backed maintainer disposition. Ordinary Codex-backed incognito sessions use the local fork path; supported native-catalog adoptions are durable. No supported producer reaches the alleged initial native-incognito write, and pinned Codex rejects the required turn-history read for genuine ephemeral threads. The removed direct mock did not represent the Gateway/creator contract.
The earlier build correctly failed on a pre-existing startup-size overage: the candidate was 227 B over, while the same pinned main was 235 B over. We waited for and integrated the canonical startup import fix, rather than raising a budget. Disk-exhaustion runs and initial mis-synchronized browser attempts were discarded as evidence; the results above are from completed healthy runs.
The additional Codex package-project typecheck also passed after the repository's required boundary-artifact preparation. A direct post-build invocation initially failed on duplicate declaration identities and a local-only test export because it omitted that preparation; no source changes, casts, or new SDK exports were needed. The unprepared invocation is recorded as a failed diagnostic, not a product regression or a passing check.
Inspected before/after screenshots and live recordings
All content is synthetic test data. Screenshots and recordings were inspected before upload. Comparisons show before on the left, after on the right.
Incognito: inaccessible child → correct prefix and restored draft
after-incognito-flow.webm
Retained pane: late response steals selection/draft → newer source presentation preserved
after-presentation-flow.webm
Named native source: label collision → independently continued child
after-native-flow.webm
Same native child after Gateway/app-server restart
Real nested fork completion
Focused final commands
Rebase integration commands:
node scripts/run-vitest.mjs src/agents/context.test.ts src/agents/subagents/registry/subagent-gateway-context-binding.test.ts src/gateway/server-plugin-in-process-dispatch.authorization.test.ts -t 'can exclude unscoped cache entries|prefers per-model contextTokens|keeps configured contextTokens|prefers verified provider discovery|keeps verified provider discovery|keeps configured native windows|caps prepared runtime tokens|subagent Gateway context binding|Gateway binding'node scripts/run-vitest.mjs src/gateway/server.sessions.create.test.ts -t 'fork|model-selection-locked'node scripts/run-vitest.mjs src/gateway/server.sessions.create.test.ts -t 'retains the 100K fallback|clamps configured capacity'Live browser drivers used an isolated state directory, workspace, and non-operator port, with real OpenAI/Codex turns. Only the retained-pane race delays a genuine WebSocket response. Assertions—not sleeps or forced clicks—drive the scenarios. No operator Gateway or saved operator state was modified.
Production LOC: +357/−344, net +13. Tests/support: +2671/−394; generated prompt fixtures: +28/−28; docs: +34/−21. The small production increase carries authoritative cleanup identity/effective context, commit-time checks, and explicit naming ownership; cleanup consolidation itself is net +1, and attachment-type deduplication removes another ten lines. Test totals include fixture moves/splits as well as new regression coverage.
Provenance, without claiming first release exposure: the key builder comes from message-level forks; the native binding/import naming path comes from upstream Codex forks, both authored and merged by
steipete. Provisional cleanup identity comes from deterministic subagent recovery, authored bysteipeteand merged byvincentkoc.