Skip to content

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

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

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.


Note on this re-submission: the previous PR (#184858) was closed automatically on 2026-10-28 when a fork of this repository on my account was deleted by an unrelated local cleanup. The commits and the diff are unchanged — the head commit is the exact same 4f35bf1 that addressed all three items from the review of 053e647 (fixture path canonicalization included). Please treat this as the continuation of #184858 rather than a new proposal; if you would prefer to keep the original thread, let me know and I will close this one instead.

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

clawsweeper Bot commented Oct 29, 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 29, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026
@clawsweeper

clawsweeper Bot commented Oct 29, 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: A failed in-place write can damage canonical memory without preserving its original bytes.
  • After: Canonical memory stays intact, both recovery copies remain available, and Doctor reports the failed repair.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused repair with shipped-entry-point evidence, compatible stable-state handling, distinct regression coverage, and a passing exact-head CI gate.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied Doctor CLI terminal output on case-sensitive NTFS exercises successful publication through a junction alias and real EPERM rejection with canonical bytes intact, both backups present, and no temporary leftovers.
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 damage the only canonical durable-memory file.
Reason: Preserving existing memory has clear value, and the repair retains the established workflow and data format.

Merge readiness

✅ Ready for maintainer review

This PR fixes a concrete durable-memory corruption path still present on current main; no actionable patch defect remains, and the exact-head CI gate passes.

Priority: P2
Reviewed head: 4f35bf1d0feef4de8b8b6fe3bdcccbef4bb1b727

Before merge

None.

Findings

None.

Agent review details

How this fits together

Doctor receives configured workspace paths and repair confirmation, archives legacy memory, and publishes merged canonical memory with a result note.

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:

Land the focused canonical-backup and atomic-publication repair through the normal merge workflow.

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

Current-main source shows canonical truncation can precede a failed write; the contributor supplied shipped-CLI failure evidence, and this read-only review executed no target code.

Is this the best way to solve the issue?

The change fixes the destructive publication at its existing owner, preserves established merge semantics, and adds distinct failure, permission, and workspace-alias coverage without introducing another writer.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Legacy archive ordering and merge format keeps the original intent (10a9acb: Repair shadowed legacy memory while archiving it first so reruns do not duplicate imported content.)
  • Canonical in-place publication changes intended behavior with a stated reason (10a9acb: The original repair wrote merged text directly; this PR explains and addresses the resulting truncation risk.)
  • Bounded reads and UTF-8 preservation keeps the original intent (ce5b795: Refuse malformed UTF-8 before rewriting memory and preserve independent archives after read failures.)

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:224 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)
  • Peter Steinberger: Raw commit ce5b795 adds src/commands/doctor-workspace.ts:204 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ce5b795128e3; files: src/commands/doctor-workspace.ts)
  • cxbAsDev: Raw commit 881b0a6 adds src/commands/doctor-workspace.ts:259 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 881b0a619f56; 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

Root-cause cluster

Relationship: canonical
Canonical: #187291
Summary: This PR continues the identical-head repair from the earlier closed, unmerged submission.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Protects durable memory from 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.

Reviewed October 29, 2026, 12:36 AM ET / 04:36 UTC.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @syxscott for the fix and the thorough failure, permission, and workspace-alias coverage. Landed via #190497 in 1b92282c1047, preserving your author/co-author credit and the requested steipete co-author credit.

The landed fix keeps the atomic writer and adds unique repair directories so a later merge cannot overwrite earlier recovery files. Red/green reproduction, 60 named tests, real ENOSPC CLI proof, published-head tests/lint, and exact-head CI passed. The squash commit is verified as an ancestor of main.

Merged to main; not yet released.

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.

2 participants