Skip to content

fix(memory): flush agent memory into the configured workspace on rooted sessions - #162142

Open
leapdragon wants to merge 1 commit into
openclaw:mainfrom
leapdragon:fix/memory-flush-agent-workspace
Open

leapdragon wants to merge 1 commit into
openclaw:mainfrom
leapdragon:fix/memory-flush-agent-workspace

Conversation

@leapdragon

Copy link
Copy Markdown
Contributor

What Problem This Solves

A dashboard session created with a session root (sessions.create with root, or a worktree session) runs with workspaceDir set to that root: resolveIngressWorkspaceOverrideForSessionRun returns the managed spawnedCwd, and the whole turn executes there. The pre-compaction memory flush inherited that override, so on such a session it created and guarded <root>/memory/<date>.md instead of the agent's memory/<date>.md.

The model, whose bootstrap files (AGENTS.md, MEMORY.md) describe the workspace memory/ directory, wrote there and was refused on every attempt:

[tools] write failed: Memory flush writes are restricted to memory/2026-09-30.md; use that path only.
raw_params={"path":"/home/…/.openclaw/workspace/memory/2026-09-30.md", …}
[tools] read failed: Path escapes sandbox root (~/.openclaw/workspace/projects/job-hunter): /home/…/.openclaw/workspace/memory/2026-09-30.md.

When the flush did land, it landed in projects/job-hunter/memory/2026-09-30.md, which the memory index never scans and the next session never loads. Seen on 2026.9.4 with a session rooted at a project subdirectory of the workspace; main passes the same run.workspaceDir to the flush.

Why This Change Was Made

Agent memory belongs to the configured workspace: runEmbeddedAgent already keeps bootstrap identity there (bootstrapWorkspaceDir: canonicalWorkspace in run-orchestrator.ts) while execution stays in the override. The flush is the write side of that same identity, so it should target the same directory.

  • FollowupRun.run gains bootstrapWorkspaceDir, set in executePreparedReplyRun to the configured workspace (context.skillsWorkspaceDir) only when it differs from the run's workspaceDir. Runs in the canonical workspace carry nothing new.
  • runMemoryFlushIfNeeded resolves memoryWorkspaceDir = bootstrapWorkspaceDir ?? workspaceDir and uses it for ensureMemoryFlushTargetFile and for the flush run's harness.workspaceDir. The append-only write guard derives its allowed path from that workspace, so the model's memory/<date>.md (relative or absolute) now resolves to the agent's memory file. The detached source-transcript view keeps the run's workspaceDir.

Spawned sessions with their own spawnedWorkspaceDir get the same treatment: their flush persists into the agent workspace that bootstrap reads, rather than a spawn directory.

User Impact

Memory flushes on rooted and worktree sessions write the agent's memory/<date>.md, where memory index and the next session's bootstrap find them. Sessions running in the configured workspace are unchanged.

Evidence

  • agent-runner-memory.test.ts: a flush for a run whose workspaceDir is a task subdirectory with bootstrapWorkspaceDir set completes, hands the harness the configured workspace, creates memory/2023-11-14.md there, and creates no memory/ under the task directory.
  • get-reply-run.media-only.test.ts: a session with spawnedCwd carries workspaceDir = cwd and bootstrapWorkspaceDir = configured workspace; a session without an override carries no bootstrapWorkspaceDir.
node scripts/run-tsgo.mjs -p tsconfig.core.json                                   # clean
node_modules/.bin/oxlint <changed files>                                          # clean
node scripts/run-vitest.mjs run src/auto-reply/reply/agent-runner-memory.test.ts \
  src/auto-reply/reply/get-reply-run.media-only.test.ts src/auto-reply/reply/memory-flush-session.test.ts
  Test Files  3 passed   Tests  168 passed

🤖 Generated with Claude Code

…ed sessions

Sessions with a session root or spawned workspace run with `workspaceDir`
set to that override, and the pre-compaction memory flush inherited it: the
flush created and guarded `<root>/memory/<date>.md`, the model wrote to the
agent's `memory/<date>.md` as its bootstrap files describe, and every write
was refused ("Memory flush writes are restricted to memory/<date>.md").
Flushes that did land went where the memory index never looks.

Carry the configured workspace on the followup run as
`bootstrapWorkspaceDir` (set only when it differs from `workspaceDir`, the
same split the embedded runner keeps for bootstrap identity) and let the
memory flush target and run in it, so the guarded path is the agent's
memory file.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 30, 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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. labels Sep 30, 2026
@clawsweeper

clawsweeper Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The PR carries the configured agent workspace into rooted-session memory flushes and uses it to prepare the daily note and initialize the harness.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused patch addresses a valid problem, but its execution-path defect and mocked-only proof prevent merge readiness.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Merge readiness

⛔ Blocked before merge - 5 items remain

The workspace bug remains on current main, and this PR contains useful work. The prior P1 finding remains unresolved on the unchanged head: file preparation and actual model execution still use different workspaces.

Priority: P1
Reviewed head: 1c6c340c0c2bbea9f0be370f8776c6ee374bf5a4

Before merge

  • Add real behavior proof - The captured evidence exercises flush preparation with a mocked embedded runner, not a rooted session's real restricted write after the fix. Add a redacted terminal trace, logs or recording showing a successful append in the configured workspace and no project-local memory write; remove private paths, IP addresses, keys, phone numbers and endpoints. Updating the PR body should trigger review automatically; otherwise ask a maintainer to comment @clawsweeper re-review. No stored-data schema or serialization contract changes. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Pass the configured workspace to the actual flush run (P1) - For a rooted session, this changes harness preparation to the configured workspace, but maintenanceRun still copies the original project workspaceDir. buildEmbeddedRunBaseParams forwards that unchanged value to runEmbeddedAgent, and memorySession supplies no workspace override. The restricted write therefore still targets the project, while the PR pre-creates the daily file elsewhere; absolute writes to the configured workspace remain rejected. Set the actual flush candidate's workspace consistently and assert that boundary rather than only the harness argument. This is the still-unfixed finding from the prior review.
  • Resolve merge risk - Target-file preparation now uses the configured workspace while the actual flush write still uses the project workspace, leaving durable notes rejected or misplaced.
  • Resolve merge risk - The branch has reported merge conflicts with current main; resolution must preserve the merged worker-accounting and plugin-owned flush paths.
  • Complete next step - Repair the actual flush workspace, resolve the reported conflicts while preserving current-main flush ownership, and provide redacted after-fix runtime proof.

Findings

  • [P1] Pass the configured workspace to the actual flush run — src/auto-reply/reply/agent-runner-memory.ts:1515-1516
Agent review details

How this fits together

Before compaction, OpenClaw runs a private maintenance turn over the conversation to save durable notes. Those notes belong in the configured agent workspace, even when the ordinary session executes in a project directory.

flowchart TD
  A[Rooted session] --> B[Conversation nearing compaction]
  C[Configured agent workspace] --> D[Memory flush preparation]
  B --> D
  D --> E[Private maintenance turn]
  E --> F[Restricted append tool]
  F --> G[Daily memory note]
Loading

Technical review

Best possible solution:

Use one configured workspace for file-based flush preparation, candidate execution and append containment, while retaining the source session's transcript and security policy.

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

Yes, source establishes the mismatch for a rooted session whose configured and execution workspaces differ. The canonical report provides a threshold-based Gateway reproduction; no runtime reproduction was executed in this read-only review.

Is this the best way to solve the issue?

No, the proposed direction is appropriate but incomplete: changing harness preparation does not change the embedded candidate's workspace. The repair must reach the final write boundary.

Full review comments:

  • [P1] Pass the configured workspace to the actual flush run — src/auto-reply/reply/agent-runner-memory.ts:1515-1516
    For a rooted session, this changes harness preparation to the configured workspace, but maintenanceRun still copies the original project workspaceDir. buildEmbeddedRunBaseParams forwards that unchanged value to runEmbeddedAgent, and memorySession supplies no workspace override. The restricted write therefore still targets the project, while the PR pre-creates the daily file elsewhere; absolute writes to the configured workspace remain rejected. Set the actual flush candidate's workspace consistently and assert that boundary rather than only the harness argument. This is the still-unfixed finding from the prior review.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Align preparation and execution (recommended)
    Carry the configured memory workspace into the actual embedded flush candidate and cover a real append that leaves the project directory untouched.

Security

None.

Evidence

What I checked:

  • Pinned introduction and clean checkout: The merge-base-to-head diff introduces only the five supplied memory/reply files. The checkout matches the previously reviewed head and git status remained clean. (1c6c340c0c2b)
  • Actual execution retains the project workspace: The new memoryWorkspaceDir reaches target-file preparation and harness initialization, but maintenanceRun is built from the original run. Its workspace passes through buildEmbeddedRunExecutionParams into runEmbeddedAgent; memorySession does not override it. (src/auto-reply/reply/agent-runner-memory.ts:1516, 1c6c340c0c2b)
  • Workspace propagation contract: createSessionMaintenanceFollowup copies run.workspaceDir and cwd, while buildEmbeddedRunBaseParams forwards those values to the embedded runner. Harness initialization does not rewrite the candidate's execution parameters. (src/auto-reply/reply/agent-runner-run-params.ts:110, 1c6c340c0c2b)
  • Current main still needs the workspace repair: At fetched main, the extracted flush preparation still passes followupRun.run.workspaceDir to ensureMemoryFlushTargetFile. The actual flush candidate likewise inherits the original maintenance workspace. (src/auto-reply/reply/memory-flush-prepare.ts:139, 888ddd5deab4)
  • Tests bypass the final write: The added rooted-session test checks the harness workspace and the pre-created file, but runEmbeddedAgent is mocked. It does not assert the actual candidate workspace or execute the restricted write tool. The captured PR body supplies tests, lint and typechecks, with no after-fix runtime trace. (src/auto-reply/reply/agent-runner-memory.test.ts:1024, 1c6c340c0c2b)
  • Existing behavior and canonical report: Memory documentation places durable notes in the agent workspace. [Bug]: Pre-compaction memory flush writes into selected project directory #161253 independently describes the same project-directory contamination, provides a deterministic threshold-based reproduction, and explicitly says existing project-local notes must not be deleted automatically. Public docs: docs/concepts/memory.md. (docs/concepts/memory.md:10, 1c6c340c0c2b)

PR surface

Source +12, Tests +47. Total +59 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 14 2 +12
Tests 2 47 0 +47
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 61 2 +59

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #161253
Summary: This PR is an incomplete candidate fix for the independently reported project-directory memory-flush bug.

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:

  • P1: Rooted sessions can fail to preserve durable context during compaction, affecting an existing agent workflow.
  • merge-risk: 🚨 session-state: The introduced workspace split leaves memory-file preparation and actual persistence targeting different directories.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish 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.

  • Align the actual embedded flush workspace with target-file preparation and add regression coverage that checks the candidate execution boundary.
  • Provide redacted after-fix runtime evidence of the rooted-session append reaching the configured workspace.

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 (1 earlier review cycle)
  • reviewed 2026-09-30T21:34:18.633Z sha 1c6c340 :: needs real behavior proof before merge. :: [P1] Pass the configured workspace to the actual flush run

Reviewed October 7, 2026, 6:23 PM ET / 22:23 UTC (Revision 2).

This branch has not been deployed

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

Labels

merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S 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.

1 participant