Skip to content

feat: expire disposable agent scratch after 24 hours - #193677

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-worktree-scratch-ttl-delete-20260919
Nov 5, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-worktree-scratch-ttl-delete-20260919

Conversation

@steipete

@steipete steipete commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long-lived managed worktrees and project checkouts accumulate disposable agent proof files and runtime coverage directories indefinitely.

User Impact

The existing hourly maintenance pass now deletes .openclaw/tmp entries and runtime node-coverage-* directories after 24 hours, measured from their newest file. Live or queued runs protect their checkout. Recorded artifacts and idle sessions do not protect scratch; save durable outputs elsewhere. Missing scratch artifacts explicitly display file expired (scratch cleaned after 24 h) when listed or opened, including previously issued download links.

This is the release-note context: fixed 24-hour scratch disposal with visible expired-artifact states, without a new configuration option or scheduler.

Why This Change Was Made

Cleanup belongs to the existing worktree maintenance owner. It consumes current run and queue custody, refuses symlinks, streams bounded scans and deletions, resumes directory enumeration across passes, and pauses after each 128 removals. Its receipt/status includes removed entries and logical bytes, live skips, and deferrals. Runtime coverage has no checkout binding; unrelated activity does not indefinitely protect shared temporary coverage.

The smallest complete change includes cleanup, existing-custody integration, and every artifact read/open transport. Production grows by 713 lines for this new lifecycle and its visible outcome; no artifact index, database schema, retention configuration, or independent scheduler is introduced. A 616-line test allocation covers distinct TTL, liveness, boundary, enumeration, pacing, artifact transport/browser regressions, and maintenance/worker-transport fixture coverage. The shared test ceiling is unchanged.

Evidence

The artifact regression fails on the exact parent: after deletion, the original implementation still returns report.txt. The candidate returns the explicit expired state. Focused backend tests, browser tests, and Files/image end-to-end checks exercise listing, preview, metadata, and HTTP 410 downloads. Before/after captures below contain synthetic data only.

Final focused validation passed 130 tests across eight files, with earlier 204-test coverage of unchanged artifact/file/mailbox consumers; the canonical-config correction passed all eight custody tests again. Browser tests passed 5/5, and Files/image expiry end-to-end cases passed. Codex autoreview is clean through P2 for the full patch from 7786241c9ae4 to 93fbc5143e86 its caller/config correction at a0f4a5fb1f1b, and the final CI corrections at 9882d57b72e7.

Initial CI exposed two task-caused gaps: the timer fixture left new scratch custody preparation real, and the strict worker download schema rejected the new boundary-denial reason. Both reproduce locally before correction. The fixture consumers now pass 188 tests across 11 files; all 15 repository download tests pass, including an escaped-scratch denial assertion. The Android job passed all 13 native tests and cleanup verification receipts but returned failure during teardown; its exact failing cleanup command is unresolved and is not classified as inherited. The new-head CI run passed, including both Android variants; the previous teardown failure is not claimed repaired or inherited.

pnpm check:changed completed on the full change and final correction. Production/test/script types, lint, formatting, SQLite worker/dialect/schema guards, and import checks pass. It retains only reproduced, attributed parent failures: 26 forbidden changelog self-attributions introduced by de04fbe0caa9 (#193427), and four unused exports introduced by 56753f7762a7 (#193098) or made unused by the caller move in e0466ffe4d11 (#193057). Both canonical checkers reproduce on exact parent 7786241c9ae407660db2daabb2937f60d73f54ca; these are main regressions, not ignored PR failures. No affected owner or release record is changed here.

The filesystem owner passed six timing, six allocation, and one CPU-profile run on 62,000 real synthetic files totaling 1.181 GB. Every run removed 708.66 MB, preserved fresh/live/outside files, and recorded zero errors. Five warm samples had median wall/CPU 86.112/40.526 seconds, including 29 seconds of intentional pacing; cumulative sampled allocation was 3.030 GB (including collected objects, not retained heap). The absent cleanup baseline reclaimed zero bytes. A/A variation reached 32.2% wall and 19.6% CPU on the shared host, so no speedup or precise throughput claim is made.

A separate real custody qualification used a 37,582,270,464-byte SQLite database with 5,000 populated/indexed sessions and real high-entropy transcript data. It skipped two live/queued worktrees, cleaned four eligible roots, then cleaned the remaining two after release. Across ten samples, 30 preparations plus 180,000 guard checks took median 130.582 ms wall / 189.465 ms process CPU; ten allocation controls measured 50.92 MB cumulative main-thread allocations. This is a combined preparation/check workload, not isolated preparation latency.

Final measurements use APFS. The granted remote host lacked btrfs support, and its lease ended before final-source replay; earlier ext4 results are initial-candidate evidence only. The two owner fixtures are separate, not one combined Gateway or btrfs test. Production btrfs throughput is not established. No production data or deployment was used; synthetic fixtures and the remote lease are cleaned up. Exact-head PR CI run 42098951349 passed at 9882d57b72e734dc9f9fa2895ea2126378e33995, including the required CI and security gates. Merged as 99ba844a3cd59 through the ordinary native workflow, without an admin exception.

Before cleanup: synthetic scratch report

After cleanup: explicit expired artifact state

Opening the expired file explains scratch cleanup

Reuse hourly worktree maintenance with current live and queued checkout custody, bounded streaming deletion, and explicit expired artifact states. Scratch references do not protect files. No new scheduler, config, or database schema.

Allocate 605 regression-test lines for TTL boundaries, live and queued custody, symlink refusal, resumable enumeration, pacing, and expired artifact transport and browser behavior.
@clawsweeper

clawsweeper Bot commented Nov 5, 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 app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Nov 5, 2026
Forward the worktree removal record through the existing pacing benchmark and use the canonical agent entries shape in custody fixtures.
@steipete
steipete marked this pull request as ready for review November 5, 2026 18:58
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T20:01:38.418501Z 9882d57 New commits
ℹ️ 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: a0f4a5fb1f

ℹ️ 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".

isLive: () => isLive(root, ids),
}));
// Coverage has no checkout/run binding; unrelated activity is not a retention veto.
targets.push({ root: os.tmpdir(), kind: "coverage", isLive: () => false });

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 Canonicalize the runtime temp root before admitting coverage cleanup

On macOS installations where os.tmpdir() returns a path under /var/folders, the /var → /private/var system alias makes this coverage target fail every pass: cleanScratch rejects any root whose rootReal differs from path.resolve(target.root). Consequently, expired runtime coverage directories are never cleaned on those installations. Canonicalize the trusted runtime temp root before constructing this target, while retaining symlink rejection for entries inside it.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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:feature Preliminary submission classification; full source review pending. labels Nov 5, 2026
@clawsweeper

clawsweeper Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR expires disposable scratch after 24 hours and explains missing scratch files across artifact and Files transports.

Example: An idle managed checkout contains .openclaw/tmp/proof/report.txt last modified 25 hours ago.

  • Before: The scratch file remains indefinitely.
  • After: Maintenance removes it, and its recorded artifact displays an expired-file explanation.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, coherently owned feature with meaningful supporting tests, but a confirmed platform defect and incomplete upgrade proof prevent readiness.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Disposable proof files and runtime coverage accumulate in long-lived checkouts, while deleted scratch references lack an understandable expiry state.
Reason: The maintainer-authored direction provides bounded storage reclamation without another scheduler or configuration surface.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open: the maintainer-approved cleanup feature is useful, but coverage cleanup fails for aliased macOS temp paths and expiry errors omit recovery guidance.

Priority: P2
Reviewed head: a0f4a5fb1f1b88f09230cc3b6d549a436d58fe7d

Before merge

  • Canonicalize the trusted runtime temp root before cleanup (P2) - When os.tmpdir() returns /var/folders/... on macOS, fs-safe canonicalizes it to /private/var/folders/.... cleanScratch then rejects it because rootReal differs from path.resolve(target.root), so every coverage cleanup pass defers without removing expired directories. Canonicalize the trusted runtime temp root when constructing this target and retain symlink rejection inside it. This independently confirms the existing review comment.
  • Give expired-file errors a recovery action (P3) - Opening a cleaned report displays only “file expired (scratch cleaned after 24 h)”, leaving the user without a next action. The repository requires changed user messages to explain recovery. Keep the compact list label if desired, but make the opening/download error tell users to regenerate the file and save durable output outside scratch.
  • 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

  • [P2] Canonicalize the trusted runtime temp root before cleanup — src/gateway/scratch-maintenance-custody.ts:248
  • [P3] Give expired-file errors a recovery action — src/shared/scratch-expiry.ts:2

Tests

  • Missing end-to-end proof: Supply a latest-stable upgrade run through real Gateway maintenance showing expired scratch removal, live/queued protection, durable-file preservation, and subsequent artifact access.
Agent review details

How this fits together

Gateway worktree maintenance combines registered checkout roots with current run and queue custody, removes eligible scratch through fs-safe, and exposes cleanup receipts and artifact availability to clients.

flowchart TD
  A[Hourly maintenance] --> B[Checkout inventory and run custody]
  B --> C[Bounded scratch cleanup]
  C --> D[Guarded filesystem removal]
  C --> E[Cleanup receipt]
  D --> F[Artifact and Files readers]
  F --> G[Expiry messages and HTTP 410]
Loading

Technical review

Best possible solution:

Retain the existing maintenance architecture, canonicalize the trusted runtime temp root, and provide actionable expiry errors.

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

The macOS failure follows directly from passing an aliased os.tmpdir() path into the canonical-root equality check; no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

Reusing the maintenance scheduler, custody owners, guarded filesystem operations, and existing artifact transports is appropriate; the runtime-root admission needs a focused correction.

Full review comments:

  • [P2] Canonicalize the trusted runtime temp root before cleanup — src/gateway/scratch-maintenance-custody.ts:248
    When os.tmpdir() returns /var/folders/... on macOS, fs-safe canonicalizes it to /private/var/folders/.... cleanScratch then rejects it because rootReal differs from path.resolve(target.root), so every coverage cleanup pass defers without removing expired directories. Canonicalize the trusted runtime temp root when constructing this target and retain symlink rejection inside it. This independently confirms the existing review comment.
    Confidence: 0.99
  • [P3] Give expired-file errors a recovery action — src/shared/scratch-expiry.ts:2
    Opening a cleaned report displays only “file expired (scratch cleaned after 24 h)”, leaving the user without a next action. The repository requires changed user messages to explain recovery. Keep the compact list label if desired, but make the opening/download error tell users to regenerate the file and save durable output outside scratch.
    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 medium; reviewed against bf0d53d5c17a.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/infra/scratch-cleanup.test.ts src/gateway/scratch-maintenance-custody.test.ts
  • pnpm test src/gateway/server-methods/artifacts.test.ts src/gateway/server-methods/sessions-files.test.ts src/gateway/control-ui-assistant-media-metadata.test.ts src/gateway/control-ui-assistant-media-policy.test.ts
  • pnpm check:changed
  • git diff --check

What I checked:

PR surface

Source +707, Tests +605, Docs +2, Other +232. Total +1546 across 33 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 20 744 37 +707
Tests 9 613 8 +605
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 3 234 2 +232
Total 33 1593 47 +1546

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 tests Production +707 lines; tests +605 lines Growth implements cleanup, custody integration, and distinct artifact transports; inspection found no definite unnecessary parallel owner.
New retention default 24 hours; zero new configuration options Existing scratch becomes disposable automatically, including files referenced by idle conversations.

Labels

Label changes:

  • add P2: Useful storage housekeeping with a platform-specific cleanup defect and limited user-facing recovery friction.
  • add merge-risk: 🚨 compatibility: The intentionally accepted default deletes pre-existing scratch even when conversations reference it; upgrade preservation evidence remains necessary.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Useful storage housekeeping with a platform-specific cleanup defect and limited user-facing recovery friction.
  • merge-risk: 🚨 compatibility: The intentionally accepted default deletes pre-existing scratch even when conversations reference it; upgrade preservation evidence remains necessary.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • 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 5, 2026, 2:24 PM ET / 19:24 UTC.

Keep the strict worker download result aligned with its producer and preserve boundary denials for escaped scratch paths. Isolate scratch custody in the existing worker-free maintenance fixture. Existing regressions reproduce red before correction; all 203 affected tests pass after correction.
@steipete
steipete merged commit 99ba844 into main Nov 5, 2026
164 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-scratch-ttl-delete-20260919 branch November 5, 2026 21:05
@steipete

steipete commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 6, 2026
* feat: expire disposable agent scratch after 24 hours

Reuse hourly worktree maintenance with current live and queued checkout custody, bounded streaming deletion, and explicit expired artifact states. Scratch references do not protect files. No new scheduler, config, or database schema.

Allocate 605 regression-test lines for TTL boundaries, live and queued custody, symlink refusal, resumable enumeration, pacing, and expired artifact transport and browser behavior.

* fix: align scratch maintenance validation callers

Forward the worktree removal record through the existing pacing benchmark and use the canonical agent entries shape in custody fixtures.

* fix: preserve scratch download boundary reasons across workers

Keep the strict worker download result aligned with its producer and preserve boundary denials for escaped scratch paths. Isolate scratch custody in the existing worker-free maintenance fixture. Existing regressions reproduce red before correction; all 203 affected tests pass after correction.
wangmiao0668000666 pushed a commit to wangmiao0668000666/openclaw that referenced this pull request Nov 6, 2026
* feat: expire disposable agent scratch after 24 hours

Reuse hourly worktree maintenance with current live and queued checkout custody, bounded streaming deletion, and explicit expired artifact states. Scratch references do not protect files. No new scheduler, config, or database schema.

Allocate 605 regression-test lines for TTL boundaries, live and queued custody, symlink refusal, resumable enumeration, pacing, and expired artifact transport and browser behavior.

* fix: align scratch maintenance validation callers

Forward the worktree removal record through the existing pacing benchmark and use the canonical agent entries shape in custody fixtures.

* fix: preserve scratch download boundary reasons across workers

Keep the strict worker download result aligned with its producer and preserve boundary denials for escaped scratch paths. Isolate scratch custody in the existing worker-free maintenance fixture. Existing regressions reproduce red before correction; all 203 affected tests pass after correction.
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
* fix: keep agent temporary files in owned scratch

* fix: preserve sandbox temp access and queued isolation custody

(cherry picked from commit f91bc99)

Release adaptation: keep the staged #202815 Git shim implementation and independently assert both Git shim execution and writable owned temp in its merged Docker/Podman fixture. Use the beta.3 isolated custody configuration (896f33d52174), not ambient sandbox inventory.

Companions: #193677 scratch expiry owner is present (99ba844); #202815 is present-equivalent (7d33d1a). #202122 is independent Git/scratch clone reclamation, #202428 is CLI history ownership, #202644 is host file-write authority, and #202874 is workspace cleanup scheduling; none prerequisite. Other later same-path commits concern separate template, sandbox, prompt, sharing, or run-lifecycle policy; see the lane companion audit.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a4070bc5b669308210b62a0b80b92c16af768b34)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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: 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.

1 participant