Skip to content

fix(agents): clean exec approvals on offline delete, and stop deleting main from taking the wildcard with it - #127037

Merged
steipete merged 1 commit into
mainfrom
steipete/approvals-agent-lifecycle
Aug 21, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/approvals-agent-lifecycle

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Two defects in one lifecycle. The second is the more serious one and is shipped today.

1. Offline agents delete leaves exec approvals behind

agents delete tries the Gateway first and falls back to a local path when the Gateway is unreachable — its own header calls this "gateway delegation and local cleanup fallback". The Gateway handler wraps deletion in withAgentExecApprovalsRemoved; the local fallback did not.

Verified against a real build, gateway stopped so the fallback path runs:

$ openclaw agents delete probe-agent --force
Moved to Trash: <workspace>
Moved to Trash: <state>/agents/probe-agent/sessions
Deleted agent: probe-agent          <- no mention of approvals

agent_deletion_journal and diagnostic_events legitimately still reference the agent afterward; scanning every table in the shared state database, exec_approvals_config was the only live policy store left behind.

The residue is not inert. Approve a pattern for an agent, delete it offline, then recreate an agent with the same id, and approvals get --json shows the old allowlist live under the new agent. The operator never granted it.

For contrast, the same delete with a Gateway running clears the entry — which is what makes this a sibling inconsistency rather than a missing feature.

2. Deleting main also deleted the "*" wildcard allowlist

This one is in the shared helper, so it affects the Gateway path too. It matched policy keys with:

([policyKey]) => normalizeAgentId(policyKey) === key

normalizeAgentId falls back to DEFAULT_AGENT_ID for anything it cannot represent. "*" strips to the empty string, so it returns "main":

"*"            loose= "main"   strict.ok= false
"main"         loose= "main"   strict.ok= true
"other-agent"  loose= "other-agent"
=> deleting "main" with the old loose match also matches "*": true

So any operator who deletes their main agent silently loses their wildcard exec approvals. A pre-fix test reproduced exactly that.

Why This Change Was Made

The offline path now calls the same journal-fenced, rollback-capable helper the Gateway path uses, rather than growing a second removal implementation.

Removal rather than a warning was a deliberate choice. An exec approval is a latent authority grant; leaving one behind contradicts the deletion contract the Gateway already enforces, and it is the id-reuse case above that turns residue into unintended authority. agents delete already moves the workspace and agent dir to Trash, so removing a policy entry is not out of character for it.

For the wildcard bug, strict normalization skips unrepresentable keys, so valid aliases are still removed while "*" and unrelated agents survive.

The fix belongs at the deletion lifecycle owner, not at the approvals read path. Making readers filter by "is this agent still configured" would compensate downstream for an upstream ownership failure, and would also change behavior for approvals written before an agent's first run.

Sibling sweep

pruneAgentConfig already handled bindings, subagent and agent-to-agent allowlists, heartbeat/system-agent ownership, and Talk ownership. Three more core-owned references also retained the deleted id and are fixed here: broadcast targets, hook mappings, and hook agent allowlists (preserving "*").

Follow-ups deliberately not taken

Each needs its own owner or a design decision, and folding them in would make this unreviewable:

  • Offline deletion still lacks the Gateway's transactional cron-job cleanup. I reproduced this separately: an hourly job survives an offline delete, stays enabled, and fires forever. It is not silent — each run records error: "cron job agent is unavailable: <id>" and cron list shows error — but it never stops, and id reuse would point it at the new agent. Cron mutation is Gateway-owned, so this needs the local cron seam wired up rather than a one-line addition.
  • Plugin-owned routing and thread bindings need an agent-deletion lifecycle hook.
  • Remote node approvals need distributed cleanup or explicit warning semantics.
  • Approval agentFilter cleanup needs a disabled-state design, since removing its last entry would widen policy rather than narrow it.

agents.defaults.sessionStore.agentId is intentionally retained as a fail-closed retired owner; auth-inheritance owners already block deletion.

User Impact

Deleting an agent without a Gateway now clears its exec approvals, matching Gateway behavior. Deleting main no longer takes the wildcard allowlist with it.

Production LOC: +45/-18, net +27.

Evidence

Live before/after on a fresh isolated HOME and OPENCLAW_STATE_DIR, unused port, seeded with target, wildcard, and other-agent policies. Inspected via json_extract(raw_json,'$.agents') directly rather than trusting CLI output (no socket token was queried or printed):

stage agents keys
before deletion nope-agent, *, other-agent
after deletion *, other-agent
after recreating nope-agent *, other-agent

Pre-fix, both regressions failed as intended: agents.delete.test.ts (deleted agent's policy remained) and exec-approvals-store.test.ts (deleting main also removed "*").

Post-fix, re-run independently here after rebasing onto current main: agents-mutate.test.ts 204 passed, exec-approvals-store.test.ts 24 passed, agents.delete.test.ts + agents.test.ts 42 passed, rc=0.

pnpm build passed (4m33s). node scripts/check-changed.mjs passed on Testbox tbx_01m0hc0zw22enc9bzhpvja6wcv (run 32449996049). oxfmt --check and git diff --check pass. $autoreview: clean, no accepted or actionable findings.

…g main from taking the wildcard with it

Two defects in one lifecycle, found by following one thread.

`agents delete` tries the Gateway first and falls back to a local path when the
Gateway is unreachable -- its own header calls this "gateway delegation and local
cleanup fallback". The Gateway path wraps deletion in
`withAgentExecApprovalsRemoved`; the local fallback did not. So deleting an agent
with no Gateway running left its exec approvals allowlist behind, silently.

That residue is not inert. Verified end to end: approve a pattern for an agent,
delete it through the offline path, recreate an agent with the same id, and
`approvals get` shows the old allowlist live under the new agent. The operator
never granted it. The offline path now uses the same journal-fenced,
rollback-capable helper as the Gateway path.

Removal rather than a warning: an exec approval is a latent authority grant, and
leaving one behind contradicts the deletion contract the Gateway already
enforces. `agents delete` already trashes the workspace and agent dir, so
removing a policy entry is not out of character for it.

The second defect is in the shared helper and affects the Gateway path too, which
means it is shipped today. It matched policy keys with

    normalizeAgentId(policyKey) === key

and `normalizeAgentId` falls back to `"main"` for anything it cannot represent.
`"*"` normalizes to `""` and therefore returns `"main"`, so deleting the `main`
agent also matched -- and removed -- the `"*"` wildcard allowlist. Strict
normalization now skips unrepresentable keys, so valid aliases are still removed
while the wildcard and unrelated agents survive.

Sibling sweep of `pruneAgentConfig`, which already handled bindings, subagent
allowlists, heartbeat/system-agent ownership, and Talk ownership: broadcast
targets, hook mappings, and hook agent allowlists also retained the deleted id.
Fixed, preserving `"*"` in the hook allowlist.

Follow-ups deliberately not taken here, each needing its own owner or design:
offline deletion still lacks the Gateway's transactional cron-job cleanup;
plugin-owned routing and thread bindings need an agent-deletion lifecycle hook;
remote node approvals need distributed cleanup or explicit warning semantics;
approval `agentFilter` cleanup needs a disabled-state design, since removing its
last entry would widen policy rather than narrow it.

Production +45/-18.
@clawsweeper

clawsweeper Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 21, 2026 05:33
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: S maintainer Maintainer-authored PR labels Aug 21, 2026
@steipete
steipete merged commit 0f642d2 into main Aug 21, 2026
292 of 293 checks passed
@steipete
steipete deleted the steipete/approvals-agent-lifecycle branch August 21, 2026 05:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Aug 21, 2026
… path (#127075)

* fix(agents): remove a deleted agent's cron jobs on the offline delete path

Follow-up to #127037, which fixed the exec-approvals half of the same gap and
named this one explicitly.

`agents delete` tries the Gateway first and falls back to a local path. The
Gateway handler nests two transactional cleanups around the roster commit --
cron wrapping approvals wrapping the config write. After #127037 the offline
path did the inner one; it still skipped cron. So deleting an agent without a
Gateway left its scheduled jobs enabled:

    $ openclaw agents delete cronprobe --force
    Deleted agent: cronprobe            <- no mention of cron
    $ sqlite3 <state>/state/openclaw.sqlite "select job_id, name, agent_id, enabled from cron_jobs"
    975cb750-... | cronprobe-job | cronprobe | 1
    $ openclaw cron list
    cronprobe-job   every 1h   Next: in 59m   idle

To be accurate about severity: this is not silent. Each firing records
`error: "cron job agent is unavailable: cronprobe"` and `cron list` flips to
`error`. The defect is that the job keeps its schedule forever, and that
recreating an agent with the same id points it at the new agent.

The fallback had collapsed two different reasons into one `null` return, which
is what made the fix look unsafe at first: credential failures happen *before*
transport, so a live scheduler may still own the cron store, while an
unreachable Gateway means nothing else is holding it. `maybeDeleteAgentThroughGateway`
now returns a discriminated union, and only the unreachable branch mutates the
store directly. The credentials branch commits the roster, warns, and sets
`cronCleanupSkipped: true` in JSON.

The local `CronService` construction already existed inside
`local-request-context.ts`; it moves to `src/cron/local-service.ts` and both
callers share it rather than growing a second cron mutation path. That
extraction also switches the default-owner resolver from
`tryResolveLegacyCompatibilityAgentId` to `tryResolveAmbientOwnerAgentId`, which
is a superset -- it honors an explicitly configured
`agents.defaults.systemAgent.agentId` and otherwise falls back to exactly the
previous function. Live testing showed agentless memory-dreaming jobs need it to
load under explicit agent ownership.

Production +89/-62.

* test(agents): split the delete suite so the new cron coverage stays under the cap

The 40-line cron regression test added in the previous commit pushed
`src/commands/agents.delete.test.ts` to 1018 code lines, over the 1000 cap, and
`check-lint-core-3` went red. Repo policy forbids a `max-lines` suppression.

Unlike the earlier `cron/view.test.ts` split there was no describe-level seam --
23 flat tests in a single describe -- so the split follows subject instead. The
seven workspace-lifecycle tests (trashing, sharing, overlap, symlink reachability,
workspace-state cleanup) move to `agents.delete.workspace.test.ts`.

`vi.mock` and `vi.hoisted` are per-file and cannot be imported, so the mock
preamble and the shared `beforeEach` are declared in both files; the helper block
above them is unchanged in each. Each file then imports only what it uses, which
is why the import lists differ.

Trimming to a hair under the cap by moving only the new test was possible and
rejected: it would have left the file at ~978 code lines, back at the cap within
a couple of changes. This leaves 749 and 603 physical lines.

No test content changed: 27 passed before, 27 after.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 22, 2026
…g main from taking the wildcard with it (openclaw#127037)

Two defects in one lifecycle, found by following one thread.

`agents delete` tries the Gateway first and falls back to a local path when the
Gateway is unreachable -- its own header calls this "gateway delegation and local
cleanup fallback". The Gateway path wraps deletion in
`withAgentExecApprovalsRemoved`; the local fallback did not. So deleting an agent
with no Gateway running left its exec approvals allowlist behind, silently.

That residue is not inert. Verified end to end: approve a pattern for an agent,
delete it through the offline path, recreate an agent with the same id, and
`approvals get` shows the old allowlist live under the new agent. The operator
never granted it. The offline path now uses the same journal-fenced,
rollback-capable helper as the Gateway path.

Removal rather than a warning: an exec approval is a latent authority grant, and
leaving one behind contradicts the deletion contract the Gateway already
enforces. `agents delete` already trashes the workspace and agent dir, so
removing a policy entry is not out of character for it.

The second defect is in the shared helper and affects the Gateway path too, which
means it is shipped today. It matched policy keys with

    normalizeAgentId(policyKey) === key

and `normalizeAgentId` falls back to `"main"` for anything it cannot represent.
`"*"` normalizes to `""` and therefore returns `"main"`, so deleting the `main`
agent also matched -- and removed -- the `"*"` wildcard allowlist. Strict
normalization now skips unrepresentable keys, so valid aliases are still removed
while the wildcard and unrelated agents survive.

Sibling sweep of `pruneAgentConfig`, which already handled bindings, subagent
allowlists, heartbeat/system-agent ownership, and Talk ownership: broadcast
targets, hook mappings, and hook agent allowlists also retained the deleted id.
Fixed, preserving `"*"` in the hook allowlist.

Follow-ups deliberately not taken here, each needing its own owner or design:
offline deletion still lacks the Gateway's transactional cron-job cleanup;
plugin-owned routing and thread bindings need an agent-deletion lifecycle hook;
remote node approvals need distributed cleanup or explicit warning semantics;
approval `agentFilter` cleanup needs a disabled-state design, since removing its
last entry would widen policy rather than narrow it.

Production +45/-18.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 22, 2026
… path (openclaw#127075)

* fix(agents): remove a deleted agent's cron jobs on the offline delete path

Follow-up to openclaw#127037, which fixed the exec-approvals half of the same gap and
named this one explicitly.

`agents delete` tries the Gateway first and falls back to a local path. The
Gateway handler nests two transactional cleanups around the roster commit --
cron wrapping approvals wrapping the config write. After openclaw#127037 the offline
path did the inner one; it still skipped cron. So deleting an agent without a
Gateway left its scheduled jobs enabled:

    $ openclaw agents delete cronprobe --force
    Deleted agent: cronprobe            <- no mention of cron
    $ sqlite3 <state>/state/openclaw.sqlite "select job_id, name, agent_id, enabled from cron_jobs"
    975cb750-... | cronprobe-job | cronprobe | 1
    $ openclaw cron list
    cronprobe-job   every 1h   Next: in 59m   idle

To be accurate about severity: this is not silent. Each firing records
`error: "cron job agent is unavailable: cronprobe"` and `cron list` flips to
`error`. The defect is that the job keeps its schedule forever, and that
recreating an agent with the same id points it at the new agent.

The fallback had collapsed two different reasons into one `null` return, which
is what made the fix look unsafe at first: credential failures happen *before*
transport, so a live scheduler may still own the cron store, while an
unreachable Gateway means nothing else is holding it. `maybeDeleteAgentThroughGateway`
now returns a discriminated union, and only the unreachable branch mutates the
store directly. The credentials branch commits the roster, warns, and sets
`cronCleanupSkipped: true` in JSON.

The local `CronService` construction already existed inside
`local-request-context.ts`; it moves to `src/cron/local-service.ts` and both
callers share it rather than growing a second cron mutation path. That
extraction also switches the default-owner resolver from
`tryResolveLegacyCompatibilityAgentId` to `tryResolveAmbientOwnerAgentId`, which
is a superset -- it honors an explicitly configured
`agents.defaults.systemAgent.agentId` and otherwise falls back to exactly the
previous function. Live testing showed agentless memory-dreaming jobs need it to
load under explicit agent ownership.

Production +89/-62.

* test(agents): split the delete suite so the new cron coverage stays under the cap

The 40-line cron regression test added in the previous commit pushed
`src/commands/agents.delete.test.ts` to 1018 code lines, over the 1000 cap, and
`check-lint-core-3` went red. Repo policy forbids a `max-lines` suppression.

Unlike the earlier `cron/view.test.ts` split there was no describe-level seam --
23 flat tests in a single describe -- so the split follows subject instead. The
seven workspace-lifecycle tests (trashing, sharing, overlap, symlink reachability,
workspace-state cleanup) move to `agents.delete.workspace.test.ts`.

`vi.mock` and `vi.hoisted` are per-file and cannot be imported, so the mock
preamble and the shared `beforeEach` are declared in both files; the helper block
above them is unchanged in each. Each file then imports only what it uses, which
is why the import lists differ.

Trimming to a hair under the cap by moving only the new test was possible and
rejected: it would have left the file at ~978 code lines, back at the cap within
a couple of changes. This leaves 749 and 603 physical lines.

No test content changed: 27 passed before, 27 after.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations maintainer Maintainer-authored PR size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant