Skip to content

fix(agents): preserve worktree-local ignored state during lossless cleanup - #108401

Merged
steipete merged 2 commits into
openclaw:mainfrom
yetval:fix/worktree-ignored-lossless
Jul 16, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
yetval:fix/worktree-ignored-lossless

Conversation

@yetval

@yetval yetval commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Automatic managed-worktree cleanup can delete ignored worktree-local state that OpenClaw itself provisioned through .worktreeinclude. Git status and ordinary Git snapshots omit ignored files; rereading the current source manifest during cleanup or restore is unsafe because the manifest and source copy can change or disappear after worktree creation.

This reaches run-end removeIfLossless(), idle garbage collection, and count/size eviction. The affected state can include credentials, local configuration, ignored databases, or recorded file deletion—not only rebuildable caches.

Why This Change Was Made

Persist exact ownership and the removal-time file state independently of the current manifest:

  • Creation records only paths whose exclusive OpenClaw provision copy succeeded. Existing destination collisions remain user-owned and are not mutated or recorded.
  • The live path ledger is stored on the managed-worktree registry row in the shared state database.
  • Before removal, ledger-owned regular ignored untracked files are read through no-follow handles, parent identities and stable file metadata are revalidated, and content is stored in bounded SQLite chunks. A recorded absence preserves deletion.
  • The synthetic Git snapshot excludes those paths so provisioned credentials never enter Git objects. It still captures tracked, staged, untracked, mode-only, assume-unchanged, skip-worktree, sparse-checkout, literal, and raw-byte pathname changes.
  • Restore recreates exact bytes and modes from SQLite without consulting mutable source files or .worktreeinclude, then atomically returns the registry metadata to live-ledger form.
  • Non-forced cleanup fails closed for legacy or malformed ledgers, paths that became tracked or unignored, symlink/type races, and nested repositories. Explicit forced deletion remains the deliberate lossy escape hatch.
  • Unrelated ignored caches remain removable because only files OpenClaw actually provisioned enter the ledger.

This replaces the original manifest-derived guard. Refusing cleanup was insufficient: it left the worktree permanently protected and still made restore depend on mutable source state. A worktree-gitdir sidecar also violated the database-first storage contract and would disappear with the worktree.

User Impact

Manifest removal, pattern removal, or source-file rotation no longer orphan provisioned ignored state. Automatic cleanup can still reclaim rebuildable ignored caches, while restorable worktrees round-trip exact OpenClaw-provisioned bytes, deletion state, and modes.

Evidence

  • node scripts/run-vitest.mjs src/agents/worktrees/service.test.ts src/agents/worktrees/service.provisioned.test.ts src/agents/worktrees/registry.test.ts — 57 passed locally; one Linux-only invalid-UTF-8 pathname case skipped on macOS.
  • node scripts/generate-kysely-types.mjs --verify — passed.
  • node scripts/check-changed.mjs -- <12 touched paths> — full changed gate passed on Blacksmith Testbox, including Linux core/test typechecks, full core lint, formatting, storage guards, and generated-schema validation: https://github.com/openclaw/openclaw/actions/runs/29502236569
  • git diff --check — passed.
  • Mandatory autoreview — all accepted/actionable findings resolved. Raw Git path bytes and stale skip-worktree behavior gained regressions during review.

The focused suite covers manifest and pattern removal, post-removal source mutation, large chunked content, deletion and full modes, destination collisions, legacy/malformed metadata, tracked/unignored/type/symlink fail-closed cases, literal and raw Git paths, assume-unchanged and sparse/skip-worktree state, nested repositories, failed-snapshot cleanup, idle GC, and count/size eviction.

No changelog edit per maintainer instruction; contributor credit is preserved in the commit trailer and squash metadata.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 15, 2026
@yetval
yetval marked this pull request as ready for review July 15, 2026 17:20
@harjothkhara

Copy link
Copy Markdown
Contributor

One remaining lossless gap: this needs to compare the provisioned file's metadata/type, not only its bytes.

copyIncludedFiles() treats mode as part of the restorable state: it lstats the source, accepts only a regular non-symlink, copies it, and then applies sourceStat.mode (src/agents/worktrees/service.ts:198-208). The new guard instead uses readFile() on both sides (:239-246). On POSIX, changing only the managed copy's mode (for example source 0644, worktree 0755) leaves git status --porcelain clean and the bytes equal, so removeIfLossless()/GC still removes the worktree. Restore then reprovisions the source's 0644 mode, losing the worktree-local executable bit. Replacing the managed copy with a symlink whose target has the same bytes is also missed because readFile() follows it, while restore recreates a regular file.

Please lstat both paths and treat a type/symlink or relevant permission-bit difference as unrestorable, with a regression test that chmods the provisioned worktree copy while leaving the source mode unchanged and expects removeIfLossless() to return false. The content comparison and its placement in both run-end and GC paths otherwise look like the right owner-boundary fix; exact-head CI is green.

@yetval

yetval commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

@harjothkhara Thanks — good catch. Addressed in ece303f85f.

The lossless guard now lstat()s both sides, requires regular files through non-symlink parent chains, compares the restorable permission bits, and only then compares bytes. Stat/read failures also fail closed instead of silently treating the worktree copy as safe.

Added POSIX regression coverage for:

  • source 0644 / worktree 0755 with identical bytes;
  • a worktree copy replaced by a same-content symlink;
  • a source baseline replaced by a same-content symlink.

Each case leaves git status --porcelain clean and now expects removeIfLossless() to return false while preserving the worktree state. Exact-head test-types and Real behavior proof are green; the remaining CI matrix is still settling, and I will refresh the PR Evidence section with the final exact-head results.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 16, 2026
@clawsweeper

clawsweeper Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed July 15, 2026, 11:34 PM ET / July 16, 2026, 03:34 UTC.

Summary
The PR adds a guard to run-end and automatic managed-worktree cleanup that compares .worktreeinclude-matched ignored files against the source checkout and preserves worktrees when content, type, permissions, or readability diverge.

PR surface: Source +70, Tests +92. Total +162 across 2 files.

Reproducibility: yes. The PR supplies a concrete real-service reproduction where only an ignored provisioned file changes, tracked status remains clean, baseline removal destroys the new value, and the patched head preserves it.

Review metrics: 1 noteworthy metric.

  • Automatic cleanup decisions: 2 gates changed. The invariant controls both run-end lossless deletion and idle/count/size eviction, so one matching gap reaches every automatic removal path.

Stored data model
Persistent data-model change detected: persistent cache schema: src/agents/worktrees/service.test.ts, serialized state: src/agents/worktrees/service.test.ts, vector/embedding metadata: src/agents/worktrees/service.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: canonical
Canonical: #108401
Summary: This PR is the canonical fix candidate for ignored provisioned-state deletion; the related orphan-adoption PR touches the same service but addresses a separate create-time crash window.

Members:

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

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Add manifest-removal and pattern-removal regressions using the real service.
  • Make the protected file set survive source-manifest drift while leaving unrelated ignored caches eligible for cleanup.

Risk before merge

  • [P1] The current patch still permits permanent deletion when the source .worktreeinclude changes or disappears after an ignored file was provisioned.
  • [P1] The fail-closed guard can protect additional worktrees, allowing configured count or size limits to remain exceeded until explicit operator cleanup.

Maintainer options:

  1. Preserve the provisioned set (recommended)
    Before merge, protect files provisioned under the worktree’s effective manifest even when the source manifest later changes or disappears, with focused regression proof.
  2. Narrow the contract explicitly
    Accept the current implementation only if maintainers intentionally define lossless protection around the source manifest’s present contents and document that earlier provisioned files can become unprotected.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Preserve previously provisioned ignored files across source `.worktreeinclude` removal or pattern changes, add real-service regressions for both cases, and keep unrelated ignored caches removable.

Next step before merge

  • [P2] A narrow code-and-regression repair can close the remaining data-loss path without a product or architecture decision.

Security
Cleared: The diff adds local Git enumeration and file comparison without new dependencies, downloads, network access, permissions, secret output, or executable hooks.

Review findings

  • [P1] Preserve files after the source include manifest changes — src/agents/worktrees/service.ts:216-218
Review details

Best possible solution:

Retain or derive the provisioned-file set independently of the source manifest’s current contents, compare that set with the exact state restore can recreate, and cover manifest removal and pattern changes with real-service regressions.

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

Yes. The PR supplies a concrete real-service reproduction where only an ignored provisioned file changes, tracked status remains clean, baseline removal destroys the new value, and the patched head preserves it.

Is this the best way to solve the issue?

No, not yet. The comparison belongs at the cleanup owner boundary, but using only the source checkout’s current include manifest leaves the lossless guarantee incomplete when provisioning rules change after worktree creation.

Full review comments:

  • [P1] Preserve files after the source include manifest changes — src/agents/worktrees/service.ts:216-218
    This guard derives the protected set only from repoRoot/.worktreeinclude at cleanup time. If a file was provisioned, its worktree copy diverges, and the source removes the pattern or manifest, this returns false or skips the path; cleanup can delete the worktree while neither snapshot nor restore retains the unique value. Preserve the effective provisioned set independently of the current source manifest and add regressions for manifest and pattern removal.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 957cc81175a3.

Label changes

Label changes:

  • add P1: The PR addresses a reproducible normal-session path that can silently and permanently delete credentials, local configuration, or other durable ignored state.
  • add merge-risk: 🚨 compatibility: The fail-closed cleanup change can retain additional worktrees and prevent configured cleanup limits from being met without operator action.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body demonstrates after-fix behavior using the actual ManagedWorktreeService, Git worktrees, and SQLite registry, with baseline loss and patched preservation under identical inputs.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body demonstrates after-fix behavior using the actual ManagedWorktreeService, Git worktrees, and SQLite registry, with baseline loss and patched preservation under identical inputs.

Label justifications:

  • P1: The PR addresses a reproducible normal-session path that can silently and permanently delete credentials, local configuration, or other durable ignored state.
  • merge-risk: 🚨 compatibility: The fail-closed cleanup change can retain additional worktrees and prevent configured cleanup limits from being met without operator action.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body demonstrates after-fix behavior using the actual ManagedWorktreeService, Git worktrees, and SQLite registry, with baseline loss and patched preservation under identical inputs.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body demonstrates after-fix behavior using the actual ManagedWorktreeService, Git worktrees, and SQLite registry, with baseline loss and patched preservation under identical inputs.
Evidence reviewed

PR surface:

Source +70, Tests +92. Total +162 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 71 1 +70
Tests 1 92 0 +92
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 163 1 +162

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/agents/worktrees/service.test.ts.
  • [P1] node scripts/check-changed.mjs -- src/agents/worktrees/service.ts src/agents/worktrees/service.test.ts.
  • [P1] ./node_modules/.bin/oxfmt --check src/agents/worktrees/service.ts src/agents/worktrees/service.test.ts.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • harjothkhara: Reviewed this cleanup invariant and identified the metadata and file-type gap addressed by the second commit. (role: reviewer; confidence: medium; files: src/agents/worktrees/service.ts, src/agents/worktrees/service.test.ts)
  • ss251: The adjacent orphan-recovery work traces the same managed-worktree service, provisioning, registry, and cleanup boundaries. (role: adjacent area contributor; confidence: medium; commits: f17ebabee25b; files: src/agents/worktrees/service.ts, src/agents/worktrees/service.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete force-pushed the fix/worktree-ignored-lossless branch from 2fbb2e6 to 2669f4a Compare July 16, 2026 13:53
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XL and removed size: M labels Jul 16, 2026
@steipete

Copy link
Copy Markdown
Contributor

Maintainer rewrite pushed at 89654d8806619e2a6e6e9c032196331fc6da1bbe.

The repair now persists the exact paths OpenClaw provisioned independently of the current manifest, snapshots their bytes, modes, and deletion state into the shared SQLite store before removal, excludes them from Git snapshot objects, and restores without consulting mutable source state. Existing destination collisions and unrelated ignored caches are never claimed.

Proof:

Exact-head PR CI is running after the final leaf-contract cycle fix.

@steipete
steipete merged commit af05f64 into openclaw:main Jul 16, 2026
118 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 17, 2026
…eanup (openclaw#108401)

* fix(worktrees): preserve provisioned cleanup state

Co-authored-by: yetval <[email protected]>

* refactor(worktrees): break provisioned registry cycle

---------

Co-authored-by: Peter Steinberger <[email protected]>
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
…eanup (openclaw#108401)

* fix(worktrees): preserve provisioned cleanup state

Co-authored-by: yetval <[email protected]>

* refactor(worktrees): break provisioned registry cycle

---------

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL 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.

3 participants