Skip to content

fix: keep project session scratch out of shared clones - #196206

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-scratch-in-shared-base-clone-20260919
Nov 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-scratch-in-shared-base-clone-20260919

Conversation

@steipete

@steipete steipete commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes agent build and clone scratch accumulating in a shared project clone when a new project session omits worktree or explicitly sets it to false.

User Impact

New sessions for projects cloned by OpenClaw always receive a managed worktree, including repository-URL sessions and retries of older pending URL-only sessions. The project picker offers New worktree for these projects. Registered local folders and configured agent workspaces retain Current checkout support.

Existing accepted sessions retain their working directories; start a new project session to leave a previously selected shared clone. Unknown nested worktrees are preserved because their path names do not establish ownership or lossless removal. This change does not impose a hard byte quota or migrate arbitrary raw-cwd sessions.

Why This Change Was Made

Project admission previously resolved the shared clone as the session root unless the caller opted into worktree creation. Exec and sandbox placement then consumed that accepted root, so normal workspace scratch guidance sent temporary builds into the maintenance source.

The admission owner now chooses managed placement for cloned projects and reuses the existing worktree preparation, binding, cancellation, and retention owners. The direct URL-to-clone binding path is removed. Existing hourly cleanup expires idle .openclaw/tmp entries after 24 hours; moving new runs off the base also lets eligible legacy tmp drain. Live or queued custody still defers cleanup. Native PR-tool worktree placement is separate work tracked in #158419.

Production code is net -7 lines. No new config, cache, schema, or GC implementation. Tests are net +137 lines; measurement tooling +96.

Evidence

  • Both new public-handler placement regressions (omitted and false worktree intent) fail on parent ce7788f5a24e5e2d0ef146a5dcea3ef4d0bb0983 and pass with the fix. They verify the managed registry binding, session cwd/root, and absence of scratch in the base.
  • Six focused suites: 70/72 passed initially; the corrected default-branch assertion and an existing remote-base retry case pass in the final targeted 8/8 rerun. That retry had one controller-drain timeout during the concurrent broad check (25.97 s), then passed in 14.59 s. Its timing cause remains unresolved; the passing replay is not claimed as a fix.
  • Scratch custody suite 9/9: actual expired base tmp drains after queued custody ends, while managed-workspace scratch and unknown nested directories remain intact. Existing TTL behavior is reused.
  • Picker state tests 50/50; targeted Chromium E2E 1/1 verifies automatic worktree selection when Current is unavailable and preserves permitted registered-folder selection. No UI source or browser-shared module changed.
  • pnpm check:changed --staged --base HEAD ran. Runtime, core-test, and scripts typecheck errors found during development were corrected; all three exact typecheck lanes and affected lint/format checks now pass. Other scoped guards passed. The remaining dead-export failures reproduce identically on the exact parent (19 production / 6 full-tree diagnostics); they are existing main regressions, not waived or hidden. The introducing changes are refactor(plugins): forward auth and catalog to their owners #190205 (f63e5cd0, 11 provider exports), fix(cli): surface stale-updater launchd scan failures in deep status #195977 (fee857b4, 3 launchd exports), refactor(auth): isolate provider auth data contracts #190544 (cf1ae7bb, 4 provider types), and Dashboards gallery: Display menu with list view, ordering and grouping #194455 (cde34f11, 1 UI export). Replacing only those changed owners with their pre-change sources in the isolated parent makes all three dead-export scans pass.
  • Independent Codex autoreview: scoped-clean through P2. Documentation anchor and git diff --check pass.

Synthetic APFS fixture: 50,000 tracked + 12,000 ignored files, 1,100,004,000 logical payload bytes; no production data. A1/A2/B1/A3/B2 controls, baseline n=15 and candidate n=11:

Owner-boundary measurement Before After
Scratch written inside base per 16 MiB write 16 MiB 0 bytes
Median / p95 wall time 2,741 / 2,851 ms 9,304 / 16,483 ms
Median main-thread CPU 5.05 ms 208.84 ms
Median main-thread allocation 3.09 MB 158.36 MB

Retained-template candidate median is 9,010 ms; the additional approximately 6.27 seconds creates an isolated checkout instead of binding the shared directory. This is a placement/correctness tradeoff, not a speedup. A/A wall medians varied 0.56%, CPU -0.91%, and allocation 52.4%; small allocation differences are not causal evidence. Timings exclude scratch writes, session-row admission, inference, remote fetch, and Git/worker CPU and allocation. These are owner-boundary measurements, not full Gateway latency or btrfs qualification. No live deployment or production deletion was performed.

Route cloned project sessions and repository URL preparation through managed worktrees, including omitted or false worktree intent and retries of older pending URL sessions. Keep registered local folders selectable as current checkouts. Reuse existing scratch retention custody and preserve unregistered nested worktrees whose contents cannot be removed losslessly.
@clawsweeper

clawsweeper Bot commented Nov 9, 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 scripts Repository scripts size: L labels Nov 9, 2026
@steipete
steipete marked this pull request as ready for review November 9, 2026 19:09
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T19:13:16.678671Z 205071f Draft marked ready
ℹ️ 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.

@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: 205071f48b

ℹ️ 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 +366 to +367
if (requestedProject.value.worktree || requestedProjectGitUrl) {
p.worktree = true;

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 Preserve accepted checkouts when adopting existing session keys

When an existing session bound directly to a cloned project is adopted through sessions.create with its key and the same projectId, omitting worktree or setting it to false now silently relocates it. This assignment installs the worktree preparation lifecycle even though existingTargetEntry exists; prepareSessionWorktreeCreation allocates a checkout, and projectPreparedSessionWorkspace overwrites the existing session's cwd while retaining its conversation. Uncommitted files and scratch in the previously accepted checkout consequently disappear from the agent's working context, contrary to the documented promise that existing sessions retain their accepted directories. Apply automatic managed placement only to genuinely new sessions, while preserving explicit worktree requests and pending-preparation recovery.

Useful? React with 👍 / 👎.

@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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR routes new cloned-project and repository-URL sessions into managed worktrees while retaining Current checkout for registered folders.

Example: Create a cloned-project session with worktree=false, then write a 16 MiB temporary build.

  • Before: The build occupies 16 MiB inside the shared project clone.
  • After: The build occupies the session's managed worktree, leaving zero build bytes in the shared clone.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-level repair with focused regression evidence, blocked by existing-session relocation and unverified upgrade compatibility.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence covers handler regressions and real-Git owner measurements, but no latest-stable upgrade preserving accepted workspace state is supplied.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Temporary builds and clones from ordinary project sessions accumulate in the shared maintenance clone.
Reason: The maintainer-authored direction protects the maintenance source using existing managed-worktree machinery and explicitly accepts the added checkout cost.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: the placement fix is useful, but automatic worktree selection also silently relocates existing keyed sessions.

Priority: P2
Reviewed head: 205071f48bf41f418e9f67f6e1ad75e61a376831

Before merge

  • Preserve accepted checkouts when reusing an existing session key (P1) - For an existing session bound directly to a cloned project, call sessions.create with its key and the same projectId while omitting worktree or setting it to false. The resolver now makes worktree true, and this assignment installs prepareSessionWorktreeCreation despite existingTargetEntry being present. The lifecycle allocates a managed checkout and projectPreparedSessionWorkspace commits its cwd while retaining the conversation. Uncommitted files in the accepted checkout are consequently absent from the agent's new working context, contradicting the documented promise that existing sessions retain their directories. Restrict automatic placement to genuinely new sessions, retaining explicit worktree requests and pending-preparation recovery, and add an existing-key regression.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P1] Preserve accepted checkouts when reusing an existing session key — src/gateway/server-methods/sessions-create.ts:366-367

Tests

  • Missing end-to-end proof: Provide a latest-stable upgrade run preserving an accepted keyed checkout and its files while verifying new-session placement and recovery of older URL-only pending sessions.
Agent review details

How this fits together

Gateway session admission resolves the selected project, prepares its workspace through the managed-worktree owner, and persists the cwd consumed by agents and terminals.

flowchart TD
  A[Session creation request] --> B[Project access and source selection]
  B --> C[Managed worktree preparation]
  B --> D[Registered current checkout]
  C --> E[Session workspace binding]
  D --> E
  E --> F[Agent and terminal execution]
  F --> G[Scratch maintenance]
Loading

Technical review

Best possible solution:

Apply automatic managed placement to new sessions while preserving accepted keyed-session workspaces and pending-preparation recovery.

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

Current main binds cloned projects directly when worktree is omitted or false; the PR reports two public-handler regressions failing on its parent and passing with the change, but this review ran no target code.

Is this the best way to solve the issue?

Choosing placement at admission and removing direct URL-to-clone binding addresses the producer of the problem without another cleanup mechanism; automatic selection must respect existing accepted sessions.

Full review comments:

  • [P1] Preserve accepted checkouts when reusing an existing session key — src/gateway/server-methods/sessions-create.ts:366-367
    For an existing session bound directly to a cloned project, call sessions.create with its key and the same projectId while omitting worktree or setting it to false. The resolver now makes worktree true, and this assignment installs prepareSessionWorktreeCreation despite existingTargetEntry being present. The lifecycle allocates a managed checkout and projectPreparedSessionWorkspace commits its cwd while retaining the conversation. Uncommitted files in the accepted checkout are consequently absent from the agent's new working context, contradicting the documented promise that existing sessions retain their directories. Restrict automatic placement to genuinely new sessions, retaining explicit worktree requests and pending-preparation recovery, and add an existing-key regression.
    Confidence: 0.98

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/server-methods/sessions-create-worktree-base.test.ts --maxWorkers=1
  • pnpm test src/gateway/server.sessions.create.projects.test.ts --maxWorkers=1
  • pnpm test src/gateway/server-methods/projects.test.ts --maxWorkers=1
  • pnpm check:changed --base ce7788f
  • Upgrade an isolated Gateway from v2026.11.2 and verify accepted-key cwd/file preservation, new cloned-project isolation, and legacy pending URL recovery.

What I checked:

Likely related people:

  • RoboClaw: Raw commit 95363ce adds src/gateway/server-methods/session-create-project.ts:67 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 95363ce54afd; files: src/gateway/server-methods/session-create-project.ts)

PR surface

Source -7, Tests +137, Docs +15, Other +98. Total +243 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 116 123 -7
Tests 4 203 66 +137
Docs 1 15 0 +15
Config 0 0 0 0
Generated 0 0 0 0
Other 2 112 14 +98
Total 10 446 203 +243

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test growth Runtime net -7 lines; tests net +137; measurement tooling net +96. The runtime reuses existing preparation and cleanup owners; added tests cover placement, legacy pending recovery, picker behavior, and scratch custody.

Labels

Label changes:

  • add P2: Shared-clone scratch accumulation is a bounded workspace-management bug with a focused repair.
  • add merge-risk: 🚨 session-state: Reusing an existing session key can replace its persisted cwd while retaining conversation state and leaving uncommitted work in the previous checkout.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Shared-clone scratch accumulation is a bounded workspace-management bug with a focused repair.
  • merge-risk: 🚨 session-state: Reusing an existing session key can replace its persisted cwd while retaining conversation state and leaving uncommitted work in the previous checkout.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 November 9, 2026, 2:28 PM ET / 19:28 UTC.

@steipete

steipete commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head CI attribution for 205071f48bf41f418e9f67f6e1ad75e61a376831: run 42680684705, attempt 1 tested merge ce8b6bd8901628205e4f3893bb490db5f0c454f3, whose main parent is 6ab90a6b65a0feef2226b3dcc5ba4b1d4a2a90dd.

Both failures are inherited. The test-lines checker passes on this PR's head: 6,604,381 lines / 6,604,387 ceiling, six lines slack. The PR adds exactly 137 test lines and already includes an exact 137-line allocation in config/test-lines-allocations/shared-clone-session-workspace.txt. CI main is 342 lines over, and the tested merge is the same 342 over. The origin is #191326 (56617cd00086481212d29745ed71f5feb8a40b9e): 350 unallocated lines consumed six lines of slack; #196151 (e2320c33ac8a2c671223af2bd57d31a5af5147be) subsequently removed two. No additional allocation belongs to this PR.

The gateway timeout is a separate main regression introduced by ba6dce8d054d275d35fe24bfe0be87ddf7ff5f74, not #196153. pnpm test src/gateway/server-methods/chat-send-pending-inputs.test.ts --maxWorkers=1 passes 40/40 on this PR's exact head. On CI's exact main parent, ordinary chat input admission > creates recipient-only mentions at original message commit, never at the queued ACK reproduces the timeout in 300.085 seconds (120-second test timeout plus 180-second cleanup timeout). I stopped that full-file baseline run after the reproduction; this is not a completed whole-file baseline result.

Causal comparison: on that exact main parent, reversing only the introducing commit's chat-send-setup.ts change makes both CI-named cases pass: the recipient-only case in 3.160 seconds and includes an idle first commit in the Inbox before ACK without waiting for the agent in 2.330 seconds (2 passed, 38 unselected, 60.50-second command). The new human-only classification skips agent dispatch; the old fixture awaits dispatchedRecorder indefinitely. The second CI failure is consistent with cleanup cascading after the first timeout. The affected test, fixture, and routing sources are byte-identical between CI main and its tested merge. Main's test owner needs to reconcile those fixtures with the new human-only behavior; that repair remains with the lead.

Focused product proof and the fresh independent Codex review remain clean through P2. CI is still red, not relabeled green. Landing this exact head uses the explicitly authorized inherited-failure exception with retained checkout, baseline, differential, and source-equality evidence. No source change or CI rerun was needed for this investigation.

@steipete
steipete merged commit 97e91a1 into main Nov 9, 2026
224 of 234 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-scratch-in-shared-base-clone-20260919 branch November 9, 2026 19:53
@steipete

steipete commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
Route cloned project sessions and repository URL preparation through managed worktrees, including omitted or false worktree intent and retries of older pending URL sessions. Keep registered local folders selectable as current checkouts. Reuse existing scratch retention custody and preserve unregistered nested worktrees whose contents cannot be removed losslessly.
obviyus added a commit that referenced this pull request Nov 10, 2026
Since 97e91a1 (#196206), cloned project sessions use a managed worktree even when worktree intent is omitted, so a required-sandbox github spawn is accepted in an isolated worktree instead of failing outside the sandbox. A registered current checkout outside the sandbox is still rejected.

Co-authored-by: obviyus <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant