Skip to content

fix(claws): preserve active and shared agent data during removal - #138693

Merged
steipete merged 3 commits into
mainfrom
codex/team-agent-delete-lease-audit-20260904
Sep 5, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/team-agent-delete-lease-audit-20260904

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Claw removal could commit config and remove directories while another process still held an agent database. It also used incomplete ownership information for retained directories. Share the existing Gateway deletion preparation with Claw and offline CLI removal: fence new claims, close only the deleted agent's actual registered handles, and reject active leases before config, approvals, MCP, cron, or filesystem effects. Retain directories containing surviving database owners, including closed databases with older or newer schemas.

Why This Change Was Made

Session cleanup needs the same deletion owner across its awaited purge and transcript archive work. An ordinary reopen after claiming the deletion journal correctly refuses access, which previously left retained databases unpurged while removal reported completion. The deletion owner now provides a scoped cleanup operation bound to its live closure, exact unfinished journal, state database, and physical store owner/path. Connections opened by that scope stay private to it, remain borrowed across awaits, and close before the operation settles. Ordinary callers, stale callbacks, foreign journal rows, and overlapping foreign leases retain their existing fences. Preexisting surviving shared-store connections retain their ordinary ownership, and cleanup removes only the deleted agent's rows.

User Impact

Failed session cleanup or archive export now keeps the deletion journal unfinished. Claw reports a partial result and supports preview/retry; Gateway and offline CLI retain purgeFailed and defer filesystem cleanup and completion. Creation provenance is removed only when the exact deletion operation successfully completes. The canonical shared directory check replaces the CLI's duplicate retention rules, and Claw's repeated partial-result construction is consolidated.

Evidence

Validation: original config-file and two-process reproductions are preserved; the final owner suite passes 325 tests with six existing platform skips across nine files. Coverage includes real postcommit archive publication failure and retry, active foreign child leases, relocated paths, closed foreign databases, stale registry/schema information, warm/cold shared stores, replacement/rollback/completion retirement, retained callbacks and aliases, and exact failed-close retry with the original operation error preserved. A fresh built standalone CLI run removed the target agent/session while preserving a foreign database and its surviving session. Final source hashes are checked before and after remote execution. The final extracted source passed the fresh standalone CLI build and all nine suites with identical hashes before, after CLI execution, and after the suites. The full changed-code gate passed on Linux (Node 24.19.0, pnpm 12.1.0) in 863.851 seconds on Testbox run https://github.com/openclaw/openclaw/actions/runs/33939598362. Fresh independent P2 review found no actionable findings. An earlier gate failed with corepack ENOENT while its runner was being cancelled; the cause of the missing binary was not established. The unchanged gate passed on a newly acquired matching lease. The final command succeeded before a runner-portal synchronization warning.

The review's retained-session purge finding and associated coverage requests are addressed by the scoped owner and real archive retry proof. The contract type move does not change a database schema or stored representation. No schema version, migration, configuration, dependency, or public RPC change; no changelog edit.
Production changes are +873/-498 (net +375); tests and test support are +855/-40 (net +815); docs are +11. Planner/type moves add no capability. The remaining production growth supplies the missing exact cleanup lifetime and handle isolation across awaited archive work. It reuses the journal, existing native borrower/close owner, existing path matcher, and lease fence; the duplicated Gateway/CLI retention rules and repeated Claw partial-result branches were removed. No global maintenance bypass or second deletion registry was introduced.

Hosted CI on the preceding head exposed two additional structural issues: the merged database owner exceeded the 700-line lint limit, and Madge counted a type-only registry cycle that the runtime-value check excludes. The repair removes the type dependency by taking the existing matcher signature and absorbs the one-use slow-open logger at its original call site. The actual merged-source lint now passes (the same pre-fix merge reproduces the failure), both cycle guards pass, scoped typed lint passes, and a fresh independent P2 review found no actionable findings. Cleanup and native-close behavior are unchanged by this follow-up.

Final head 24f56c0341ba039c58ef9a773b58c73a38586690 passed CI attempt 2, including openclaw/ci-gate. Attempt 1 failed only while downloading the Matrix crypto native dependency (ECONNRESET before the boundary check); the normal targeted retry passed.

The latest ClawSweeper review confirms the retained-session finding and both rank-up requests are addressed. Its remaining compatibility reminder is accepted: active database owners must release their handles, and callers must retry an unfinished deletion rather than recreate over it. This is documented and covered by refusal/retry tests. The flagged lifecycle and cleanup additions are process-local closures, AsyncLocalStorage, and handle maps; no serialized field, schema version, migration, or stored representation changes, so a data migration is not applicable.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. labels Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 11:06 PM ET / September 5, 2026, 03:06 UTC.

ClawSweeper review

What this changes

Makes Claw, Gateway, and offline agent removal preserve active or shared databases and retain retryable cleanup state when session cleanup fails.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains a useful repair absent from current main. The previous retained-session purge finding is addressed, and no new blocking correctness defect was found.

Priority: P2
Reviewed head: d725e9d42f42d0aa2641f0040e9ad02c9062183b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-boundary repair with meaningful regression coverage and the previous blocker addressed.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary contributor-proof gate does not apply to this maintainer-authored PR, and no unresolved authority-chain violation was identified. The captured body reports the changed CLI deletion flow preserving foreign data; linked execution logs were unreachable from this reviewer.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary contributor-proof gate does not apply to this maintainer-authored PR, and no unresolved authority-chain violation was identified. The captured body reports the changed CLI deletion flow preserving foreign data; linked execution logs were unreachable from this reviewer.
Evidence reviewed 10 items Pinned change and clean checkout: Verified HEAD matches the supplied original PR head. Reviewed the merge-base-to-head changes; git diff --check passed and git status --short remained empty. The stale test merge was not used to infer removal of main-branch behavior.
Current main still needs the repair: Current main invokes the purge without deletion-owned access and ignores its failure result before continuing cleanup. The inspected Claw removal and deletion-journal files are unchanged from the PR merge base.
Latest-release comparison: The verified v2026.9.1 tag contains the earlier Claw config-removal flow without the new database-lease preparation.
Findings None None.
Security None None.

How this fits together

Agent removal coordinates configuration, execution approvals, session databases, and filesystem cleanup. Its deletion journal prevents recreation while cleanup is unfinished and distinguishes the removed agent’s data from surviving agents’ data.

flowchart TD
  A[Claw or agent removal] --> B[Claim deletion journal]
  B --> C[Check database owners and leases]
  C -->|Active holder| D[Refuse before removal]
  C -->|Safe| E[Remove configuration and purge sessions]
  E -->|Cleanup fails| F[Retain journal for retry]
  E -->|Cleanup succeeds| G[Preserve shared paths and complete deletion]
Loading

Before merge

  • Resolve merge risk (P1) - Existing removal scripts that assume immediate completion may need to handle active-database refusals and retry unfinished cleanup before recreating the agent.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +388, Tests +811, Docs +11, Other +4. Total +1214 across 28 files.

View PR surface stats
Area Files Added Removed Net
Source 17 865 477 +388
Tests 9 850 39 +811
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 1 5 1 +4
Total 28 1731 517 +1214

Review metrics

Metric Value Why it matters
Production versus test growth Production +388 net; tests and test support +815 net; docs +11 Planner and type moves are neutral overall; remaining production growth adds the missing cleanup lifetime and private-handle ownership while removing duplicate retention logic.

Stored data model

Persistent data-model change detected: serialized state: src/agents/agent-lifecycle-registry.ts, serialized state: src/state/agent-deletion-cleanup.ts, unknown-data-model-change: src/agents/agent-lifecycle-registry.ts, unknown-data-model-change: src/state/agent-deletion-cleanup.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the documented stop-and-retry behavior (recommended)
    Retain the intentional refusal and partial-cleanup outcomes so active or surviving agent data cannot be discarded to complete removal.

Technical review

Best possible solution:

Keep the shared planner and journal-owned cleanup with documented retry recovery; the private handle lifetime justifies the remaining production growth without changing the stored schema.

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

Yes, from source: current main lacks Claw’s pre-effect lease check and ignores purge failure before continuing cleanup. The branch contains focused two-process and populated-store regressions; this review did not execute them.

Is this the best way to solve the issue?

Yes: extending the existing deletion journal and database lifecycle repairs the owning boundary across all three callers. Moving purge ahead of the fence or introducing a global maintenance bypass would weaken isolation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 790fbf0304a6.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary contributor-proof gate does not apply to this maintainer-authored PR, and no unresolved authority-chain violation was identified. The captured body reports the changed CLI deletion flow preserving foreign data; linked execution logs were unreachable from this reviewer.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repairs a concrete, bounded agent-removal safety problem without evidence of an ongoing widespread outage.
  • merge-risk: 🚨 compatibility: Removal now refuses active database holders and preserves unfinished cleanup instead of allowing callers to treat every config removal as complete.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary contributor-proof gate does not apply to this maintainer-authored PR, and no unresolved authority-chain violation was identified. The captured body reports the changed CLI deletion flow preserving foreign data; linked execution logs were unreachable from this reviewer.

Evidence

What I checked:

  • Pinned change and clean checkout: Verified HEAD matches the supplied original PR head. Reviewed the merge-base-to-head changes; git diff --check passed and git status --short remained empty. The stale test merge was not used to infer removal of main-branch behavior. (d725e9d42f42)
  • Current main still needs the repair: Current main invokes the purge without deletion-owned access and ignores its failure result before continuing cleanup. The inspected Claw removal and deletion-journal files are unchanged from the PR merge base. (src/claws/lifecycle-state.ts:611, 790fbf0304a6)
  • Latest-release comparison: The verified v2026.9.1 tag contains the earlier Claw config-removal flow without the new database-lease preparation. (src/claws/lifecycle-config-removal.ts:163, ad6fe23aecb9)
  • Preflight precedes removal effects: Claw claims the journal and prepares database deletion before entering MCP, cron, approvals, or config-removal work. The shared planner refreshes all registered database owners, includes incompatible-schema registrations, and closes only handles belonging to the removed agent. (src/claws/lifecycle-config-removal.ts:209, d725e9d42f42)
  • Previous finding resolved: Claw now passes runDatabaseCleanup into the real purge and returns session_cleanup_failed before filesystem cleanup when it fails. Gateway and offline CLI pass the same owner and defer filesystem deletion and journal completion on purgeFailed, addressing both retained rank-up moves. (src/claws/lifecycle-state.ts:583, d725e9d42f42)
  • Cleanup authority reaches the write boundary: The cleanup scope checks its live closure, exact unfinished journal operation, state database, and target. Database transactions revalidate access before mutation; foreign deletion rows and overlapping foreign leases remain fenced. This path is OpenClaw-owned Node/SQLite code and supplies no affirmative Codex runtime or protocol dependency. (src/state/openclaw-agent-db.ts:497, d725e9d42f42)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Leon-SK668: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

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

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-05T00:01:23.205Z sha 6e217f8 :: blocked before merge. :: [P2] Keep retained-store session purge inside deletion ownership
  • reviewed September 4, 2026, 8:44 PM ET / September 5, 2026, 00:44 UTC sha unknown :: blocked before merge. :: [P2] Keep retained-store session purge inside deletion ownership

@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Sep 5, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 5, 2026
@steipete
steipete merged commit cf127a3 into main Sep 5, 2026
303 of 305 checks passed
@steipete
steipete deleted the codex/team-agent-delete-lease-audit-20260904 branch September 5, 2026 03:32
@steipete

steipete commented Sep 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 Sep 5, 2026
…nclaw#138693)

* fix(claws): preserve active and shared agent data during removal

* fix(agents): keep session cleanup within deletion ownership

* refactor(state): remove deletion cleanup type cycle
vincentkoc added a commit to LiuwqGit/openclaw that referenced this pull request Sep 5, 2026
* commit 'cf127a39cb97ff5c3c2dfe8d4b37bc9dee9470e8':
  fix(claws): preserve active and shared agent data during removal (openclaw#138693)
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 gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant