Skip to content

Commit 0f642d2

Browse files
authored
fix(agents): clean exec approvals on offline delete, and stop deleting main from taking the wildcard with it (#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.
1 parent bed80ee commit 0f642d2

6 files changed

Lines changed: 92 additions & 22 deletions

File tree

‎src/commands/agents.commands.delete.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
isGatewayCredentialsRequiredError,
4343
isGatewayTransportError,
4444
} from "../gateway/call.js";
45+
import { withAgentExecApprovalsRemoved } from "../infra/exec-approvals.js";
4546
import { normalizeAgentId, normalizeAgentIdStrict } from "../routing/session-key.js";
4647
import { defaultRuntime, type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
4748
import { readAgentDeletionJournal } from "../state/agent-deletion-journal.js";
@@ -276,19 +277,21 @@ export async function agentsDeleteCommand(
276277
existingJournal ?? { agentId, agentDir, workspaceDir, sessionsDir, deleteFiles },
277278
);
278279
try {
279-
if (configured) {
280-
await replaceConfigFile({
281-
nextConfig: result.config,
282-
...(baseHash !== undefined ? { baseHash } : {}),
283-
writeOptions: {
284-
allowedAgentRosterRemovals: [agentId],
285-
...(opts.json ? { skipOutputLogs: true } : {}),
286-
},
287-
});
288-
if (!opts.json) {
289-
logConfigUpdated(runtime);
280+
await withAgentExecApprovalsRemoved(agentId, async () => {
281+
if (configured) {
282+
await replaceConfigFile({
283+
nextConfig: result.config,
284+
...(baseHash !== undefined ? { baseHash } : {}),
285+
writeOptions: {
286+
allowedAgentRosterRemovals: [agentId],
287+
...(opts.json ? { skipOutputLogs: true } : {}),
288+
},
289+
});
290+
if (!opts.json) {
291+
logConfigUpdated(runtime);
292+
}
290293
}
291-
}
294+
});
292295
deletion.commit();
293296
} catch (error) {
294297
if (!existingJournal) {

‎src/commands/agents.config.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { pinSurvivorWorkspaceForRosterCollapse } from "../config/agent-workspace
1919
import { listRouteBindings } from "../config/bindings.js";
2020
import type { IdentityConfig } from "../config/types.base.js";
2121
import type { OpenClawConfig } from "../config/types.openclaw.js";
22-
import { normalizeAgentId } from "../routing/session-key.js";
22+
import { normalizeAgentId, normalizeAgentIdStrict } from "../routing/session-key.js";
2323

2424
export type AgentSummary = {
2525
id: string;
@@ -207,6 +207,10 @@ export function pruneAgentConfig(
207207
} {
208208
const id = normalizeAgentId(agentId);
209209
const clearedOwnerRefs: string[] = [];
210+
const targetsDeletedAgent = (candidate: string) => {
211+
const normalized = normalizeAgentIdStrict(candidate);
212+
return normalized.ok && normalized.value === id;
213+
};
210214
const clearOwnerRef = <T extends { agentId?: string }>(value: T | undefined, path: string) => {
211215
const owner = normalizeOptionalString(value?.agentId);
212216
if (!value || !owner || normalizeAgentId(owner) !== id) {
@@ -220,7 +224,7 @@ export function pruneAgentConfig(
220224
const pruneAllowAgents = (allowAgents: string[] | undefined) =>
221225
allowAgents?.filter((entry) => {
222226
const trimmed = entry.trim();
223-
return !trimmed || trimmed === "*" || normalizeAgentId(trimmed) !== id;
227+
return !trimmed || !targetsDeletedAgent(trimmed);
224228
});
225229
const nextAgentsList = [];
226230
for (const entry of agents) {
@@ -277,6 +281,23 @@ export function pruneAgentConfig(
277281
}
278282
: undefined;
279283
const nextTalk = clearOwnerRef(cfg.talk, "talk.agentId");
284+
const nextBroadcast = cfg.broadcast
285+
? Object.fromEntries(
286+
Object.entries(cfg.broadcast).map(([peerId, value]) => [
287+
peerId,
288+
Array.isArray(value) ? value.filter((entry) => !targetsDeletedAgent(entry)) : value,
289+
]),
290+
)
291+
: undefined;
292+
const nextHooks = cfg.hooks
293+
? {
294+
...cfg.hooks,
295+
allowedAgentIds: cfg.hooks.allowedAgentIds?.filter((entry) => !targetsDeletedAgent(entry)),
296+
mappings: cfg.hooks.mappings?.filter(
297+
(mapping) => !mapping.agentId || !targetsDeletedAgent(mapping.agentId),
298+
),
299+
}
300+
: undefined;
280301
const { list: _legacyList, ownership: _ownership, ...agentsConfig } = cfg.agents ?? {};
281302
const nextAgentsConfig = cfg.agents
282303
? {
@@ -305,6 +326,8 @@ export function pruneAgentConfig(
305326
...cfg,
306327
agents: nextAgentsConfig,
307328
bindings: filteredBindings.length > 0 ? filteredBindings : undefined,
329+
broadcast: nextBroadcast,
330+
hooks: nextHooks,
308331
talk: nextTalk,
309332
tools: nextTools,
310333
};

‎src/commands/agents.delete.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
} from "../config/sessions/session-accessor.js";
2020
import type { OpenClawConfig } from "../config/types.openclaw.js";
2121
import { GatewayTransportError } from "../gateway/transport-error.js";
22+
import { readExecApprovalsSnapshot, saveExecApprovals } from "../infra/exec-approvals.js";
2223
import { parseAgentSessionKey } from "../routing/session-key.js";
2324
import { readAgentDeletionJournal } from "../state/agent-deletion-journal.js";
2425
import { readAgentProvenance, recordAgentProvenance } from "../state/agent-provenance.js";
@@ -319,13 +320,28 @@ describe("agents delete command", () => {
319320
"agent:main:main": { sessionId: "sess-main", updatedAt: Date.now() },
320321
},
321322
});
323+
saveExecApprovals({
324+
version: 1,
325+
agents: {
326+
"*": { security: "deny" },
327+
main: { security: "allowlist", allowlist: [{ pattern: "/usr/bin/old" }] },
328+
ops: { security: "allowlist", allowlist: [{ pattern: "/usr/bin/keep" }] },
329+
},
330+
});
322331

323332
await agentsDeleteCommand({ id: "main", force: true, json: true }, runtime);
324333

325334
expect(runtime.error).not.toHaveBeenCalled();
326335
expect(runtime.exit).not.toHaveBeenCalledWith(1);
327336
expect(configMocks.replaceConfigFile).toHaveBeenCalledOnce();
328337
expectSessionStore(cfg, {}, "main");
338+
expect(readExecApprovalsSnapshot().file.agents).toEqual({
339+
"*": { security: "deny" },
340+
ops: {
341+
security: "allowlist",
342+
allowlist: [expect.objectContaining({ pattern: "/usr/bin/keep" })],
343+
},
344+
});
329345
});
330346
});
331347

@@ -570,6 +586,7 @@ describe("agents delete command", () => {
570586
"agent:main:main": { sessionId: "sess-main", updatedAt: now + 3 },
571587
},
572588
});
589+
expect(readExecApprovalsSnapshot().exists).toBe(false);
573590

574591
await agentsDeleteCommand({ id: "ops", force: true, json: true }, runtime);
575592

@@ -591,6 +608,7 @@ describe("agents delete command", () => {
591608
expectSessionStore(cfg, {
592609
"agent:main:main": { sessionId: "sess-main", updatedAt: now + 3 },
593610
});
611+
expect(readExecApprovalsSnapshot().exists).toBe(false);
594612
});
595613
});
596614

‎src/commands/agents.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,19 @@ describe("agents helpers", () => {
451451
{ agentId: "work", match: { channel: "whatsapp" } },
452452
{ agentId: "home", match: { channel: "telegram" } },
453453
],
454+
broadcast: {
455+
strategy: "parallel",
456+
"peer-1": ["work", "home"],
457+
"peer-2": ["WORK"],
458+
},
459+
hooks: {
460+
allowedAgentIds: ["*", "work", "home"],
461+
mappings: [
462+
{ id: "work-hook", agentId: "WORK", action: "agent" },
463+
{ id: "home-hook", agentId: "home", action: "agent" },
464+
{ id: "default-hook", action: "agent" },
465+
],
466+
},
454467
tools: {
455468
agentToAgent: { enabled: true, allow: ["work", "home"] },
456469
},
@@ -463,6 +476,16 @@ describe("agents helpers", () => {
463476
expect(result.config.bindings).toStrictEqual([
464477
{ agentId: "home", match: { channel: "telegram" } },
465478
]);
479+
expect(result.config.broadcast).toEqual({
480+
strategy: "parallel",
481+
"peer-1": ["home"],
482+
"peer-2": [],
483+
});
484+
expect(result.config.hooks?.allowedAgentIds).toEqual(["*", "home"]);
485+
expect(result.config.hooks?.mappings).toEqual([
486+
{ id: "home-hook", agentId: "home", action: "agent" },
487+
{ id: "default-hook", action: "agent" },
488+
]);
466489
expect(result.config.tools?.agentToAgent?.allow).toEqual(["home"]);
467490
expect(result.config.agents?.defaults?.subagents?.allowAgents).toEqual(["home"]);
468491
expect(result.config.agents?.defaults?.heartbeat).toEqual({ every: "5m" });

‎src/infra/exec-approvals-store.test.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -261,18 +261,20 @@ describe("exec approvals SQLite store", () => {
261261
expect(commit).not.toHaveBeenCalled();
262262
});
263263

264-
it("removes one agent and preserves unrelated policy", async () => {
264+
it("removes one agent and preserves wildcard and unrelated policy", async () => {
265265
saveExecApprovals({
266266
version: 1,
267267
agents: {
268-
removed: { security: "allowlist", allowlist: [{ pattern: "/usr/bin/old" }] },
268+
"*": { security: "deny" },
269+
main: { security: "allowlist", allowlist: [{ pattern: "/usr/bin/old" }] },
269270
kept: { security: "allowlist", allowlist: [{ pattern: "/usr/bin/keep" }] },
270271
},
271272
});
272-
seedAgentDeletionJournal("removed");
273+
seedAgentDeletionJournal("main");
273274

274-
await expect(withAgentExecApprovalsRemoved("removed", async () => "ok")).resolves.toBe("ok");
275+
await expect(withAgentExecApprovalsRemoved("main", async () => "ok")).resolves.toBe("ok");
275276
expect(loadExecApprovals().agents).toEqual({
277+
"*": { security: "deny" },
276278
kept: expect.objectContaining({
277279
allowlist: [expect.objectContaining({ pattern: "/usr/bin/keep" })],
278280
}),

‎src/infra/exec-approvals-store.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
AgentDeletionCommitUncertainError,
55
} from "../agents/agent-lifecycle-registry.js";
66
import { createSubsystemLogger } from "../logging/subsystem.js";
7-
import { normalizeAgentId } from "../routing/session-key.js";
7+
import { normalizeAgentId, normalizeAgentIdStrict } from "../routing/session-key.js";
88
import { readAgentDeletionJournal } from "../state/agent-deletion-journal.js";
99
import { withExistingOpenClawStateDatabaseReadOnly } from "../state/openclaw-state-db-readonly.js";
1010
import {
@@ -224,9 +224,10 @@ export async function withAgentExecApprovalsRemoved<T>(
224224
if (!operationId) {
225225
throw new ExecApprovalsMutationFencedError();
226226
}
227-
const removedPolicyEntries = Object.entries(snapshot.file.agents ?? {}).filter(
228-
([policyKey]) => normalizeAgentId(policyKey) === key,
229-
);
227+
const removedPolicyEntries = Object.entries(snapshot.file.agents ?? {}).filter(([policyKey]) => {
228+
const normalizedPolicyKey = normalizeAgentIdStrict(policyKey);
229+
return normalizedPolicyKey.ok && normalizedPolicyKey.value === key;
230+
});
230231
if (removedPolicyEntries.length > 0) {
231232
const updated = updateExecApprovalsInTransaction({
232233
baseHash: snapshot.hash,

0 commit comments

Comments
 (0)