Repository navigation
fix(sessions): resolve relative session stores against the state dir, not the working directory - #182444
Conversation
Resolve relative session.store selectors independently of service cwd. Back up and verify Doctor recovery of prior physical stores before retiring registrations, and deduplicate aliases in write admission. Preserve history, sharing, delivery receipts, and recovery originals; refuse unresolved data-at-risk cases. Fixes #181660. Thanks @erickj92 and @kqtxmaster-boop for the diagnosis and reproduction.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6954a1bf91
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| key = `agent:${logicalAgentId}:relative-store-recovery-${sha256Hex(`${source.path}\n${sourceClaim.key}`).slice(0, 24)}`; | ||
| canonical = await prepareCanonical(key); |
There was a problem hiding this comment.
Remap child lineage when recovering a conflicting parent
When an old-store parent conflicts with a canonical session and has a distinct session ID, this branch assigns the old parent a recovery key, but its children are copied with their original parentSessionKey/spawnedBy references. copySessionClaimForRepair writes fresh.entry unchanged, and its generation rehoming only maps references to the individual claim being copied. Consequently, readSessionRowParents in session-row-projection-record.ts attaches those children to the unrelated canonical parent instead of the recovered parent. Doctor then records completion and retires the source registration with that incorrect lineage. Plan the source-to-destination key mapping before copying and apply it to retained parent references as well as session keys.
Useful? React with 👍 / 👎.
|
Codex review: needs real behavior proof before merge. What this changesResolve relative session stores against the active state directory and recover stores created under the previous working-directory interpretation. Example: HOME=/home/alex, OPENCLAW_STATE_DIR=/home/alex/.openclaw, cwd=/home/alex, and session.store=agents/{agentId}/sessions/sessions.json.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 4 items remain Keep open: this maintainer-owned PR addresses the confirmed split-store bug, but recovery can attach children to the wrong parent. Priority: P0 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe session resolver translates configured selectors into database locations; Doctor inventories and copies old stores, while writer admission coordinates access to physical databases. flowchart TD
A[Session configuration] --> B[State-relative resolver]
B --> C[Canonical session database]
D[Old registered stores] --> E[Doctor recovery]
E --> C
C --> F[Gateway session reads]
Technical reviewBest possible solution: Keep the state-relative resolver and existing repair owners, preserve lineage through a complete recovery-key mapping, and provide affected browser users a visible Doctor recovery action. Do we have a high-confidence way to reproduce the issue? The reporter's selector and admission trace establish the split-store path, and source inspection establishes the recovery-lineage defect; no target code was executed during this review. Is this the best way to solve the issue? Centralizing path resolution and reusing the existing backed-up copy owners is appropriate, but recovery must plan all destination keys before copying references between sessions. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b27c88e0cac9. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: shipped entry point. SecurityNeeds attention: Relocated membership needs final history-disclosure proof before this security boundary is cleared. EvidenceSecurity concerns:
What I checked:
Likely related people:
PR surfaceSource +764, Tests +557, Docs +5. Total +1326 across 26 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 24, 2026, 5:05 AM ET / 09:05 UTC. |
Keep the completion fingerprint that prevents deleted conversations from being restored from retained source databases. Audit its bounded noncredential key and move the reviewed artifact edge to the extracted claim-copy owner. Classify only the traced offline copy operations, preserving rejection of unreviewed callers, extra writes, and unrelated runtime SQL. No baseline or runtime behavior changes.
… not the working directory (openclaw#182444) A relative session.store resolved against process.cwd, so a systemd unit without WorkingDirectory (cwd=$HOME) created a second physical agent database per agent, and the second Control UI turn's read batch then spanned both and was refused. Relative stores now anchor to the state dir. Doctor backs up stores created by the old cwd behavior, merges them into the canonical agent databases (originals preserved, conflicting session generations refused), verifies preservation, records a completion fingerprint so retained originals cannot resurrect later-deleted conversations, and only then retires their registrations. Write admission deduplicates physical aliases of one database while still refusing genuinely different ones. Fixes openclaw#181660. Thanks @erickj92 for the root cause and @kqtxmaster-boop.
… not the working directory (#182444) A relative session.store resolved against process.cwd, so a systemd unit without WorkingDirectory (cwd=$HOME) created a second physical agent database per agent, and the second Control UI turn's read batch then spanned both and was refused. Relative stores now anchor to the state dir. Doctor backs up stores created by the old cwd behavior, merges them into the canonical agent databases (originals preserved, conflicting session generations refused), verifies preservation, records a completion fingerprint so retained originals cannot resurrect later-deleted conversations, and only then retires their registrations. Write admission deduplicates physical aliases of one database while still refusing genuinely different ones. Fixes #181660. Thanks @erickj92 for the root cause and @kqtxmaster-boop. Release adaptation: the stable line has no scripts/lib/personal-credential-writer-guard.mts, src/agents/auth-profiles/file-state.test.ts, legacy-main-session-migration-restore.ts or the sqlite-database-admission identity cache. Dropped the guard allowlist entry and its test, imported restoreColdSessionClaims from legacy-main-session-migration-claims.ts, and keyed write-admission alias dedupe on readDatabasePathIdentitySync only. Kept the stable reentrancy check (the ported alias test passes reentrant=true). Ported the Doctor relative-store repair into the stable preflight after plugin migrations (no heartbeat repair step on this line). Kept the stable session-event-permissions fake timers and the database-worker ratchet test (main's new case depends on main-only helpers); dropped the unrelated agent-create test tweak. runtime-status uses resolveSessionStorePathCore in both stable call sites. (cherry picked from commit a64daf7)
Adapt 12 audited database fixes and eight large-conversation reader groups. Stream archive materialization with bounded buffers, preserving full history. Original sources: #187496 8b38db5 #181554 55477ab #179057 ff5b71a #180414 2f2dc1e #182444 a64daf7 #183410 fa9ca88 #175091 ca07b1b #179089 a6f4826 #182446 84806d0 #157151 5cc6f4a #174249 a09c26b #172028 70856fb #172970 dd9cdee #177937 1bb6763 #182091 38bf89c #190182 33e7baf #189284 3d4fc94 #188450 3c8bd4d #188483 b195f61 #190690 c51d733 Proof: 454 distinct tests in initial lane; 11 relevant repair tests. Final integrated lint/type/format pass pending. Co-authored-by: RomneyDa <[email protected]>
Adapt approved source fixes to the September extended-stable owners. Preserve original APIs and custody; include review-driven regressions. Backport-of: a64daf7 — Peter Steinberger — fix(sessions): resolve relative session stores against the state dir, not the working directory (#182444) Validation: independent source review, exact patch/file identity and git diff --check. Runtime tests, types and builds deferred to authorized remote CI; not run locally. Co-authored-by: RomneyDa <[email protected]>
* fix(gateway): publish node reapproval with committed pairing facts Adapt main commit 94f180d to the extended-stable worker dispatcher, retaining cleanup admission and stale-session fencing. Co-authored-by: RomneyDa <[email protected]> * test(gateway): clarify CLI announcement tool-only phase Keep exact token, barrier, and completion ordering assertions intact while explicitly excluding narration before the barrier. Co-authored-by: RomneyDa <[email protected]> * style(gateway): format node reapproval regression Reflow the spy chain reported by hosted CI; no behavioral changes. Co-authored-by: RomneyDa <[email protected]> * test(secrets): decouple Telegram fixture from plugin discovery Import the real public Telegram secret collector directly so collection does not depend on Gateway discovery environment. Exercise collection with bundled plugins disabled while retaining existing token assertions. Gateway timeout attribution remains unresolved; no production behavior or timeout changes. Co-authored-by: RomneyDa <[email protected]> * test(secrets): load Telegram fixture through public resolver Replace the static extension import rejected by core type and boundary checks with the existing test public-artifact resolver. Keep the real collector in the Vitest module graph and preserve the disabled-discovery regression. Independent source review accepted; local test, typecheck, build, install, and performance execution remain excluded by operator instruction. Hosted CI must validate the correction. Co-authored-by: RomneyDa <[email protected]> * style(secrets): format Telegram fixture import Co-authored-by: RomneyDa <[email protected]> * fix(ui): honor recovery holds before initial chat history Keep drafting available while the existing send owner holds recovery or a retained initial turn. Restore Send when that hold clears without waiting for initial history or submitting the draft automatically. Add renderer regressions for both holds and clarify the pre-history outbox contract. Controlled real-Gateway red/green evidence: 42523861169 / 42526889715. Diagnostic branch is not merged. Co-authored-by: RomneyDa <[email protected]> * fix(ui): preserve startup status presentation while holding send Restore the existing connected startup/history status suppression without reopening Send admission. Extend both durable hold regressions to reject the duplicate composer status band. Existing cloud E2E assertions remain unchanged. Co-authored-by: RomneyDa <[email protected]> * fix(release): backport installer, service, path and telemetry repairs Adapt approved source fixes to the September extended-stable owners. Preserve original APIs and custody; include review-driven regressions. Backport-of: eb5d0cb — Javier MV — fix(install): keep the installed runtime private under umask 0002 (#186782) Backport-of: b079019 — Sukhdeep — fix(daemon): Gateway repair stops the Gateway and fails when macOS denies the Trash (#189321) Backport-of: 558e2f3 — YangManBOBO — fix(cli): compare gateway state dirs case-insensitively on Windows (#185917) Backport-of: b7ce1c3 — Peter Steinberger — test(windows): keep ordinary CLI coverage in one partition Backport-of: ba75cf7 — Juan Buhagiar Duijst — fix(diagnostics-otel): gateway stalls after model calls on large sessions with content capture on (#186666) Validation: independent source review, exact patch/file identity and git diff --check. Runtime tests, types and builds deferred to authorized remote CI; not run locally. Co-authored-by: RomneyDa <[email protected]> * fix(release): preserve notes and harden messaging and exec approval Adapt approved source fixes to the September extended-stable owners. Preserve original APIs and custody; include review-driven regressions. Backport-of: 0a171b4 — Leizhen Zhang — fix(auto-reply): long punctuation runs stall abort-trigger detection (#184433) Backport-of: 49600b5 — Long Jin — fix(memory): preserve inline notes during MEMORY.md compaction (#164089) Backport-of: 982f3b1 — RoboClaw — fix(imessage): report Automation failures after Gateway updates (#186117) Backport-of: 3f7ee38 — art22s — fix: require approval for dynamic shell predicates (#187884) Validation: independent source review, exact patch/file identity and git diff --check. Runtime tests, types and builds deferred to authorized remote CI; not run locally. Co-authored-by: RomneyDa <[email protected]> * fix(release): retain sandbox, recovery lease and Matrix boundaries Adapt approved source fixes to the September extended-stable owners. Preserve original APIs and custody; include review-driven regressions. Backport-of: a19f1bf — Agustin Rivera — fix(agents): fail closed when sandboxed spawned children resolve CLI-backed models (#178742) Backport-of: c9f3f82 — Peter Steinberger — fix(agents): release restart-recovery fences for killed runs (#181992) Backport-of: dfb6454 — Leizhen Zhang — fix(matrix): crafted formatted_body stalls the Gateway in the mention check (#184432) Validation: independent source review, exact patch/file identity and git diff --check. Runtime tests, types and builds deferred to authorized remote CI; not run locally. Co-authored-by: RomneyDa <[email protected]> * fix(config): preserve last-good state through writes and rollback Adapt approved source fixes to the September extended-stable owners. Preserve original APIs and custody; include review-driven regressions. Backport-of: 99418fc — weiqinl — fix(config): keep last-known-good when the observer flags the config as truncated (#152565) Validation: independent source review, exact patch/file identity and git diff --check. Runtime tests, types and builds deferred to authorized remote CI; not run locally. Co-authored-by: RomneyDa <[email protected]> * fix(sessions): preserve history when relocating relative stores Adapt approved source fixes to the September extended-stable owners. Preserve original APIs and custody; include review-driven regressions. Backport-of: a64daf7 — Peter Steinberger — fix(sessions): resolve relative session stores against the state dir, not the working directory (#182444) Validation: independent source review, exact patch/file identity and git diff --check. Runtime tests, types and builds deferred to authorized remote CI; not run locally. Co-authored-by: RomneyDa <[email protected]> * fix(release): repair September backport type contracts Split terminal recovery actions into distinct discriminants without changing behavior. Use the branch-native Doctor import signature, checking held maintenance authority before and after the awaited import. Validation: independent exact-diff source review, formatter and git diff --check passed. Local tests, typechecks and builds not run per operator restriction; fresh exact-head remote qualification required. Repairs CI 42643973970 attempt 1. Co-authored-by: RomneyDa <[email protected]> * fix(release): align backport regressions with September contracts Preserve uncertain config-write outcomes while correcting branch-native fixture APIs and lint errors found by hosted CI. Co-authored-by: RomneyDa <[email protected]> * test(ci): separate Windows capacity from growing inventory Keep package coverage and the five-job limit independent of a historical timing snapshot. Preserve the rounded capacity boundary and exercise the documented bounded-growth fallback with fixed estimates. Co-authored-by: RomneyDa <[email protected]> * test(node-host): keep launcher cleanup with its invoke owner Wait for a positive launcher PID before probing liveness, and cancel through the existing invocation owner on every exit path. Never send SIGKILL to file-derived PID zero. Co-authored-by: RomneyDa <[email protected]> * test(release): observe owned Gateway reservation cleanup Verify the real reservation closes before relaunch instead of rebinding an already-released port that another socket can acquire. Preserve all seven packaged startup recovery scenarios. Co-authored-by: RomneyDa <[email protected]> * test(release): capture native compiler busy-executable evidence Preserve real API execution and errors while recording failure-only executable inode and writable descriptor metadata. Add a Linux kernel-path diagnostic regression; no retry or copy change. Co-authored-by: RomneyDa <[email protected]> * test(release): repair stability regression fixtures Register CLI admission metadata through the runtime registry, observe the rollback health baseline, and preserve exact SQLite byte expectations. Co-authored-by: RomneyDa <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: RomneyDa <[email protected]>
What Problem This Solves
Fixes #181660: a relative
session.storecan select a second database when a service starts from$HOME, breaking session reads during subsequent chat turns.User Impact
Relative paths now consistently resolve against the active state directory, including the reporter's
agents/{agentId}/sessions/sessions.jsonconfiguration. Absolute and home-relative paths retain their explicit locations. Stop the Gateway and runopenclaw doctor --fixto recover stores created by the old working-directory resolution before restarting.Doctor backs up both stores and shared state, preserves sessions, history, sharing, and completed delivery receipts, verifies each copy, then retires the old registration. It retains the original database and backups. A completion receipt prevents later runs from resurrecting conversations deleted after recovery.
Repair refuses conflicting history for the same session ID or membership, pending durable deliveries/context-engine work, unexpired Goal receipts, retained transcript archives without a proven transfer, and uncopied rehearsal sources. Those cases need the reported work settled or explicit recovery at the original store; neither original is discarded.
Why This Change Was Made
The path resolver used the process working directory. A systemd service without
WorkingDirectorycould therefore register both~/agents/...and the canonical state-directory database. The resolver now owns one state-relative interpretation. The reference did not promise a cwd or config-directory base; the active state directory matches the default store, profiles, and state overrides. The existing write-admission owner separately deduplicates physical database aliases before enforcing single-store reentry, while continuing to reject genuinely different databases and worker-owned transactions. This leaves #182090's diagnostic improvement independent.Doctor's existing migration and session-copy owners handle recovery. Doctor shares the existing legacy-main claim copier and canonical delivery copier. Prior registered locators survive the early inventory/pruning stage until the backed-up repair finishes. No schema, dependency, or configuration option is added.
Thanks @erickj92 and @kqtxmaster-boop for the diagnosis and reproduction.
Evidence
CI repair: reviewed offline ownership
Doctor's machine-state write is a required completion fingerprint, not registration or credential persistence. The bounded
sessions.relative-store.v1.<path hash>key prevents retained originals from resurrecting conversations deleted after recovery. The registration owner has no equivalent durable completion receipt. The exact writer entry now documents this namespace and exclusive Doctor custody.The reviewed artifact edge moved from retired
copyClaimCrossStoretocopySessionClaimForRepair; the former permission was removed. It continues using the existingcopySessionNodeArtifactsForRepairowner inside the admitted transaction after claim and sharing checks. The broader canonical-repair operation also copies generations and replaces selected-winner membership, so routing through it would alter relocation semantics.Once the writer errors were cleared, the requested full ratchet exposed 22 calls in the extracted modules that had lost their previous migration/Doctor classification. Three exact operation classifications retain that offline ownership with traced caller evidence. Unrelated operations in both files remain T1. No baseline, blanket file exemption, runtime behavior, or credential authority changed.
All six new regression cases failed before their respective fixes and passed afterward. Negative controls reject other callers, repeated writer edges, the retired caller, and unrelated runtime SQL. Final tooling replay: 212 tests in four files passed; all 12 Doctor recovery tests also passed (224 distinct cases across five files). Tooling typecheck, typed lint, formatting, whitespace, and native commit hooks passed. Autoreview failed authentication and produced no verdict.
One inspection of the failed UI logs and fixtures found no causal path from this PR. All three use a mocked Gateway and do not execute the changed resolver, Doctor migration, or database admission. Failures were route settlement after navigation (
chat-active-turn-recovery), activity-event count (home-attention), and missing Undo after navigation (session-management.archive-undo). They remain separate defects; no timeout, assertion, or retry changed. PostgreSQL conformance 3/3 is the inherited worker-runtime asset problem tracked by #182464 (open in the inspected snapshot).CI repair head:
78bf03b653ad85fbb1fa942e73335c6c8bcc6f35. Repair delta: tooling +28/-1; tests +80/-0.sessions.create, then twochat.sendturns returnedTURN_1_OKandTURN_2_OK. The live replay at1304584e103etook 23.190s and 1.726s; Gateway readiness took 72.007s including cold source startup (phase split unprofiled). Only the canonical database existed; no admission or observer errors. The base produced the duplicate-database observer error, although both RPCs acknowledged; the reporter's precise second-RPC rejection was not reproduced.unicorn-magicplugin-export and prompt-cache warnings, plus a harness-shutdown reply-drain warning. The native agent runtime completed both real model calls; plugin loading and warning-free shutdown are not claimed fixed.1304584e103epassed in 607.5s; the integrated runtime build passed in 128.76s. A moved cold-claim export found during integration was corrected by importing its current owner. Full SQLite inventory was omitted under the approved local gate time budget; PR CI remains the broad check.[email protected]package in isolated state, used its actual Gateway to create canonical and old cwd-relative histories, then ran current Doctor and booted the current Gateway. Both histories survived in the canonical physical database, both originals had owner-backed recovery captures, and only the canonical registry entry remained after the new boot. The proof used realsessions.create,chat.inject, andchat.historyRPCs without provider credentials. After integration, Doctor again merged and physically verified both histories. The first candidate boot hit its deadline during a dirty-tree source rebuild, before Gateway startup. After committing the same source and building cleanly, the proof resumed that exact upgraded state: boot/history/physical-registry checks passed in 69.27s. A startup maintenance inventory-incomplete skip was logged; no warning-free claim is made.6954a1bf910bpassed all 4 selected files / 50 tests on Node (paths 7, admission 25, Doctor 12, sandbox 6). The wrapper completed in 331.39s, including 212.5s of E2E runtime build preparation and 25.373s of shared worker compilation. This reuses main's sandbox fixture unchanged.1304584e103e: 19 files, 386 tests passed, including all 12 Doctor regressions, the new interrupted-output and terminal-recovery consumers, and prefix stability. A separately attempted new-main cron consumer timed out inownat 128.828s, then passedforeignat 95.173s; the run was interrupted before repeating the stall. Its fixture has no relative selector and model execution is mocked. Creator/config/tool/job-admission costs need phase profiling; no fix is claimed.Slow-test evidence and performance follow-ups
src/gateway/server-methods/agents-delete.integration.test.ts, “deletes real agent storage and permits recreation after active,” 57.527s. It combines a real Gateway, native bindings, memory-discovery settlement, repeated deletion/recreation, and two late-write fencing cycles. Test-cost reduction is a separate follow-up; no timeout, retry, or assertion was relaxed.src/gateway/server-methods/cron.inference-binding.test.ts, 209.065s aggregate test time. Its per-case fixture seeds auth state and repeatedly closes/reopens SQLite-backed cron services to prove persistence; fixture-cost reduction is a separate follow-up.src/gateway/server.agent-artifact-apis.test.ts, combined agent/environment/artifact RPC flow, 36.166s. It starts a real Gateway and performs three explicit restarts to check persistence after create, artifact writes, and deletion. No restart assertions were removed.src/agents/main-session-recovery/main-session-restart-recovery.test.ts, 265.764s aggregate test time. Its 5,712-line suite creates and cleans fresh session/transcript state per case; fixture-cost work is a separate follow-up.The final Doctor file took 289.076s of test time; phase evidence is described above. E2E preparation took 12m28.4s and shared source preparation took a separate 101.172s before test bodies. Shared-host load was high, but its contribution is not quantified. No timeout, retry, skip, assertion, or baseline was relaxed.
Reproduction commands and output
Every test command used an isolated
HOMEandOPENCLAW_STATE_DIRbeneath this worktree. Node test commands setOPENCLAW_VITEST_RUNTIME=node.The live harness exported isolated state before starting Node, then set cwd to its fresh home before importing the production Gateway. The provider credential was supplied through the approved secret owner and never logged.
The interrupted-manifest report remains a named follow-up: investigate the actual
startup-migration-*.jsonfiles and startup trace. Current source treats these as backup receipts. A two-startup production-path probe with an unfinished receipt and a removed source did not recreate either the database or registry entry, so this PR does not change receipt retirement speculatively.Public SDK impact inventory observed 53 package identities calling the existing resolver surfaces; this is an observed-consumer count, not an affected-package count. Sampled calls use configured selectors or defaults and do not establish a dependency on process cwd. Inventory coverage has 407 incomplete/missing package scans and 621 unresolved references; bundled usage was checked in source, without a complete bundled inventory. Signatures remain unchanged.
The live replay exercised exactly the source patch committed as
1304584e103eafc777cb406731a5f0d244a36803(verified patch SHA-256). GitHub then reported a conflict with main's newly landed sandbox fixture repair. Integration commit6954a1bf910b2bb6996ffbd06c611fe6bc2f7692reuses that fixture unchanged. All 14 runtime production files in this PR are byte-identical to the live-tested head; unrelated newly merged main changes were not re-proven by the earlier live run. Main's media fixture repair and the current cold-claim restoration owner are also retained.Diff size: production/tooling +1,182/-391 (16 files); tests +645/-8 (12 files); docs +6/-1 (2 files). Existing claim/delivery-copy implementations were moved into shared repair owners; the old implementations were removed.