Skip to content

fix: doctor memory merge can empty MEMORY.md when the merge write fails - #184858

Closed
syxscott wants to merge 4 commits into
openclaw:mainfrom
syxscott:fix/doctor-root-memory-atomic-merge
Closed

syxscott wants to merge 4 commits into
openclaw:mainfrom
syxscott:fix/doctor-root-memory-atomic-merge

Conversation

@syxscott

@syxscott syxscott commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: openclaw doctor's legacy root memory merge can leave MEMORY.md empty or torn when the merge write fails (crash, Ctrl-C, ENOSPC/EPERM mid-write), silently destroying the agent's durable memory.

The merge archived only the legacy memory.md before overwriting the canonical MEMORY.md with a truncate-in-place writeFile — the pre-merge canonical bytes existed nowhere else. The truncated file is also what the doctor note reports as a completed repair when the error is caught upstream, so the loss is silent.

User Impact

User impact: a failed or interrupted doctor memory merge now leaves the live MEMORY.md byte-for-byte intact, and the pre-merge canonical content is preserved as MEMORY.md.pre-merge beside the existing legacy archive for recovery. The merge success note reports the new backup path.

The publication matches the existing memory writer (extensions/memory-core/src/dreaming-markdown.ts): replaceFileAtomic with preserveExistingMode, the workspace's actual directory mode passed back as dirMode (publication can no longer widen a private 0700 workspace to 0755), the permission-error copy fallback left disabled (its unlink-then-recreate path would reintroduce the tear), durable temp+fsync+rename semantics, and the workspace directory resolved through realpath before publication so configured workspace aliases keep working (the atomic writer rejects symlinked parents by design; the alias is resolved for publication only, and the final-file symlink rejection is unaffected because earlier bounded reads already verified the canonical file as a regular file).

Why This Change Was Made

The same function already treats atomicity as a requirement one step earlier (the legacy archive move is an atomic rename, and the archive is re-read "after the atomic move"), but the canonical overwrite — the one mutation with no recovery copy — bypassed that. The fix reuses the existing atomic-replace owner (@openclaw/fs-safe/atomic) and the existing timestamped repair archive directory, rather than adding new state or helpers.

Evidence

Shipped CLI, successful merge through a workspace directory alias (openclaw doctor --fix, workspace configured as a junction alias to a case-sensitive directory):

│  Workspace memory root merged:
│  - current: ...\oc-proof2\ws-alias\MEMORY.md
│  - backup:  ...\ws-alias\.openclaw-repair\root-memory\2026-10-27T08-13-09-701Z\memory.md
│  - pre-merge backup: ...\ws-alias\.openclaw-repair\root-memory\2026-10-27T08-13-09-701Z\MEMORY.md.pre-merge
│  - merged legacy content from: ...\ws-alias\memory.md
│  - removed legacy file: ...\ws-alias\memory.md

Verified through the junction's real target afterwards: MEMORY.md holds the merged content in the exact byte format main produces, the repair directory holds both memory.md and MEMORY.md.pre-merge, and memory.md is gone from the live path.

Shipped CLI, failed publication (MEMORY.md marked read-only, so the publication rename fails with EPERM):

│  Workspace memory repair could not be completed: EPERM: operation not
│  permitted, rename '...\ws-ro\MEMORY.md.42020.c558acb6-....tmp' -> '...\ws-ro\MEMORY.md'
=== after the run ===
canonical bytes: "# Canonical\n"          (intact, still read-only)
backups: memory.md ("# Legacy\n"), MEMORY.md.pre-merge ("# Canonical\n")
workspace listing: no temp leftovers

Completed upgrade from latest stable (stable 2026.10.7 via pnpm dlx, then this build, both through the shipped Doctor CLI on the same isolated case-sensitive workspace + state dir):

  1. [email protected] doctor --fix on the split workspace: merges with its own note format and no canonical backup (exit 0).
  2. This build's openclaw doctor --fix on the same state dir: completes the shared-state-DB migration custody and finishes with "Doctor complete" (exit 0, zero split/shadow findings).
  3. Post-upgrade check: the stable-merged MEMORY.md is preserved byte-for-byte, no re-merge or rewrite occurred, and the workspace holds only the merged file.

Data-model compatibility: the merge output format is byte-identical across stable 2026.10.7, main, and this head — existing data loads and works unchanged, and openclaw memory status on a merged workspace reports the memory file with normal dreaming path resolution.

Regression tests (src/commands/doctor-workspace.test.ts; red on main, green on this head; verified executing locally on a case-sensitive NTFS scratch dir since the canonical/legacy pair requires one):

  • preserves canonical memory when publication fails with ENOSPC / with EPERM: a failed publication leaves the live file intact, no fallback recreates it, the pre-merge backup holds the original bytes. The fixture path is canonicalized (realpath) like the shared temp-dir helpers, so the rename interception matches the resolved publication destination on hosts whose tmpdir sits behind a symlink (macOS).
  • preserves the workspace mode across a successful merge: a 0700 workspace stays 0700 (POSIX-checked in CI; Windows chmod is a no-op).
  • merges through a symlinked workspace directory alias: a configured alias is followed for publication and the merged file lands in the same canonical file (POSIX red on head, green with the fix, via CI; on Windows the junction variant executes green — the fs-safe parent rejection it fixes is POSIX-only, so Windows cannot reproduce the red).

Checks per the review acceptance list: pnpm vitest run src/commands/doctor-workspace.test.ts src/commands/doctor-memory-recall.test.ts — 19/19 pass; oxlint clean on both touched files; git diff --check clean; pnpm tsgo:prod all lanes pass.

Test environment notes and gaps

The canonical/legacy pair (MEMORY.md + memory.md) can only coexist on a case-sensitive filesystem, so this repair suite no-ops on case-insensitive hosts (existing tests in this file already guard with if (!(await seedMemory())) return;). Local verification used a per-directory case-sensitive NTFS scratch dir (NTFS setCaseSensitiveInfo); CI runs the suite on Linux, where the alias test also reproduces the POSIX red/green for the parent-rejection fix.

Upgrade note: stable 2026.10.8 was published today and is correctly refused by this repo's pnpm minimumReleaseAge supply-chain policy, so the upgrade run uses 2026.10.7, the newest installable stable.

Not covered: an injected publication failure during a full interactive openclaw doctor run (the CLI failure above uses a read-only canonical file, a real OS-level denial through the shipped CLI). The repository-wide lint shard crashes on this Windows box from memory pressure; the changed files are oxlint-clean directly and CI runs the full lint on the exact head.

The legacy root memory merge archived the legacy file but overwrote the
canonical MEMORY.md with a truncate-in-place writeFile and no copy of the
pre-merge bytes. A crash or ENOSPC mid-write tore or emptied the only
durable memory file, and the failure surfaced only as a doctor note.

Copy the canonical file beside the legacy archive before the merge and
publish through the repo's atomic text writer with the original file mode,
so a failed or interrupted merge leaves the live file intact and the
pre-merge bytes recoverable.
@clawsweeper

clawsweeper Bot commented Oct 26, 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 commands Command implementations size: S labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Doctor backs up canonical memory and publishes merged legacy memory through the existing atomic file writer.

Example: Doctor merges MEMORY.md containing "# Canonical\n" with memory.md containing "# Legacy\n", but publication fails with EPERM.

  • Before: An interrupted in-place write can truncate canonical memory without a canonical backup.
  • After: Canonical memory remains intact, both recovery copies exist, and Doctor reports the failed repair.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused, complete repair with shipped-entry-point evidence, distinct regression coverage, and all prior findings resolved; required CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied shipped Doctor output on case-sensitive NTFS covers successful alias publication and real EPERM rejection with canonical bytes intact, both backups present, and no temporary leftovers; completed stable-upgrade evidence preserves existing merged memory.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A failed Doctor merge can truncate the only canonical durable-memory file.
Reason: Protecting existing memory has clear value, and the change preserves the established repair workflow.

Merge readiness

✅ Ready for maintainer review

This PR fixes a concrete memory-loss path still present on current main; earlier findings are resolved, and no remaining actionable defect was found.

Priority: P2
Reviewed head: 4f35bf1d0feef4de8b8b6fe3bdcccbef4bb1b727

Before merge

None.

Findings

None.

Agent review details

How this fits together

Doctor receives configured agent workspace paths, detects split root memory, obtains repair confirmation, and archives legacy content before publishing canonical memory.

flowchart TD
  A[Doctor CLI] --> B[Memory recall health]
  B --> C[Workspace memory repair]
  C --> D[Legacy archive and canonical backup]
  D --> E[Atomic file writer]
  E --> F[Canonical MEMORY.md]
  C --> G[Doctor result note]
Loading

Technical review

Best possible solution:

Retain the focused backup-and-atomic-publication fix and land it after required CI passes.

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

Current-main source exposes truncation before a failed write can complete; contributor evidence exercises failed publication through the shipped CLI, while this review ran no target code.

Is this the best way to solve the issue?

Backing up canonical bytes and reusing the existing atomic writer directly fixes the destructive write without changing merge semantics or adding a competing owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Legacy archive ordering and merge format keeps the original intent (10a9acb: Repair shadowed legacy memory while archiving it first so repeated repairs do not duplicate content.)
  • Canonical in-place publication changes intended behavior with a stated reason (10a9acb: The original repair published merged text directly; this PR explains and addresses the resulting truncation risk.)
  • Bounded reads and valid UTF-8 keeps the original intent (ce5b795: Preserve malformed memory bytes and refuse unsafe decoding before repair mutation.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Mariano: Raw commit 10a9acb adds src/commands/doctor-workspace.ts:225 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 10a9acbf2936; files: src/commands/doctor-workspace.ts)

PR surface

Source +32, Tests +94. Total +126 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 33 1 +32
Tests 1 95 1 +94
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 128 2 +126

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Prevents durable-memory corruption during the limited split-root-memory Doctor repair path.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-26T18:09:17.786Z sha 065aa40 :: needs real behavior proof before merge. :: [P1] Preserve the workspace directory's existing permissions | [P2] Disable destructive copy fallback for the canonical memory write
  • reviewed 2026-10-27T03:06:21.284Z sha 84ddf27 :: needs real behavior proof before merge. :: [P2] Resolve workspace directory aliases before atomic publication
  • reviewed 2026-10-27T03:14:00.230Z sha 84ddf27 :: needs real behavior proof before merge. :: [P2] Resolve workspace directory aliases before atomic publication
  • reviewed 2026-10-27T08:54:03.890Z sha 053e647 :: needs real behavior proof before merge. :: [P2] Canonicalize the fixture path before intercepting publication

Reviewed October 27, 2026, 10:52 AM ET / 14:52 UTC (Revision 5).

… memory merge

Review findings on 065aa40: writeTextAtomic defaults dirMode to 0755 and
chmods the existing parent directory, widening a private 0700 workspace, and
its unconditional copy fallback unlinks the live MEMORY.md when rename fails
with EPERM/EEXIST, reintroducing the tear this fix removes.

Publish through replaceFileAtomic directly, matching the existing memory
writer: pass the workspace's actual mode back as dirMode, keep the original
file mode via preserveExistingMode, and leave the copy fallback disabled so a
denied rename fails the repair with the live file untouched. Cover EPERM
publication failures and workspace-mode preservation in tests.
@syxscott

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed 84ddf270 addressing all findings from the review of 065aa40b:

  • [P1] Workspace permissions: publication now uses replaceFileAtomic directly and passes the workspace's actual mode back as dirMode, so the existing directory mode is never changed (verified by a new test asserting a 0700 workspace stays 0700; POSIX-checked in CI).
  • [P2] Destructive copy fallback: disabled by calling replaceFileAtomic without copyFallbackOnPermissionError. An EPERM/EEXIST rename failure now fails the repair with the live MEMORY.md untouched. The proof comment in the PR body shows the contrast: the same injected failure previously completed the merge through the fallback's unlink-then-recreate path.
  • Security concern (workspace privacy): same fix as P1 — no mode mutation on any path, including failed publications.
  • Real behavior proof: added terminal output from a shipped openclaw doctor --fix run (successful merge, both backups, legacy removed) and from a real repair-path run with injected EPERM (canonical bytes intact, pre-merge backup present, no temp leftovers), both reproduced in the PR body. Verified the tests genuinely execute via a case-sensitive NTFS scratch directory (the canonical/legacy pair requires one); red on main, green on this head.
  • Data-model compatibility: merge output is byte-identical to main's format, and a second openclaw doctor --fix run after the merge reports no findings.

PR body updated with all of the above.

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
Review finding on 84ddf27: replaceFileAtomic rejects a symlinked parent
directory on POSIX, so a configured workspace alias (a supported setup) made
the merged memory publication fail after the legacy file had already been
archived. The in-place write it replaces followed the alias.

Resolve the workspace directory with realpath for publication only. The
final-file symlink rejection is unaffected: earlier bounded reads already
verified the canonical file as a regular file, and the destination inside the
resolved directory is that same file. Cover the alias case in tests.
@syxscott

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed 053e6470 addressing all three items from the review of 84ddf270:

  • [P2] Workspace directory aliases: publication now resolves the workspace through realpath before calling replaceFileAtomic (doctor-workspace.ts), so configured aliases keep working while the atomic writer's symlink-parent rejection stays intact for everything it is designed to catch. The final-file symlink rejection is unaffected — earlier bounded reads already verified the canonical file as a regular file before publication is attempted. Covered by a new test, merges through a symlinked workspace directory alias (POSIX red on head / green with the fix via CI; the Windows junction variant executes green since the fs-safe parent rejection is POSIX-only).
  • Real behavior proof (failed publication through the shipped CLI): marked MEMORY.md read-only so the publication rename fails with EPERM in a real openclaw doctor --fix run — the doctor reports "could not be completed", canonical bytes stay intact, both backups exist, no temp leftovers. Full terminal output and post-run filesystem state are in the PR body.
  • Real behavior proof (upgrade + data-model compatibility): ran latest stable 2026.10.5 (pnpm dlx) on a fresh split workspace — it merged with its own old path — then ran this build's Doctor against the stable-produced workspace: zero split/shadow findings, merged MEMORY.md byte-identical afterwards, and openclaw memory status on a merged workspace reports the memory file with normal dreaming path resolution. Details in the PR body.
  • Acceptance list: pnpm vitest run src/commands/doctor-workspace.test.ts src/commands/doctor-memory-recall.test.ts 19/19, oxlint clean on both files, git diff --check clean, pnpm tsgo:prod pass.

PR body updated with all evidence.

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 27, 2026
The publication-failure tests intercept renames by comparing against the
fixture path, but the repair now publishes to the realpath-resolved
workspace. On hosts whose temporary root is a symlink (macOS /var ->
/private/var), the fixture and the destination differ, the fault is never
injected, and the test fails on its error-note assertion. Canonicalize the
fixture path like the shared temp-dir helpers do.
@syxscott

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Pushed 4f35bf1d addressing all three items from the review of 053e6470:

  • [P2] Fixture path canonicalization: the memory-repair fixture now realpaths its mkdtemp directory before deriving canonicalPath, exactly as the shared temp-dir helpers document ("symlinked roots break tests that compare or intercept fs paths by equality"), so the rename interceptor compares against the resolved publication destination on hosts whose tmpdir is a symlink (macOS).
  • Completed latest-stable upgrade: full chain through shipped CLIs on one isolated case-sensitive workspace + state dir — stable 2026.10.7 (pnpm dlx) doctor --fix merged the split workspace (exit 0), then this build's doctor --fix completed the state-DB migration custody and finished "Doctor complete" (exit 0, zero split/shadow findings), with the stable-merged MEMORY.md preserved byte-for-byte. Terminal output and the post-upgrade state are in the PR body. (Stable 2026.10.8 was published today and is correctly refused by this repo's pnpm minimumReleaseAge policy, so 2026.10.7 is the newest installable stable.)
  • Data-model compatibility: covered by the upgrade above plus the byte-identical merge format across stable 2026.10.7 / main / this head, and openclaw memory status reading a merged workspace normally.

Checks: pnpm vitest run src/commands/doctor-workspace.test.ts src/commands/doctor-memory-recall.test.ts 19/19, oxlint clean on the touched file, git diff --check clean. PR body updated with all evidence.

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 27, 2026
@syxscott syxscott closed this by deleting the head repository Oct 28, 2026
@syxscott

Copy link
Copy Markdown
Contributor Author

This submission was closed by mistake on 2026-10-28; the repair itself is unchanged and continues in #187291 (same head 4f35bf1d, ClawSweeper 5/6 diamond lobster, CI green). Please review #187291 instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant