Skip to content

fix(sessions): resolve relative session stores against the state dir, not the working directory - #182444

Merged
steipete merged 6 commits into
mainfrom
upd/upd-l1884
Oct 24, 2026
Merged

steipete merged 6 commits into
mainfrom
upd/upd-l1884

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #181660: a relative session.store can 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.json configuration. Absolute and home-relative paths retain their explicit locations. Stop the Gateway and run openclaw doctor --fix to 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 WorkingDirectory could 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 copyClaimCrossStore to copySessionClaimForRepair; the former permission was removed. It continues using the existing copySessionNodeArtifactsForRepair owner 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.

node --max-old-space-size=4096 --import ./scripts/tsx.mjs scripts/check-database-worker-ratchet.mts --base origin/main
# SQLite T1 live calls: 170 -> 170; T1-compat deprecated-only calls: 15 -> 15.
# SQLite worker ratchet OK: no T1 call-count growth against 00c611d4d4cb18b8b323cf350dac59178e01472f.

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.

  • Node 26.12.1 regressions fail on the base: the exact relative config resolves under the temporary home; real Doctor misses the old session; symlink/hardlink aliases trip the admission guard. They pass with this change.
  • All 12 Doctor recovery tests pass on Node: real Doctor discovery, non-home prior working directory, canonical-history and membership conflicts, idempotent retirement, delivery receipts, and data-at-risk refusals. The pre-integration run took 50.686s; the later integrated run took 289.076s. Its four full-flow cases took 128.942/40.104/32.905/36.645s. Progress logs place at least 20s of the first and 10s of subsequent cases in legacy preflight, before relative repair; the remaining phase cost is unprofiled. Follow-up checks use the existing maintenance/repair owner instead of repeatedly booting full Doctor.
  • Live isolated dev Gateway with cwd equal to a temporary home and the exact reported config: actual Control UI identity, session/event subscriptions, sessions.create, then two chat.send turns returned TURN_1_OK and TURN_2_OK. The live replay at 1304584e103e took 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.
  • The live base and fixed runs both emitted inherited unicorn-magic plugin-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.
  • Core and 20 selected-test types, typed lint, formatting, whitespace, zero import cycles, and the line-cap ratchet passed. The clean-head full build at 1304584e103e passed 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.
  • Published-stable upgrade: installed the official [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 real sessions.create, chat.inject, and chat.history RPCs 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.
  • Before integration, admission tests had 23 passes; paths/sandbox/ACP had 55; canonical/legacy-copy/cold-read siblings had 41.
  • After resolving the GitHub conflict, the integrated head 6954a1bf910b passed 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.
  • Focused replay at 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 in own at 128.828s, then passed foreign at 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.
  • Consumer scope initially covered 802 direct/one-barrel importing files plus prefix stability. After integration, selection found 805 consumers; the three newly introduced files were attempted against current source: two passed, and the cron file has the unresolved partial outcome described above. Before main integration, 799 files had normal/focused outcomes; the four live-only files were then invoked with the live config and skipped five cases under their existing opt-ins. The disjoint broad batches recorded 12,751 passing, 12 failing, and 70 skipped cases; seven additional focused-file totals are not inferred. Those historical totals retain failures rather than rewrite them with replays. The placement, queued-media, watcher, and sandbox fixture failures received focused repair/reuse checks; three host custody cases remain inherited reds. Two fleet-preflight failures and one unchanged filesystem SDK compatibility case are inherited host custody failures: the unchanged backup policy rejects the external volume's group-writable, non-sticky ancestor, even though test directories are private. An isolated probe of the actual policy reproduced the refusal; all six policy/capture/fixture modules are byte-identical to the base. The direct capture case fails before Doctor; attributing the missing-original assertion in the other case to the same failed capture is a source-order inference. No host permissions or custody guard were changed.
  • Main landed its queued-reply fixture initialization/reset repair during this lane; the PR reuses it through integration instead of retaining a competing fix. The worker auth fixture now disables the hosted macOS watcher at directory admission while preserving the no-row-child assertions. Main subsequently landed its Docker endpoint/daemon/container fixture repair. Conflict integration reuses that file unchanged, removing this lane's equivalent fixture repair from the PR. State-relative caller fixtures assert the new base explicitly. An agent-creation failure was reproduced on the untouched base: a workspace-write fixture disabled native filesystem support before cold shared-state creation; initializing its real shared store before that narrow fault injection preserves its assertions.
  • Fixed a nearby watcher-test cost: advancing fake wall-clock time persisted future mailbox timestamps, forcing real waits after the clock was restored. Only timer APIs are now faked. The 24-case file passed in 67.146s versus 172.618s earlier; the two targeted watcher cases fell from 27.331/30.253s to 9.009/5.156s. Worker concurrency/cache also changed, so the entire file reduction is not attributed solely to this fix.
  • Codex review could not authenticate in the isolated review environment; no review verdict is claimed.
Slow-test evidence and performance follow-ups
  • Existing slow integration case: 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.
  • Existing slow file: 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.
  • Existing slow integration case: 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.
  • Existing slow file: 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.
  • Existing credential-update case: predecessor identity key material, 62.133s; file aggregate 130.878s. It performs real capture, exclusive Doctor migration/repair, receipt checks, rollback, and DB closure. The same-shaped metadata case took 16.167s; the 62s phase split is not measured.
  • Existing native model ownership case: guarded host-auth input, 32.781s. It performs fresh session/auth setup, asynchronous tool-authority fingerprinting, runtime preparation, and steering checks; model execution is stubbed and makes no network call. First-use policy/worker cost is plausible but unprofiled.
  • Existing agent-command file: 136.774s across 59 passing cases, median 2.363s and maximum 5.301s. Per-case fresh HOME/config/store setup and SQLite/queue cleanup preserve custody; inference is mocked. Fixture reuse needs separate work with those boundaries retained.
  • Existing plugin-deferral file: 131.356s across 14 passing cases, maximum 26.953s. Repeated real Doctor/plugin-convergence flows and fresh state fixtures account for the distributed work; the longest case intentionally runs six Doctor passes across incomplete and settled plugin states. No explicit sleep or polling loop was found.
  • Existing channel-progress E2E file: 16 passing cases, 338.324s; suppressed Slack announcements took 82.781s. Two explicit 31-second provider waits cross the real 30-second final-digest threshold (at least 62s); the remainder includes a real Gateway/channel/subagent flow and lifecycle polling. A faster observer-clock contract is a separate follow-up; these waits and delivery assertions remain unchanged.
  • Existing reply-agent E2E file: 163.711s over 230 cases, maximum 3.554s. The distributed cost is real session admission/SQLite setup and joined cleanup; model inference is mocked and imports are warmed.
  • Existing Workshop-learning E2E case: 39.618s (two-case file 68.049s). It performs ten foreground provider rounds, four background review rounds, real tool receipts and skill-file edits, then verifies persisted notice delivery and unchanged source history. No fixed sleep was found; the phase split remains unprofiled.
  • Final sandbox workspaceRoot case: 33.818s, with Docker responses mocked and workspace/state paths real. Phase costs remain unprofiled; assertions and deadlines were retained.

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 HOME and OPENCLAW_STATE_DIR beneath this worktree. Node test commands set OPENCLAW_VITEST_RUNTIME=node.

node scripts/run-vitest.mjs src/commands/doctor-relative-session-store.test.ts --maxWorkers=1
# 12 passed
node scripts/run-vitest.mjs src/state/openclaw-agent-write-admission.test.ts --maxWorkers=1
# 23 passed
node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/l1884/core.tsbuildinfo
node --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.ts
pnpm build
# passed on clean final head, 607.5 seconds
node .artifacts/stable-upgrade/proof.mjs
# STABLE_WROTE_SPLIT_STORES: 2026.10.6; Doctor verified both histories
node .artifacts/stable-upgrade/resume-integrated-proof.mjs
# resumed the same repaired state after a clean build
# CANONICAL_PHYSICAL_STATE_VERIFIED: after-doctor, after-candidate-boot
# STABLE_UPGRADE_PROOF_SUCCESS: 2 histories, 2 owner-backed originals

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.

PROOF_PHASE=fixed-ui PROOF_SEED_CANONICAL=1 LIVE_PROVIDER=openai \
TSX_DISABLE_CACHE=1 TSX_TSCONFIG_PATH="$PWD/tsconfig.json" \
node --import tsx .artifacts/live-two-turn/proof.mts
# final TURN_1_OK; final TURN_2_OK
# canonical=true legacy=false; PROOF_SUCCESS_TWO_TURNS

The interrupted-manifest report remains a named follow-up: investigate the actual startup-migration-*.json files 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 commit 6954a1bf910b2bb6996ffbd06c611fe6bc2f7692 reuses 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.

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.
@clawsweeper

clawsweeper Bot commented Oct 24, 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 commands Command implementations docker Docker and sandbox tooling agents Agent runtime and tooling size: XL labels Oct 24, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the docker Docker and sandbox tooling label Oct 24, 2026
@steipete
steipete marked this pull request as ready for review October 24, 2026 08:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T09:38:05.949346Z b48f89c New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: b48f89ceaf95b2f1542fd74f15da7ea7858aea39
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/runtime-status.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +333 to +334
key = `agent:${logicalAgentId}:relative-store-recovery-${sha256Hex(`${source.path}\n${sourceClaim.key}`).slice(0, 24)}`;
canonical = await prepareCanonical(key);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Resolve 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.

  • Before: The main agent's configured store resolves under /home/alex/agents/main, alongside its state-directory database.
  • After: The selector resolves under /home/alex/.openclaw/agents/main, and Doctor can recover the old store with backups.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful maintainer-directed repair with substantial real-runtime and upgrade evidence, limited by an actionable lineage defect and unproven relocated sharing isolation.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Follow-up browser conversations can fail because a relative selector creates a second database for the same agent.
Reason: The reporter established the configuration trigger and workaround, and the maintainer explicitly approved state-relative resolution with backed-up recovery.

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
Reviewed head: 6954a1bf910b2bb6996ffbd06c611fe6bc2f7692

Before merge

  • Add real behavior proof - Authority-chain proof required: the supplied terminal output demonstrates real Gateway turns and stable-release recovery, but membership relocation still needs allowed and source-only forbidden clients exercised through chat.history, followed by revocation and denial before response publication; redact credentials and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Remap child lineage using the complete recovery-key mapping (P2) - If both stores contain agent:main:parent with distinct session IDs, the old parent receives a recovery key. An old-store child whose parentSessionKey or spawnedBy names agent:main:parent is then copied unchanged: copySessionClaimForRepair writes fresh.entry, and generation rehoming knows only the child key. readSessionRowParents consequently attaches the child to the unrelated canonical parent. Doctor nevertheless records completion and retires the source registration. Plan the source-to-destination key mapping before copying and apply it to entry and retained-generation parent references.
  • Resolve security concern: Verify authorization after membership relocation - Store relocation persists source membership under destination session keys. Stored-row assertions do not establish which client receives history after conflict recovery or revocation; no concrete unauthorized disclosure was demonstrated.
  • Resolve merge risk - Before merge, the PR owner must establish that relocated sharing grants keep source-only members out of the canonical conflicting session and that revoked membership remains ineffective at history publication.

Findings

  • [P2] Remap child lineage using the complete recovery-key mapping — src/commands/doctor-relative-session-store.ts:328-332
  • [medium] Verify authorization after membership relocation — src/config/sessions/session-claim-repair-copy.ts:239

Tests

  • Missing end-to-end proof: Supplied proof does not cover recovered parent-child lineage or post-recovery history disclosure to allowed, forbidden, and subsequently revoked members.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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:

  • [P2] Remap child lineage using the complete recovery-key mapping — src/commands/doctor-relative-session-store.ts:328-332
    If both stores contain agent:main:parent with distinct session IDs, the old parent receives a recovery key. An old-store child whose parentSessionKey or spawnedBy names agent:main:parent is then copied unchanged: copySessionClaimForRepair writes fresh.entry, and generation rehoming knows only the child key. readSessionRowParents consequently attaches the child to the unrelated canonical parent. Doctor nevertheless records completion and retires the source registration. Plan the source-to-destination key mapping before copying and apply it to entry and retained-generation parent references.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Verify recovered sharing isolation (recommended)
    The PR owner should exercise member, conflicting-session nonmember, and revoked-member history requests through the Gateway after recovery.
  2. Pause recovery landing
    Keep the PR open until the relocated sharing boundary is demonstrated.

Provenance checked

  • Relative selector resolution and sandbox callers changes intended behavior with a stated reason (c4d2684: The async reporting refactor captured cwd before yielding and retained source-lifetime checks; the original introduction of cwd-relative semantics remains unknown because older blobs are unavailable.)
  • Invocation-directory handling changes intended behavior with a stated reason (6830c82: The earlier change preserved invocation paths across package replacement; this PR deliberately removes invocation-directory dependence for configured relative session stores.)
  • Shared claim and delivery repair owners keeps the original intent (7bc4491: Doctor migration preserves retained generations and logical-session artifacts through shared copy owners; extraction retains that responsibility and removes the superseded implementations.)
  • Nested writer admission keeps the original intent (283d5e6: Admission prevents stale or worker-owned contexts from borrowing unsafe write access; the new alias deduplication retains rejection for distinct databases and worker reservations.)

Testing

Proof path: shipped entry point.

Security

Needs attention: Relocated membership needs final history-disclosure proof before this security boundary is cleared.

Evidence

Security concerns:

  • [medium] Verify authorization after membership relocation — src/config/sessions/session-claim-repair-copy.ts:239
    Store relocation persists source membership under destination session keys. Stored-row assertions do not establish which client receives history after conflict recovery or revocation; no concrete unauthorized disclosure was demonstrated.
    Confidence: 0.95

What I checked:

Likely related people:

  • Vincent Koc: Raw commit 932846b adds src/config/sessions/paths.ts:14 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: low; commits: 932846b521c0; files: src/config/sessions/paths.ts)

PR surface

Source +764, Tests +557, Docs +5. Total +1326 across 26 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 14 1154 390 +764
Tests 10 565 8 +557
Docs 2 6 1 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 1725 399 +1326

Review metrics

Metric Value Why it matters
Production versus test changes Production +1,154/-390; tests +565/-8. Growth primarily implements backed-up recovery and preservation checks; existing claim and delivery copiers move to shared owners with their old implementations removed.

Labels

Label changes:

  • add P0: The linked official-release report blocks ordinary follow-up browser conversations after an update and requires terminal or configuration recovery.
  • add merge-risk: 🚨 compatibility: The public resolveStorePath behavior changes for existing relative selectors; the maintainer explicitly adopts that change and supplies stable-upgrade recovery evidence.
  • add merge-risk: 🚨 session-state: Conflict recovery can persist child links to an unrelated canonical parent.
  • add merge-risk: 🚨 security-boundary: Recovery transfers durable sharing membership without supplied final-disclosure proof for nonmembers and revoked members.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P0: The linked official-release report blocks ordinary follow-up browser conversations after an update and requires terminal or configuration recovery.
  • merge-risk: 🚨 session-state: Conflict recovery can persist child links to an unrelated canonical parent.
  • merge-risk: 🚨 security-boundary: Recovery transfers durable sharing membership without supplied final-disclosure proof for nonmembers and revoked members.
  • merge-risk: 🚨 compatibility: The public resolveStorePath behavior changes for existing relative selectors; the maintainer explicitly adopts that change and supplies stable-upgrade recovery evidence.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Prove allowed and forbidden history responses after recovery, then revoke the allowed member and prove denial before history publication.

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.

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.
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 24, 2026
@steipete
steipete merged commit a64daf7 into main Oct 24, 2026
150 checks passed
@steipete
steipete deleted the upd/upd-l1884 branch October 24, 2026 10:02
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
… 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.
RomneyDa pushed a commit that referenced this pull request Oct 26, 2026
… 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)
tideclaw-bot added a commit that referenced this pull request Nov 4, 2026
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]>
RomneyDa added a commit that referenced this pull request Nov 9, 2026
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]>
RomneyDa added a commit that referenced this pull request Nov 9, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security-sensitive-changed size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Error: Session read batch cannot reenter an active SQLite writer admission

1 participant