File size: 26,433 Bytes
d197cf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
import { isDeepStrictEqual } from "node:util";
import { coerceErrorMessage } from "@openclaw/normalization-core";
import {
  AgentSharedStoreOwnerError,
  assertAgentSessionStoreDeletionSafe,
  isPathOwnedBySurvivingAgent,
  readAgentDeleteDatabaseRegistry,
  resolveSurvivingDatabaseFilePaths,
} from "../agents/agent-delete-databases.js";
import { getRuntimeConfig } from "../config/config.js";
import { clawCronGatewayJobMatchesRef, deleteClawCronRef, markClawCronRefRemoved } from "./cron.js";
import {
  clawBootstrapStateBlocksRemove,
  planClawBootstrapRemoval,
  removeClawBootstrap,
} from "./lifecycle-bootstrap-removal.js";
import {
  withClawAgentConfigRemoval,
  digestClawAgentRemovalSurface,
} from "./lifecycle-config-removal.js";
import {
  clawRemoveQuietRuntime,
  ClawRemoveError,
  cleanupClawAgentFilesystem,
  deletionEffects,
  readClawRemoveCronInventory,
  releaseClawRemoveRows,
  removeClawWorkspaceFile,
  workspaceContainsUntrackedEntries,
} from "./lifecycle-delete-support.js";
import { removeClawMcpServers } from "./lifecycle-mcp-removal.js";
import {
  CLAW_REMOVE_PLAN_SCHEMA_VERSION,
  CLAW_REMOVE_RESULT_SCHEMA_VERSION,
  type ClawRemoveApplyOptions,
  type ClawRemovePlanOptions,
  type ClawRemoveResult,
  type ClawRemovePlan,
  type ClawRemovePlanAction,
} from "./lifecycle-remove-contract.js";
import { readClawStatus } from "./lifecycle-status.js";
import { clawMcpRemovalSelector, planClawMcpServerRemoval } from "./mcp.js";
import { clawMonitorSnapshotSchema } from "./monitor-cleanup-contract.js";
import { applyClawPackageRemovalPhase } from "./package-remove-phase.js";
import {
  filterReferencedCleanup,
  projectClawPackageRemovePlan,
  digestClawRemovalState,
} from "./package-remove-plan.js";
import { planClawPackageRemovals } from "./package-remove.js";
import { CLAW_OUTPUT_STABILITY } from "./types.js";

export { ClawRemoveError } from "./lifecycle-delete-support.js";
export {
  CLAW_REMOVE_PLAN_SCHEMA_VERSION,
  CLAW_REMOVE_RESULT_SCHEMA_VERSION,
} from "./lifecycle-remove-contract.js";
export { readClawStatus, type ClawStatusRecord } from "./lifecycle-status.js";

export async function buildClawRemovePlan(
  target: string,
  options: ClawRemovePlanOptions = {},
): Promise<ClawRemovePlan> {
  const status = await readClawStatus(target, options);
  const blockers: ClawRemovePlan["blockers"] = [];
  if (status.records.length === 0) {
    blockers.push({
      code: "claw_not_found",
      message: `No installed Claw matches ${JSON.stringify(target)}.`,
    });
  } else if (status.records.length > 1) {
    blockers.push({
      code: "claw_ambiguous",
      message: `Claw name ${JSON.stringify(target)} matches multiple agents; use an agent id.`,
    });
  }
  const record = status.records.length === 1 ? status.records[0] : undefined;
  if (record?.agentState === "modified") {
    blockers.push({
      code: "agent_modified",
      message: `Agent ${JSON.stringify(record.install.agentId)} changed after add.`,
    });
  }
  for (const file of record?.workspaceFiles ?? []) {
    if (file.state === "unsafe") {
      blockers.push({
        code: "workspace_file_unsafe",
        message: `${file.path}: ${file.message ?? "unsafe file"}`,
      });
    }
  }
  if (record && clawBootstrapStateBlocksRemove(record)) {
    blockers.push({
      code: "bootstrap_cleanup_uncertain",
      message: `BOOTSTRAP.md has ${record.bootstrap.state} ownership state and must be reconciled before removal.`,
    });
  }
  for (const server of record?.mcpServers ?? []) {
    if (server.state === "pending") {
      blockers.push({
        code: "mcp_cleanup_uncertain",
        message: `MCP server ${JSON.stringify(server.name)} has ${server.state} ownership state and must be reconciled before removal.`,
      });
    }
  }
  for (const cron of record?.cronJobs ?? []) {
    if (cron.status !== "removed" && (cron.status !== "complete" || !cron.schedulerJobId)) {
      blockers.push({
        code: "cron_cleanup_uncertain",
        message: `Cron declaration ${JSON.stringify(cron.manifestId)} has ${cron.status} ownership state and must be reconciled before removal.`,
      });
    }
  }
  const actions: ClawRemovePlanAction[] = [];
  if (record) {
    const packageCleanup = filterReferencedCleanup(options.referencedCleanup, "package");
    const mcpCleanup = filterReferencedCleanup(options.referencedCleanup, "mcp");
    const packageDecisions = await planClawPackageRemovals(record.install, record.packages, {
      ...options,
      deps: options.packageDeps,
      referencedCleanup: packageCleanup,
    });
    const packagePlan = projectClawPackageRemovePlan({
      decisions: packageDecisions,
      inspections: record.packages,
      cleanup: packageCleanup,
    });
    blockers.push(...packagePlan.blockers);
    const config = options.config ?? getRuntimeConfig();
    try {
      assertAgentSessionStoreDeletionSafe(config, record.install.agentId, options);
    } catch (error) {
      if (!(error instanceof AgentSharedStoreOwnerError)) {
        throw error;
      }
      blockers.push({ code: "shared_session_store_owner", message: error.message });
    }
    const effects = deletionEffects(
      config,
      record.install.agentId,
      record.install.workspace,
      options.env,
    );
    const survivingDatabaseFilePaths = resolveSurvivingDatabaseFilePaths(
      readAgentDeleteDatabaseRegistry(options),
      record.install.agentId,
      options.env,
    );
    const sharedWithSurvivor = (pathname: string) =>
      isPathOwnedBySurvivingAgent(
        config,
        record.install.agentId,
        pathname,
        survivingDatabaseFilePaths,
        options.env,
      );
    const sharedWorkspace = Boolean(effects.workspace) && sharedWithSurvivor(effects.workspace);
    const sharedAgentDir = sharedWithSurvivor(effects.agentDir);
    const sharedSessionsDir = sharedWithSurvivor(effects.sessionsDir);
    const workspaceHasModifiedFiles =
      record.workspaceFiles.some((file) => file.state === "modified") ||
      record.bootstrap.state === "modified";
    const trackedWorkspacePaths = [
      ...record.workspaceFiles.map((file) => file.path),
      ...(record.install.bootstrap && record.bootstrap.state === "pending"
        ? [record.bootstrap.path]
        : []),
    ];
    const workspaceHasUntrackedEntries = await workspaceContainsUntrackedEntries(
      record.install.workspace,
      trackedWorkspacePaths,
    );
    const { attachedJobs, monitors, inspectionUnavailable } = await readClawRemoveCronInventory(
      record.install.agentId,
      options,
    );
    const ownedSchedulerJobIds = new Set(
      record.cronJobs
        .filter((cron) => cron.status !== "removed" && cron.schedulerJobId)
        .map((cron) => cron.schedulerJobId),
    );
    actions.push({
      kind: "agent",
      id: record.install.agentId,
      action: "remove",
      target: `agents.entries[${JSON.stringify(record.install.agentId)}]`,
      blocked: record.agentState === "modified",
      details: {
        expectedState: record.agentState,
        configDigest: record.install.agentConfigDigest,
        removalSurfaceDigest: digestClawAgentRemovalSurface(
          options.config ?? getRuntimeConfig(),
          record.install.agentId,
        ),
        ownedPaths: record.install.agentOwnedPaths,
      },
      ...(record.agentState === "modified" ? { reason: "Agent config digest changed." } : {}),
    });
    if (effects.pruned.removedBindings > 0) {
      actions.push({
        kind: "configBinding",
        id: record.install.agentId,
        action: "remove",
        target: `bindings[agentId=${record.install.agentId}]`,
        blocked: record.agentState === "modified",
        details: { count: effects.pruned.removedBindings },
      });
    }
    if (effects.pruned.removedAllow > 0) {
      actions.push({
        kind: "agentAllow",
        id: record.install.agentId,
        action: "remove",
        target: `tools.agentToAgent.allow[${record.install.agentId}]`,
        blocked: record.agentState === "modified",
        details: { count: effects.pruned.removedAllow },
      });
    }
    if (effects.workspace) {
      actions.push({
        kind: "workspace",
        id: record.install.agentId,
        action:
          sharedWorkspace || workspaceHasModifiedFiles || workspaceHasUntrackedEntries
            ? "retain"
            : "trash",
        target: effects.workspace,
        blocked: record.agentState === "modified",
        details: {
          retained: sharedWorkspace || workspaceHasModifiedFiles || workspaceHasUntrackedEntries,
          sharedWith: effects.workspaceSharedWith,
        },
        ...(sharedWorkspace
          ? { reason: "Workspace contains state owned by another agent." }
          : workspaceHasModifiedFiles
            ? { reason: "Workspace contains locally modified Claw-managed files." }
            : workspaceHasUntrackedEntries
              ? { reason: "Workspace contains files or directories not managed by this Claw." }
              : {}),
      });
    }
    if (effects.agentDir) {
      actions.push({
        kind: "agentState",
        id: record.install.agentId,
        action: sharedAgentDir ? "retain" : "trash",
        target: effects.agentDir,
        blocked: record.agentState === "modified",
        ...(sharedAgentDir
          ? { reason: "Agent directory contains state owned by another agent." }
          : {}),
      });
    }
    actions.push({
      kind: "sessionIndex",
      id: record.install.agentId,
      action: "delete",
      target: `session store entries for agent:${record.install.agentId}`,
      blocked: record.agentState === "modified",
    });
    actions.push({
      kind: "sessionTranscripts",
      id: record.install.agentId,
      action: sharedSessionsDir ? "retain" : "trash",
      target: effects.sessionsDir,
      blocked: record.agentState === "modified",
      ...(sharedSessionsDir
        ? { reason: "Session directory contains state owned by another agent." }
        : {}),
    });
    for (const job of attachedJobs.filter((candidate) => !ownedSchedulerJobIds.has(candidate.id))) {
      if (monitors.some((monitor) => isDeepStrictEqual(monitor, job))) {
        actions.push({
          kind: "scheduledJob",
          id: job.id,
          action: "remove",
          target: `cron_jobs:${job.id}`,
          blocked: false,
          reason: "Config-owned monitor; Gateway cancellation and drainage precede local cleanup.",
          details: { ...job },
        });
        continue;
      }
      blockers.push({
        code: "agent_job_attached",
        message: `Cron job ${JSON.stringify(job.id)} still references agent ${JSON.stringify(record.install.agentId)}; reassign or remove independent work, or reconnect to the serving Gateway to verify monitor ownership.`,
      });
      actions.push({
        kind: "scheduledJob",
        id: job.id,
        action: "retain",
        target: `cron_jobs:${job.id}`,
        blocked: true,
        reason:
          "Scheduled work without verified Claw or config ownership must be handled explicitly.",
        details: {
          ...(inspectionUnavailable ? { monitorInspection: "unavailable" } : {}),
          name: job.name,
          enabled: job.enabled,
          agentId: job.agentId,
          ownerAgentId: job.ownerAgentId,
        },
      });
    }
    for (const file of record.workspaceFiles) {
      actions.push({
        kind: "workspaceFile",
        id: file.path,
        action: file.state === "unchanged" ? "delete" : "retain",
        target: `${file.workspace}:${file.path}`,
        blocked: file.state === "unsafe",
        details: {
          expectedState: file.state,
          contentDigest: file.contentDigest,
          workspace: file.workspace,
        },
        ...(file.state === "modified"
          ? { reason: "Local content changed; preserve the file." }
          : {}),
      });
    }
    const bootstrapAction = planClawBootstrapRemoval(record);
    if (bootstrapAction) {
      actions.push(bootstrapAction);
    }
    actions.push(...packagePlan.actions);
    const unmatchedMcpSelectors = new Set(mcpCleanup?.selected ?? []);
    for (const server of record.mcpServers) {
      const blocked = server.state === "pending";
      const decision = planClawMcpServerRemoval(server, {
        ...options,
        referencedCleanup: mcpCleanup,
      });
      unmatchedMcpSelectors.delete(clawMcpRemovalSelector(server));
      if (decision.blocked) {
        blockers.push({
          code: "referenced_cleanup_requires_override",
          message: `${clawMcpRemovalSelector(server)}: ${decision.reason ?? "explicit conflict override is required"}`,
        });
      }
      actions.push({
        kind: "mcpServer",
        id: server.name,
        action: blocked ? "retain" : decision.action,
        target: `mcp.servers.${server.name}`,
        blocked,
        details: {
          expectedState: server.state,
          configDigest: server.configDigest,
          relationship: server.relationship,
          origin: server.origin,
          independentOwner: server.independentOwner,
          affectedClawAgentIds: decision.affectedClawAgentIds,
          cleanupMode: mcpCleanup?.mode ?? "retain",
          availableCleanupModes:
            server.relationship === "referenced"
              ? ["retain", "remove-if-unused", "remove-selected"]
              : ["remove"],
        },
        ...(blocked
          ? { reason: `MCP ownership state is ${server.state}.` }
          : decision.reason
            ? { reason: decision.reason }
            : {}),
      });
    }
    for (const selector of unmatchedMcpSelectors) {
      blockers.push({
        code: "referenced_cleanup_not_found",
        message: `Selected referenced resource ${JSON.stringify(selector)} is not owned by this Claw.`,
      });
    }
    for (const cron of record.cronJobs) {
      const blocked =
        cron.status !== "removed" && (cron.status !== "complete" || !cron.schedulerJobId);
      actions.push({
        kind: "cronJob",
        id: cron.manifestId,
        action: blocked ? "retain" : "remove",
        target: cron.schedulerJobId ?? cron.declarationKey,
        blocked,
        details: {
          expectedStatus: cron.status,
          declarationKey: cron.declarationKey,
          schedulerJobId: cron.schedulerJobId,
          job: cron.job,
        },
        ...(blocked ? { reason: `Cron ownership state is ${cron.status}.` } : {}),
      });
    }
    actions.push({
      kind: "installRecord",
      id: record.install.agentId,
      action: "remove",
      target: `claw_installs:${record.install.agentId}`,
      blocked: false,
      details: {
        expectedStatus: record.install.status,
        planIntegrity: record.install.planIntegrity,
        sourceIntegrity: record.install.claw.integrity,
      },
    });
  }
  const planIdentity = {
    target,
    agentId: record?.install.agentId,
    actions,
    blockers,
  };
  return {
    schemaVersion: CLAW_REMOVE_PLAN_SCHEMA_VERSION,
    stability: CLAW_OUTPUT_STABILITY,
    dryRun: true,
    mutationAllowed: false,
    planIntegrity: digestClawRemovalState(planIdentity),
    target,
    ...(record ? { agentId: record.install.agentId } : {}),
    actions,
    blockers,
  };
}

export async function applyClawRemovePlan(
  plan: ClawRemovePlan,
  options: ClawRemoveApplyOptions = {},
): Promise<ClawRemoveResult> {
  if (options.consentPlanIntegrity !== plan.planIntegrity) {
    throw new ClawRemoveError(
      "plan_integrity_mismatch",
      "Consent does not match the current Claw remove plan; run remove --dry-run again.",
    );
  }
  if (plan.blockers.length > 0 || !plan.agentId) {
    throw new ClawRemoveError("remove_blocked", "The Claw remove plan contains blockers.");
  }
  const monitorGateway = options.monitorGateway;
  if (!monitorGateway) {
    throw new ClawRemoveError(
      "monitor_gateway_required",
      "Claw removal requires the serving Gateway to establish safe cancellation and drainage.",
    );
  }
  const currentPlan = await buildClawRemovePlan(plan.target, options);
  if (currentPlan.planIntegrity !== plan.planIntegrity) {
    throw new ClawRemoveError("remove_changed", "Claw-owned state changed after remove planning.");
  }
  const agentId = plan.agentId;
  const plannedAgentAction = plan.actions.find(
    (action) => action.kind === "agent" && action.id === agentId,
  );
  const expectedRemovalSurfaceDigest = plannedAgentAction?.details?.removalSurfaceDigest;
  if (typeof expectedRemovalSurfaceDigest !== "string") {
    throw new ClawRemoveError("remove_changed", "Claw remove plan is missing config state.");
  }
  const current = await readClawStatus(plan.agentId, options);
  const record = current.records[0];
  if (
    !record ||
    record.agentState === "modified" ||
    clawBootstrapStateBlocksRemove(record) ||
    record.workspaceFiles.some((file) => file.state === "unsafe") ||
    record.mcpServers.some((server) => server.state === "pending")
  ) {
    throw new ClawRemoveError("remove_changed", "Claw-owned state changed after remove planning.");
  }
  const packageDecisions = await planClawPackageRemovals(record.install, record.packages, {
    ...options,
    deps: options.packageDeps,
    referencedCleanup: filterReferencedCleanup(options.referencedCleanup, "package"),
  });
  const plannedPackages = plan.actions
    .filter((action) => action.kind === "packageRef")
    .map((action) => `${action.id}:${action.action}`)
    .toSorted();
  const currentPackages = packageDecisions
    .map(
      (decision) =>
        `${decision.packageRef.kind}:${decision.packageRef.ref}@${decision.packageRef.version}:${decision.action === "uninstall" ? "uninstall" : "release"}`,
    )
    .toSorted();
  if (JSON.stringify(plannedPackages) !== JSON.stringify(currentPackages)) {
    throw new ClawRemoveError("remove_changed", "Package ownership changed after remove planning.");
  }
  const plannedMcpServers = plan.actions
    .filter((action) => action.kind === "mcpServer")
    .map((action) => `${action.id}:${action.action}`)
    .toSorted();
  const currentMcpServers = record.mcpServers
    .map((server) => `${server.name}:${planClawMcpServerRemoval(server, options).action}`)
    .toSorted();
  if (JSON.stringify(plannedMcpServers) !== JSON.stringify(currentMcpServers)) {
    throw new ClawRemoveError("remove_changed", "MCP ownership changed after remove planning.");
  }
  const result: ClawRemoveResult = {
    schemaVersion: CLAW_REMOVE_RESULT_SCHEMA_VERSION,
    stability: CLAW_OUTPUT_STABILITY,
    dryRun: false,
    status: "partial",
    agentId,
    agentRemoved: false,
    workspaceFiles: [],
    packages: [],
    mcpServers: [],
    cronJobs: [],
    packageRefsReleased: 0,
  };
  const partial = (code: string, message: string): ClawRemoveResult => ({
    ...result,
    error: { code, message },
  });
  const monitors = currentPlan.actions
    .filter((action) => action.kind === "scheduledJob" && action.action === "remove")
    .map((action) => clawMonitorSnapshotSchema.parse(action.details));
  return await withClawAgentConfigRemoval<ClawRemoveResult>(
    {
      agentId,
      expectedDigest: record.install.agentConfigDigest,
      expectedInstall: record.orphaned ? null : record.install,
      expectedRemovalSurfaceDigest,
      expectedState: record.agentState,
      fallbackWorkspace: record.install.workspace,
      config: options.config,
      stateDatabase: options,
      onModified: () =>
        new ClawRemoveError("agent_modified", "Agent config changed during remove."),
      quiesceMonitors: (operationId) => monitorGateway.quiesce(agentId, operationId, monitors),
      drainMonitors: async (operationId) => await monitorGateway.drain(agentId, operationId),
    },
    async (commitRemoval, assertCurrent) => {
      assertCurrent();
      const mcpRemoval = await removeClawMcpServers({
        agentId,
        servers: record.mcpServers,
        options,
        assertCurrent,
      });
      assertCurrent();
      result.mcpServers = mcpRemoval.mcpServers;
      if (mcpRemoval.error) {
        return partial("mcp_cleanup_failed", mcpRemoval.error);
      }
      const cronJobs = result.cronJobs;
      for (const cron of record.cronJobs) {
        if (cron.status !== "removed" && (!cron.schedulerJobId || cron.status !== "complete")) {
          throw new ClawRemoveError(
            "cron_cleanup_uncertain",
            `Cron declaration ${JSON.stringify(cron.manifestId)} is not safely removable.`,
          );
        }
        if (
          cron.status !== "removed" &&
          (!options.cronGateway?.get || !options.cronGateway.remove)
        ) {
          throw new ClawRemoveError(
            "cron_gateway_required",
            "Claw cron jobs require the gateway-owned cron.get and cron.remove APIs.",
          );
        }
        try {
          if (cron.status !== "removed") {
            const live = await options.cronGateway!.get!(cron.schedulerJobId!);
            if (live != null && !clawCronGatewayJobMatchesRef(agentId, cron, live)) {
              throw new Error(
                `Cron declaration ${JSON.stringify(cron.manifestId)} changed after planning.`,
              );
            }
            assertCurrent();
            if (live != null) {
              try {
                await options.cronGateway!.remove(cron.schedulerJobId!);
              } catch (removeError) {
                // Re-read after transport loss; a durable removal may have succeeded.
                const afterRemove = await options.cronGateway!.get!(cron.schedulerJobId!);
                if (afterRemove != null) {
                  throw removeError;
                }
              }
            }
            assertCurrent();
            markClawCronRefRemoved(agentId, cron.manifestId, options);
          }
          deleteClawCronRef(agentId, cron.manifestId, options);
          cronJobs.push({
            manifestId: cron.manifestId,
            schedulerJobId: cron.schedulerJobId,
            action: "removed",
          });
        } catch (error) {
          const message = coerceErrorMessage(error);
          cronJobs.push({
            manifestId: cron.manifestId,
            schedulerJobId: cron.schedulerJobId,
            action: "error",
            message,
          });
          return partial("cron_cleanup_failed", message);
        }
      }
      const configRemoval = await commitRemoval();
      const { cleanupTargets, configBeforeDelete, completeDeletion } = configRemoval;
      result.agentRemoved = configRemoval.agentRemoved;
      try {
        await configRemoval.drainMonitors();
        configRemoval.assertCurrent();
      } catch (error) {
        return partial("monitor_cleanup_failed", coerceErrorMessage(error));
      }
      const purgeSessions =
        options.purgeSessions ??
        (await import("../config/sessions/cleanup-service.js")).purgeAgentSessionStoreEntries;
      const purgeFailed = await purgeSessions(configBeforeDelete, agentId, {
        env: options.env,
        runDatabaseCleanup: configRemoval.runDatabaseCleanup,
      });
      assertCurrent();
      if (purgeFailed) {
        return partial(
          "session_cleanup_failed",
          "Session cleanup failed; correct the reported error and retry Claw removal.",
        );
      }
      try {
        const removed = await applyClawPackageRemovalPhase(packageDecisions, {
          ...options,
          agentId,
          operationId: configRemoval.operationId,
          assertCurrent,
        });
        result.packages = removed.packages;
        result.pluginRuntime = removed.application;
        result.warnings = removed.warnings;
      } catch (error) {
        return partial("package_cleanup_failed", coerceErrorMessage(error));
      }
      assertCurrent();
      const packageErrors = result.packages.filter((pkg) => pkg.action === "error");
      if (packageErrors.length > 0) {
        return partial("package_cleanup_failed", packageErrors.map((pkg) => pkg.reason).join("; "));
      }
      const workspaceFiles = result.workspaceFiles;
      for (const file of record.workspaceFiles) {
        assertCurrent();
        workspaceFiles.push(await removeClawWorkspaceFile(file, assertCurrent));
      }
      assertCurrent();
      const bootstrap = await removeClawBootstrap(record, assertCurrent);
      const cleanupErrors = workspaceFiles
        .filter((file) => file.action === "error")
        .map((file) => file.message ?? `Could not remove ${file.path}.`);
      if (bootstrap?.action === "error") {
        cleanupErrors.push(bootstrap.message ?? `Could not remove ${bootstrap.path}.`);
      }
      if (cleanupErrors.length === 0) {
        const workspaceHasRemainingEntries = await workspaceContainsUntrackedEntries(
          cleanupTargets.workspaceDir,
          record.workspaceFiles.map((file) => file.path),
        );
        configRemoval.assertCurrent();
        cleanupErrors.push(
          ...(await cleanupClawAgentFilesystem({
            agentId,
            nextConfig: configRemoval.nextConfig,
            targets: cleanupTargets,
            runtime: clawRemoveQuietRuntime,
            trashPath: options.trashPath,
            stateDatabase: options,
            assertCurrent,
            retainWorkspace:
              workspaceHasRemainingEntries ||
              bootstrap?.action === "retainedModified" ||
              workspaceFiles.some((file) => file.action === "retainedModified"),
          })),
        );
      }
      const complete = releaseClawRemoveRows(
        agentId,
        workspaceFiles,
        cleanupErrors,
        configRemoval.assertCurrent,
        completeDeletion,
        options,
      );
      return {
        ...result,
        status: complete ? "complete" : "partial",
        ...(bootstrap ? { bootstrap } : {}),
        packageRefsReleased: complete ? record.packages.length : 0,
        ...(complete
          ? {}
          : {
              error: {
                code: "workspace_cleanup_failed",
                message: cleanupErrors.join("; "),
              },
            }),
      };
    },
  ).catch((error: unknown) =>
    partial(
      error instanceof ClawRemoveError ? error.code : "monitor_cleanup_failed",
      coerceErrorMessage(error),
    ),
  );
}