Skip to content

fix(agents): let agents delete retire an unconfigured but registered agent - #207257

Merged
obviyus merged 2 commits into
mainfrom
core/agents-delete-retired
Nov 28, 2026
Merged

obviyus merged 2 commits into
mainfrom
core/agents-delete-retired

Conversation

@obviyus

@obviyus obviyus commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

What problem this solves

Fixes #205927 (with #207212, which stopped maintenance from recreating the deleted directory).

An agent removed from agents.entries by hand, whose directory was then deleted as Doctor advised, keeps its row in the shared agent-database registry. openclaw doctor then prints Skipped missing registered agent database … on every run, and no supported command can clear it: openclaw agents delete <id> answered "not found" because the agent is not configured and has no deletion record.

Doctor deliberately does not drop a registration just because its file is missing (#203130: the startup upgrade copies state without databases over 64 MiB, so that rule deleted real registrations). The removal therefore belongs to explicit agent deletion.

Change

  • openclaw agents delete <id> and the Gateway agents.delete method accept an agent that is not in config but still has a registered database. They run the existing journaled deletion: paths that are already gone are skipped, the registrations are removed with the journal, and config is not written. Confirmation and --force behave as for any delete.
  • If any of the agent's paths still exist, the confirmation lists them before anything moves to Trash.
  • Doctor's Skipped missing registered agent database warning names openclaw agents delete <id> for unconfigured, non-reserved agents. A configured agent's missing database (the upgrade-shadow case) keeps the old text. The orphan-directory note names the same command instead of "remove stale dirs".
  • An id with no config entry, deletion record or registration is still "not found". Nothing happens automatically: no config edit, Doctor run or maintenance cycle removes a registration.

Update behavior

Doctor wording only; no migration, schema, stored row or update-path change.

User population

Gateway and CLI installs that retired an agent by removing it from config and deleting its directory. Two reporters on #205927.

Evidence

  • src/commands/agents.delete.test.ts "retires an unconfigured agent that is still registered":

    • files gone: Doctor's state migration reports the missing store on two runs, agents delete retired --force exits 0, the registration is gone, the deletion journal is complete, then two Doctor runs are silent. Red on main fe1e8208 (no command pointer; delete answers "not found").
    • directory remains: the confirmation lists the existing agent directory; cancelling changes nothing; confirming moves it to Trash and removes the registration. Red on main (no prompt is reached: "not found").
    • unknown id with no config entry, record or registration: still "not found".
  • Guards green: state-upgrade.large-agent-db.test.ts (fix(state): keep large agent databases registered across startup upgrades #203130: a database omitted from the upgrade copy keeps its registration), state-migrations.media-persistence-targets.test.ts, agent-deletion-journal-initialization.test.ts, doctor-state-integrity.test.ts, and the Gateway agents-delete integration, upgrade and drain suites.

  • Real Gateway, isolated (own port, empty HOME and state, env -i). Configure main and retired, start and stop the Gateway, remove retired from config and delete its directory, start the Gateway, then run the CLI against it:

    main fe1e8208
      doctor: Skipped missing registered agent database <state>/agents/retired/agent/openclaw-agent.sqlite.
      openclaw agents delete retired --force -> exit 1: Agent "retired" not found. Run openclaw agents list to see configured agents.
      doctor x2 afterwards: warning on every run; registry rows: main,retired
    this PR 53a60cd2
      doctor: Skipped missing registered agent database <state>/agents/retired/agent/openclaw-agent.sqlite. If agent "retired" is retired, run openclaw agents delete retired to remove its registration.
      openclaw agents delete retired --force -> exit 0: Deleted agent: retired   (Gateway log: agents.delete ✓)
      doctor x2 afterwards, same Gateway still running, no restart: no warning; registry rows: main
    upgrade: state created by v2026.11.10 (latest stable), then this PR: same result as above
    

Accepted edge cases

  • A completed keep-files deletion whose files remain can be deleted again, this time with its files (moved to Trash; the confirmation lists them).
  • agents delete does not refuse a store Doctor holds back after a lost deletion journal; Doctor still prints its restore-first guidance.
  • If the registration points at a database on an unmounted volume, the confirmation says none of the agent's files were found on disk; deletion removes only the registration.

Final head 1c7963b9 (53a60cd2 with main merged in, to pick up the protocol-allowlist fix from #207259). On that build, the same isolated-Gateway run again: Doctor warns before the delete; agents delete retired --force runs through the running Gateway; doctor and status are then silent on two runs each, without a restart; the registry holds main only; the directory stays absent. Local review on 1c7963b9: patch is correct, 0 findings.

…agent

- CLI agents delete and Gateway agents.delete accept an agent absent from config that still has a registered database, and run the existing journaled deletion; gone paths are skipped and the registration is removed.
- The confirmation lists any of the agent's paths that still exist before anything moves to Trash.
- Doctor's missing-registration warning and orphan-directory note name openclaw agents delete <id>.

Fixes #205927
@clawsweeper

clawsweeper Bot commented Nov 28, 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 commands Command implementations agents Agent runtime and tooling size: S labels Nov 28, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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. labels Nov 28, 2026
@clawsweeper

clawsweeper Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR lets explicit agent deletion retire database registrations for agents already removed from config and updates Doctor’s cleanup guidance.

Example: Agent retired is absent from agents.entries, its directory is gone, and its database registration remains.

  • Before: openclaw agents delete retired reports not found, while Doctor repeatedly warns about the missing database.
  • After: Explicit deletion accepts retired and uses the existing deletion journal to remove its registration.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful and narrowly scoped, with one concrete transport inconsistency and no required real-behavior or upgrade proof.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Operators cannot finish retiring an agent after removing its config entry and directory, so Doctor keeps reporting its stale registration.
Reason: The maintainer-authored direction supplies the missing explicit cleanup operation while respecting intentional registration retention.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this maintainer-authored PR addresses a confirmed retirement gap, but its Gateway path still changes config despite the promised preservation.

Reviewed head: 53a60cd2e225bc53cee0632a60f50487604d6dbb

Before merge

  • [P2] Skip config mutation when retiring an unconfigured agent (P2) - The new eligibility check lets an agent absent from config, with a registration and no deletion journal, reach the unconditional deleteAgentConfigEntry call at line 337. That helper still runs pruneAgentConfig and commits through mutateConfigFileWithRetry before returning undefined for the missing entry. For example, a surviving agent’s subagents.allowAgents entry naming retired is removed through the Gateway, while offline deletion leaves it intact. This contradicts the promised no-config-write behavior and makes retirement depend on the transport. Skip config publication for this newly admitted case and retain the existing journaled cleanup.
  • 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] [P2] Skip config mutation when retiring an unconfigured agent — src/gateway/server-methods/agents-delete.ts:184-185
Agent review details

How this fits together

The CLI and Gateway deletion entry points feed the existing agent lifecycle owner, which journals retirement, drains work, cleans storage, and removes database registrations; Doctor discovers remaining registrations and reports recovery guidance.

flowchart TD
  A[Operator deletion request] --> B[CLI or Gateway]
  B --> C[Config and database registry]
  C --> D[Journaled deletion owner]
  D --> E[Drain work and clean files]
  E --> F[Remove registration and finish journal]
  C --> G[Doctor diagnostics]
Loading

Technical review

Best possible solution:

Keep the existing journaled deletion owner and make retirement of an already-unconfigured agent preserve config through both transports.

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

The linked release report and current-main rejection establish the original gap; source tracing also establishes the Gateway config mutation, but no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

Extending explicit deletion is appropriate because file absence cannot authorize automatic deregistration; the remaining repair belongs in the existing Gateway deletion flow.

Full review comments:

  • [P2] [P2] Skip config mutation when retiring an unconfigured agent — src/gateway/server-methods/agents-delete.ts:184-185
    The new eligibility check lets an agent absent from config, with a registration and no deletion journal, reach the unconditional deleteAgentConfigEntry call at line 337. That helper still runs pruneAgentConfig and commits through mutateConfigFileWithRetry before returning undefined for the missing entry. For example, a surviving agent’s subagents.allowAgents entry naming retired is removed through the Gateway, while offline deletion leaves it intact. This contradicts the promised no-config-write behavior and makes retirement depend on the transport. Skip config publication for this newly admitted case and retain the existing journaled cleanup.
    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 672a898d07e4.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/commands/agents.delete.test.ts src/infra/state-migrations.media-persistence-targets.test.ts
  • pnpm test --config test/vitest/vitest.gateway.config.ts src/gateway/server-methods/agents-mutate.test.ts
  • Demonstrate the config-preservation regression failing before the repair and passing afterward.
  • Verify CLI and Gateway retirement after upgrading copied v2026.11.10 state, preserving survivor settings and data.

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 24d5996 adds src/agents/agent-delete-databases.ts:84 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 24d599636ab2; files: src/agents/agent-delete-databases.ts)
  • Ayaan Zaidi: Raw commit c2af38c adds src/infra/state-migrations.media-persistence-targets.ts:274 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c2af38cdbd7d; files: src/infra/state-migrations.media-persistence-targets.ts)

PR surface

Source +52, Tests +68, Docs +1. Total +121 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 68 16 +52
Tests 2 69 1 +68
Docs 2 3 2 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 140 19 +121

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.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #205927
Summary: This PR addresses registration retirement left outstanding after the directory-recreation repair.

Members:

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

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: Gateway retirement can prune stored references and rewrite config that the offline path preserves.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab 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:

  • merge-risk: 🚨 compatibility: Gateway retirement can prune stored references and rewrite config that the offline path preserves.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab 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 28, 2026, 12:23 AM ET / 05:23 UTC.

@obviyus

obviyus commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

No override was used; landed after merging main with green CI.

@obviyus
obviyus merged commit 98b9f17 into main Nov 28, 2026
135 checks passed
@obviyus
obviyus deleted the core/agents-delete-retired branch November 28, 2026 06:11
obviyus added a commit that referenced this pull request Nov 28, 2026
…ld store (#207290)

## What problem this solves

Follow-up to #207257. After deletion history is lost, Doctor holds back some agent stores and tells the operator to restore them first (`openclaw agents add … to abort deletion and restore`). `openclaw agents delete` on such an agent asked a plain "Delete agent?" with no hint of that, so a held store could be deleted without the user ever seeing Doctor's advice.

## Change

- Doctor's per-store restore-first guidance moved, unchanged, into `formatHeldAgentStoreGuidance` (`src/commands/doctor-agent-deletion-held.ts`). Doctor's journal repair calls it; nothing else formats it.
- `agents delete` reads Doctor's recorded recovery holds (`readAgentDeletionRecoveryHoldsInWorker`, the same record `agents add` checks). For each held store of the agent:
  - Interactive: the confirmation starts with `Warning: Doctor holds back a store of agent "<id>" because its deletion history was lost. Continuing deletes it without restoration:`, then Doctor's guidance, then the usual question.
  - `--force`: the same warning is printed to stderr and deletion proceeds. `--json` stdout is unchanged.
- Agents without a hold keep the ordinary confirmation.

Gateway: the CLI confirms locally before it calls the Gateway's `agents.delete`, so both CLI transports (through the Gateway and offline) show the warning. The Gateway method has no confirmation of its own.

## Not covered: Control UI

The Control UI delete dialog does not show the held-store warning. The UI has no hold state on the wire, and adding a protocol field for it is deliberately parked (decision D56): the UI lists only configured agents while holds are mostly on unconfigured stores, deletion moves files to Trash, and Doctor already prints the restore-first guidance. Reopen if a real report shows a Control UI user deleting a held store.

## User population

CLI users deleting an agent whose store Doctor holds back after a lost or unusable deletion journal.

## Evidence

- `agents.delete.test.ts` "shows Doctor's restore-first warning for a held store before confirming": a registered `retired` store, a reconstructed deletion journal that holds it, then `agents delete retired`.
  - Interactive: the confirmation contains `Doctor holds back a store of agent "retired"` and Doctor's `openclaw agents add 'retired' … to abort deletion and restore`; cancelling changes nothing. The configured `ops` agent (no hold) keeps `Delete agent "ops" and prune workspace/state?`.
  - `--force --json`: stderr carries the same warning; deletion proceeds and the registration is removed.
  - Red on main `98b9f17b`: the confirmation has no warning.
- `doctor-agent-deletion-journal.test.ts` and the rest of `agents.delete.test.ts` stay green (40 tests): Doctor's held-store text is byte-identical after the move.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 28, 2026
…207438)

## What problem this solves

Follow-up to #207257 (fixes the `server.agents.config-readiness` "publishes overlapping mutations from two operators" failure on main, bisected to #207257: parent 3/3 pass, #207257 3/3 fail).

#207257 made `agents.delete` accept a retired agent: not in config, still in the agent-database registry. A keep-files deletion (`deleteFiles: false`) keeps that registration. So after it completes, the agent is retired and has a completed deletion record that holds its real paths.

A second delete of that agent then went wrong in both owners:

- `deleteFiles: false` again (a concurrent loser behind the deletion lease, or any later repeat): it claimed the completed record and began a new one with paths re-resolved from config. Config no longer has the agent, so these were the default paths (`<state>/workspace-<id>`), not the agent's. It then ran drain, cron removal, exec-approval removal and a config write again.
- `deleteFiles: true` (the CLI always sends this; #207257 accepted edge 1, "a completed keep-files deletion whose files remain can be deleted again, this time with its files"): it moved `<state>/workspace-<id>` to Trash and left the agent's real custom workspace in place. The CLI prompt listed the default paths, not the kept ones.

## Change

- Gateway `agents.delete` (`src/gateway/server-methods/agents-delete.ts`): for a retired agent with a completed deletion record,
  - `deleteFiles: false` returns `ok` with `removed: []`, `failed: []`. It does not claim the record, begin a journal, or run drain, cron, exec-approval or config steps.
  - `deleteFiles: true` runs the normal journaled deletion on the paths from the completed record, never re-resolved from config.
- CLI local fallback (`src/commands/agents.commands.delete.ts`): the same path choice, so the confirmation and the deletion name the recorded paths.
- The `agents.delete` handler waits for a config-application receipt and reports "saved but not confirmed (unclaimed)" when no write claimed it. The no-op writes no config, so it settles that receipt as `applied` itself (`getRuntimeConfigWriteApplication(...).claim()?.settle("applied")`). Today only the config reloader settles receipts; this is the one other settler, and it is used only when nothing was written.

The surviving-agent check before Trash (`unclaimedBySurvivor` against the next config) is unchanged and now runs against the recorded path.

## User population

Gateway and CLI installs that delete an agent with "keep files" (Control UI or `agents.delete {deleteFiles:false}`) and then delete it again, or delete it with its files later. Both routes: Gateway RPC (`agents-delete.ts`) and the CLI offline fallback (`agents.commands.delete.ts`).

## Impact on main (unreleased)

#207257 is on main only (not in a release). Measured in a real Gateway on main `ca6d4ca7` (test below, with probes):

- Keep-files repeat: the completed record was replaced by one with default paths. The registration, a seeded peer agent (config, workspace, session) and a file seeded at `<state>/workspace-<id>` were untouched. From code: cron removal and exec-approval removal filter by the deleted agent's id; the config write with `allowMissing` prunes only that id's bindings/allow entries. Nothing of another agent changed.
- With-files re-delete after that: `removed` held `<state>/workspace-repeat-keep-files` (method `trash`), the seeded default-path file was gone (in Trash, recoverable), and the real custom workspace was still on disk.
- So the irreversible-looking damage is bounded: a wrong directory moved to Trash (recoverable) only when the user re-deletes with files and something exists at `<state>/workspace-<id>`; kept files left behind. No other agent's state was touched.

## Accepted edge cases

- A crash between claiming the completed record and beginning the new journal loses the recorded paths; the next attempt uses default paths. This window existed before and is not widened.
- A completed record can go stale if the id is added to config by hand with another workspace and then removed again by hand (agent creation through the Gateway or CLI claims the record; a hand edit does not). A with-files delete then uses the recorded workspace. Main used the default path here, also wrong.
- A keep-files repeat no longer re-runs cron/exec-approval cleanup for the retired id. `sessions.create` refuses unknown agent ids; before #207257 the same repeat was refused as "not found" with no cleanup at all.

## Evidence

- `src/gateway/server.agents.config-readiness.test.ts` (real Gateway, real stores, no mocks of the delete owner):
  - "publishes overlapping mutations from two operators": the concurrent loser's result is a no-op, the kept workspace and agent dir exist, the winner's record is unchanged, the registration is unchanged.
  - "repeats a completed keep-files deletion as a no-op and later deletes its recorded files": the same four-part contract for a sequential repeat, plus a peer agent and a default-path file left untouched, then a with-files delete trashes the recorded workspace and leaves the default-path file.
  - Red on main `ca6d4ca7` (record replaced: `workspaceDir` = `<state>/workspace-<id>`), green on head.
- `src/commands/agents.delete.test.ts` "deletes the recorded files of a retired agent after a keep-files deletion": own workspace (prompt names it, it goes to Trash, registration removed; red on main, the prompt never names it) and a workspace now used by a surviving agent (not trashed).
- Existing `agents.delete` command suite green, including #207257's retired-agent cases.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
…agent (openclaw#207257)

## What problem this solves

Fixes openclaw#205927 (with openclaw#207212, which stopped maintenance from recreating the deleted directory).

An agent removed from `agents.entries` by hand, whose directory was then deleted as Doctor advised, keeps its row in the shared agent-database registry. `openclaw doctor` then prints `Skipped missing registered agent database …` on every run, and no supported command can clear it: `openclaw agents delete <id>` answered "not found" because the agent is not configured and has no deletion record.

Doctor deliberately does not drop a registration just because its file is missing (openclaw#203130: the startup upgrade copies state without databases over 64 MiB, so that rule deleted real registrations). The removal therefore belongs to explicit agent deletion.

## Change

- `openclaw agents delete <id>` and the Gateway `agents.delete` method accept an agent that is not in config but still has a registered database. They run the existing journaled deletion: paths that are already gone are skipped, the registrations are removed with the journal, and config is not written. Confirmation and `--force` behave as for any delete.
- If any of the agent's paths still exist, the confirmation lists them before anything moves to Trash.
- Doctor's `Skipped missing registered agent database` warning names `openclaw agents delete <id>` for unconfigured, non-reserved agents. A configured agent's missing database (the upgrade-shadow case) keeps the old text. The orphan-directory note names the same command instead of "remove stale dirs".
- An id with no config entry, deletion record or registration is still "not found". Nothing happens automatically: no config edit, Doctor run or maintenance cycle removes a registration.

## Update behavior

Doctor wording only; no migration, schema, stored row or update-path change.

## User population

Gateway and CLI installs that retired an agent by removing it from config and deleting its directory. Two reporters on openclaw#205927.

## Evidence

- `src/commands/agents.delete.test.ts` "retires an unconfigured agent that is still registered":
  - files gone: Doctor's state migration reports the missing store on two runs, `agents delete retired --force` exits 0, the registration is gone, the deletion journal is complete, then two Doctor runs are silent. Red on main `580d6b3b` (no command pointer; delete answers "not found").
  - directory remains: the confirmation lists the existing agent directory; cancelling changes nothing; confirming moves it to Trash and removes the registration. Red on main (no prompt is reached: "not found").
  - unknown id with no config entry, record or registration: still "not found".
- Guards green: `state-upgrade.large-agent-db.test.ts` (openclaw#203130: a database omitted from the upgrade copy keeps its registration), `state-migrations.media-persistence-targets.test.ts`, `agent-deletion-journal-initialization.test.ts`, `doctor-state-integrity.test.ts`, and the Gateway `agents-delete` integration, upgrade and drain suites.
- Real Gateway, isolated (own port, empty HOME and state, `env -i`). Configure `main` and `retired`, start and stop the Gateway, remove `retired` from config and delete its directory, start the Gateway, then run the CLI against it:

  ```text
  main 580d6b3
    doctor: Skipped missing registered agent database <state>/agents/retired/agent/openclaw-agent.sqlite.
    openclaw agents delete retired --force -> exit 1: Agent "retired" not found. Run openclaw agents list to see configured agents.
    doctor x2 afterwards: warning on every run; registry rows: main,retired
  this PR 53a60cd
    doctor: Skipped missing registered agent database <state>/agents/retired/agent/openclaw-agent.sqlite. If agent "retired" is retired, run openclaw agents delete retired to remove its registration.
    openclaw agents delete retired --force -> exit 0: Deleted agent: retired   (Gateway log: agents.delete ✓)
    doctor x2 afterwards, same Gateway still running, no restart: no warning; registry rows: main
  upgrade: state created by v2026.11.10 (latest stable), then this PR: same result as above
  ```

## Accepted edge cases

- A completed keep-files deletion whose files remain can be deleted again, this time with its files (moved to Trash; the confirmation lists them).
- `agents delete` does not refuse a store Doctor holds back after a lost deletion journal; Doctor still prints its restore-first guidance.
- If the registration points at a database on an unmounted volume, the confirmation says none of the agent's files were found on disk; deletion removes only the registration.

Final head `1c7963b9` (`53a60cd2` with `main` merged in, to pick up the protocol-allowlist fix from openclaw#207259). On that build, the same isolated-Gateway run again: Doctor warns before the delete; `agents delete retired --force` runs through the running Gateway; `doctor` and `status` are then silent on two runs each, without a restart; the registry holds `main` only; the directory stays absent. Local review on `1c7963b9`: patch is correct, 0 findings.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
…ld store (openclaw#207290)

## What problem this solves

Follow-up to openclaw#207257. After deletion history is lost, Doctor holds back some agent stores and tells the operator to restore them first (`openclaw agents add … to abort deletion and restore`). `openclaw agents delete` on such an agent asked a plain "Delete agent?" with no hint of that, so a held store could be deleted without the user ever seeing Doctor's advice.

## Change

- Doctor's per-store restore-first guidance moved, unchanged, into `formatHeldAgentStoreGuidance` (`src/commands/doctor-agent-deletion-held.ts`). Doctor's journal repair calls it; nothing else formats it.
- `agents delete` reads Doctor's recorded recovery holds (`readAgentDeletionRecoveryHoldsInWorker`, the same record `agents add` checks). For each held store of the agent:
  - Interactive: the confirmation starts with `Warning: Doctor holds back a store of agent "<id>" because its deletion history was lost. Continuing deletes it without restoration:`, then Doctor's guidance, then the usual question.
  - `--force`: the same warning is printed to stderr and deletion proceeds. `--json` stdout is unchanged.
- Agents without a hold keep the ordinary confirmation.

Gateway: the CLI confirms locally before it calls the Gateway's `agents.delete`, so both CLI transports (through the Gateway and offline) show the warning. The Gateway method has no confirmation of its own.

## Not covered: Control UI

The Control UI delete dialog does not show the held-store warning. The UI has no hold state on the wire, and adding a protocol field for it is deliberately parked (decision D56): the UI lists only configured agents while holds are mostly on unconfigured stores, deletion moves files to Trash, and Doctor already prints the restore-first guidance. Reopen if a real report shows a Control UI user deleting a held store.

## User population

CLI users deleting an agent whose store Doctor holds back after a lost or unusable deletion journal.

## Evidence

- `agents.delete.test.ts` "shows Doctor's restore-first warning for a held store before confirming": a registered `retired` store, a reconstructed deletion journal that holds it, then `agents delete retired`.
  - Interactive: the confirmation contains `Doctor holds back a store of agent "retired"` and Doctor's `openclaw agents add 'retired' … to abort deletion and restore`; cancelling changes nothing. The configured `ops` agent (no hold) keeps `Delete agent "ops" and prune workspace/state?`.
  - `--force --json`: stderr carries the same warning; deletion proceeds and the registration is removed.
  - Red on main `b4ec01fa`: the confirmation has no warning.
- `doctor-agent-deletion-journal.test.ts` and the rest of `agents.delete.test.ts` stay green (40 tests): Doctor's held-store text is byte-identical after the move.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
…penclaw#207438)

## What problem this solves

Follow-up to openclaw#207257 (fixes the `server.agents.config-readiness` "publishes overlapping mutations from two operators" failure on main, bisected to openclaw#207257: parent 3/3 pass, openclaw#207257 3/3 fail).

openclaw#207257 made `agents.delete` accept a retired agent: not in config, still in the agent-database registry. A keep-files deletion (`deleteFiles: false`) keeps that registration. So after it completes, the agent is retired and has a completed deletion record that holds its real paths.

A second delete of that agent then went wrong in both owners:

- `deleteFiles: false` again (a concurrent loser behind the deletion lease, or any later repeat): it claimed the completed record and began a new one with paths re-resolved from config. Config no longer has the agent, so these were the default paths (`<state>/workspace-<id>`), not the agent's. It then ran drain, cron removal, exec-approval removal and a config write again.
- `deleteFiles: true` (the CLI always sends this; openclaw#207257 accepted edge 1, "a completed keep-files deletion whose files remain can be deleted again, this time with its files"): it moved `<state>/workspace-<id>` to Trash and left the agent's real custom workspace in place. The CLI prompt listed the default paths, not the kept ones.

## Change

- Gateway `agents.delete` (`src/gateway/server-methods/agents-delete.ts`): for a retired agent with a completed deletion record,
  - `deleteFiles: false` returns `ok` with `removed: []`, `failed: []`. It does not claim the record, begin a journal, or run drain, cron, exec-approval or config steps.
  - `deleteFiles: true` runs the normal journaled deletion on the paths from the completed record, never re-resolved from config.
- CLI local fallback (`src/commands/agents.commands.delete.ts`): the same path choice, so the confirmation and the deletion name the recorded paths.
- The `agents.delete` handler waits for a config-application receipt and reports "saved but not confirmed (unclaimed)" when no write claimed it. The no-op writes no config, so it settles that receipt as `applied` itself (`getRuntimeConfigWriteApplication(...).claim()?.settle("applied")`). Today only the config reloader settles receipts; this is the one other settler, and it is used only when nothing was written.

The surviving-agent check before Trash (`unclaimedBySurvivor` against the next config) is unchanged and now runs against the recorded path.

## User population

Gateway and CLI installs that delete an agent with "keep files" (Control UI or `agents.delete {deleteFiles:false}`) and then delete it again, or delete it with its files later. Both routes: Gateway RPC (`agents-delete.ts`) and the CLI offline fallback (`agents.commands.delete.ts`).

## Impact on main (unreleased)

openclaw#207257 is on main only (not in a release). Measured in a real Gateway on main `2adbdc49` (test below, with probes):

- Keep-files repeat: the completed record was replaced by one with default paths. The registration, a seeded peer agent (config, workspace, session) and a file seeded at `<state>/workspace-<id>` were untouched. From code: cron removal and exec-approval removal filter by the deleted agent's id; the config write with `allowMissing` prunes only that id's bindings/allow entries. Nothing of another agent changed.
- With-files re-delete after that: `removed` held `<state>/workspace-repeat-keep-files` (method `trash`), the seeded default-path file was gone (in Trash, recoverable), and the real custom workspace was still on disk.
- So the irreversible-looking damage is bounded: a wrong directory moved to Trash (recoverable) only when the user re-deletes with files and something exists at `<state>/workspace-<id>`; kept files left behind. No other agent's state was touched.

## Accepted edge cases

- A crash between claiming the completed record and beginning the new journal loses the recorded paths; the next attempt uses default paths. This window existed before and is not widened.
- A completed record can go stale if the id is added to config by hand with another workspace and then removed again by hand (agent creation through the Gateway or CLI claims the record; a hand edit does not). A with-files delete then uses the recorded workspace. Main used the default path here, also wrong.
- A keep-files repeat no longer re-runs cron/exec-approval cleanup for the retired id. `sessions.create` refuses unknown agent ids; before openclaw#207257 the same repeat was refused as "not found" with no cleanup at all.

## Evidence

- `src/gateway/server.agents.config-readiness.test.ts` (real Gateway, real stores, no mocks of the delete owner):
  - "publishes overlapping mutations from two operators": the concurrent loser's result is a no-op, the kept workspace and agent dir exist, the winner's record is unchanged, the registration is unchanged.
  - "repeats a completed keep-files deletion as a no-op and later deletes its recorded files": the same four-part contract for a sequential repeat, plus a peer agent and a default-path file left untouched, then a with-files delete trashes the recorded workspace and leaves the default-path file.
  - Red on main `2adbdc49` (record replaced: `workspaceDir` = `<state>/workspace-<id>`), green on head.
- `src/commands/agents.delete.test.ts` "deletes the recorded files of a retired agent after a keep-files deletion": own workspace (prompt names it, it goes to Trash, registration removed; red on main, the prompt never names it) and a workspace now used by a surviving agent (not trashed).
- Existing `agents.delete` command suite green, including openclaw#207257's retired-agent cases.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 29, 2026
…t stores (#207212)

## What problem this solves

Refs #205927 (two reporters).

Doctor tells operators to remove the directory of an agent that is no longer in `agents.entries`. Deleting the directory leaves the agent's row in the shared agent-database registry. Gateway tool-usage retention loops over every registered database and runs its prune through the same write path a live agent uses, which prepares, and so creates, the store. The next maintenance cycle brings the deleted directory back with a fresh, empty SQLite store.

## Change

`src/config/sessions/tool-usage.ts`: one private opener, `runUsageOperation`, with a `create` switch that sets both the capture's creation authority and `prepare`.

- Live-agent writes (ranking sightings, flush, reset, import) pass `create: true`. Behavior unchanged.
- Retention passes `create: false`. It prunes existing stores and skips a missing one. It never creates a store or directory.

Other loops over registered databases were checked; none needed a change:

- Session-registry maintenance returns early for a missing store (`session-registry-maintenance.ts:137`).
- The Doctor loops (usage-cost cache, memory schema, stale auth order) stat or inspect read-only before opening.

Credit: wangmiao0668000666 found the same create-on-prune path and the same capture detail in #205999.

## Not changed

- The registry row stays. Doctor still prints `Skipped missing registered agent database …` on each run until the registration is retired. That is the issue's remaining half and needs its own fix, so #205927 stays open.
- Known edge, also on `main`: if another caller opened the store in this process within the idle-handle window (30 min) before its directory was removed, that one retention cycle logs `tool usage retention failed` (worker `ENOENT`). It creates nothing, and the next cycle prunes normally.

## User population

Gateway installs that retired an agent by deleting its directory, as Doctor's state-integrity note advises. Retention runs on every Gateway (`server-maintenance.ts`, hourly, first run 130 s after start).

## Evidence

- `tool-usage.test.ts` regression: a registered database for an unconfigured agent, its directory removed, and a live store with an expired row, then `pruneRegisteredAgentToolUsage`.
  - Red on main `fd194285`: the directory is recreated.
  - Green here: the directory stays gone and the live store is pruned.
- Real Gateway, same steps on both sides. Each side has its own loopback port and an empty HOME and state directory.
  1. Configure `main` and `retired`, start the Gateway, and stop it: both stores are created and registered.
  2. Remove `retired` from config and delete `agents/retired`.
  3. Start the Gateway and wait 170 s, past the first maintenance cycle.

  ```text
  main fd19428: agents/retired exists again after 170 s = yes
    store born 09:18:41.315 (gateway ready 09:16:34.694, so the 130 s retention cycle)
    09:18:41.661 [cron/maintenance] Session registry maintenance completed
  this PR:       agents/retired exists again after 170 s = no
  registry on both sides afterwards: main,retired (the registration is untouched)
  ```

  The file is born just before "Session registry maintenance completed", which matches the issue's evidence.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 37511ae)

Companion disposition: #207257 changes explicit agents delete behavior; not a prerequisite for non-creating retention.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…t stores (#207212)

## What problem this solves

Refs #205927 (two reporters).

Doctor tells operators to remove the directory of an agent that is no longer in `agents.entries`. Deleting the directory leaves the agent's row in the shared agent-database registry. Gateway tool-usage retention loops over every registered database and runs its prune through the same write path a live agent uses, which prepares, and so creates, the store. The next maintenance cycle brings the deleted directory back with a fresh, empty SQLite store.

## Change

`src/config/sessions/tool-usage.ts`: one private opener, `runUsageOperation`, with a `create` switch that sets both the capture's creation authority and `prepare`.

- Live-agent writes (ranking sightings, flush, reset, import) pass `create: true`. Behavior unchanged.
- Retention passes `create: false`. It prunes existing stores and skips a missing one. It never creates a store or directory.

Other loops over registered databases were checked; none needed a change:

- Session-registry maintenance returns early for a missing store (`session-registry-maintenance.ts:137`).
- The Doctor loops (usage-cost cache, memory schema, stale auth order) stat or inspect read-only before opening.

Credit: wangmiao0668000666 found the same create-on-prune path and the same capture detail in #205999.

## Not changed

- The registry row stays. Doctor still prints `Skipped missing registered agent database …` on each run until the registration is retired. That is the issue's remaining half and needs its own fix, so #205927 stays open.
- Known edge, also on `main`: if another caller opened the store in this process within the idle-handle window (30 min) before its directory was removed, that one retention cycle logs `tool usage retention failed` (worker `ENOENT`). It creates nothing, and the next cycle prunes normally.

## User population

Gateway installs that retired an agent by deleting its directory, as Doctor's state-integrity note advises. Retention runs on every Gateway (`server-maintenance.ts`, hourly, first run 130 s after start).

## Evidence

- `tool-usage.test.ts` regression: a registered database for an unconfigured agent, its directory removed, and a live store with an expired row, then `pruneRegisteredAgentToolUsage`.
  - Red on main `fd194285`: the directory is recreated.
  - Green here: the directory stays gone and the live store is pruned.
- Real Gateway, same steps on both sides. Each side has its own loopback port and an empty HOME and state directory.
  1. Configure `main` and `retired`, start the Gateway, and stop it: both stores are created and registered.
  2. Remove `retired` from config and delete `agents/retired`.
  3. Start the Gateway and wait 170 s, past the first maintenance cycle.

  ```text
  main fd19428: agents/retired exists again after 170 s = yes
    store born 09:18:41.315 (gateway ready 09:16:34.694, so the 130 s retention cycle)
    09:18:41.661 [cron/maintenance] Session registry maintenance completed
  this PR:       agents/retired exists again after 170 s = no
  registry on both sides afterwards: main,retired (the registration is untouched)
  ```

  The file is born just before "Session registry maintenance completed", which matches the issue's evidence.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 37511ae)

Companion audit: #207257 changes deletion of unconfigured registered agents; existing-only maintenance avoids reopening a removed store independently.

Co-authored-by: RomneyDa <[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 commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime impact:ux-friction User-facing flow adds avoidable confusion or support burden without fully blocking progress. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S 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.

Doctor recommends deleting retired agent directories, but Gateway maintenance recreates their SQLite stores

1 participant