<!-- Parent: sf-ai-agentscript/SKILL.md -->
# Agent Metadata Lifecycle & Cleanup

> Versioning, cleanup, and deletion patterns for Agent Script metadata objects.

---

## GenAiPlannerBundle Versioning

Each `sf agent publish authoring-bundle` creates a new GenAiPlannerBundle version. Understanding the naming conventions is critical for cleanup.

### Naming Conventions

| Convention | Example | When Used |
|-----------|---------|-----------|
| Hash suffix | `MyAgent_16jXXXXXXXXXXXX` | Default — auto-generated by publisher |
| Version suffix | `MyAgent_vNN` | Optional — set via GenAiPlannerBundle metadata after publish |

The hash suffix is non-deterministic — each publish generates a different hash. Over time, an org accumulates many bundle versions (e.g., `_v18`, `_v19`, `_v22`, ..., `_v31`).

### What Each Publish Creates

```
sf agent publish authoring-bundle
  └── GenAiPlannerBundle (new version)
       ├── GenAiPluginDefinition (per topic)
       ├── GenAiPluginActionDefinition (per action)
       └── plannerSurfaces (channel config)
```

Old bundle versions remain in the org. They are inactive but retain references to Apex/Flow targets via GenAiFunction definitions.

### Retrieve a Specific BotVersion

When you need to inspect or patch a specific published version, retrieve the exact `BotVersion` explicitly:

```bash
sf project retrieve start \
  --metadata Bot:MyAgent \
  --metadata BotVersion:MyAgent.v3 \
  --target-org TARGET_ORG
```

Current SF CLI releases correctly retrieve the requested `BotVersion` rather than always falling back to only the latest version.

---

## Flow Version Drift

`sf project retrieve start --metadata Flow:FlowName` retrieves the **latest** version (may be Draft/Obsolete), while the publisher validates against the **active** version's I/O.

**Impact**: If the latest Flow version renamed an input (e.g., `RecordId` -> `IncomingCaseId`), your locally-defined action I/O will mismatch the active version at publish time.

**Prevention**: Always verify the active Flow version before defining action I/O:

```bash
sf data query --query "SELECT ActiveVersionId, LatestVersionId FROM FlowDefinitionView WHERE ApiName = 'My_Flow' LIMIT 1" -o TARGET_ORG --json
```

If `ActiveVersionId != LatestVersionId`, inspect the active version's inputs via Tooling API before writing your action definition.

---

## Orphan-Then-Delete Pattern

When Salesforce returns "setup object in use" on metadata deletion, parent-child references create circular dependency locks. The Tooling API can break these references.

### Technique

1. **PATCH child records** to null out their parent reference (e.g., `PlannerId: null`)
2. **DELETE the now-childless parent** via Tooling API REST DELETE
3. Repeat up the dependency tree

### Implementation

```bash
# Step 1: Orphan child PluginDefinitions by nulling PlannerId
# CRITICAL: Must set unique LocalDeveloperName to avoid DUPLICATE_DEVELOPER_NAME error
curl -X PATCH "$INSTANCE_URL/services/data/vXX.0/tooling/sobjects/GenAiPluginDefinition/PLUGIN_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"PlannerId": null, "LocalDeveloperName": "original_name_del_001"}'

# Step 2: Delete the now-childless PlannerBundle
curl -X DELETE "$INSTANCE_URL/services/data/vXX.0/tooling/sobjects/GenAiPlannerBundle/BUNDLE_ID" \
  -H "Authorization: Bearer $TOKEN"
```

### LocalDeveloperName Uniqueness Constraint

When nulling `PlannerId`, the platform enforces `LocalDeveloperName` uniqueness across all orphaned records. Use a unique suffix:

```json
{"PlannerId": null, "LocalDeveloperName": "<original_name>_del_<sequence>"}
```

### API Comparison for Setup Object Deletion

| Method | Result |
|--------|--------|
| `sf project delete source` | "setup object in use" |
| SOAP `deleteMetadata` | "setup object in use" |
| Tooling API DELETE (without orphaning) | "setup object in use" |
| REST API DELETE on BotDefinition | "insufficient access rights" |
| Apex DML | "DML not allowed on [object]" |
| Composite API (ordered) | "setup object in use" on each subrequest |
| **Tooling API PATCH + DELETE** | **Works for PlannerBundle hierarchy** |

---

## What Cannot Be Deleted

Even with the Orphan-Then-Delete pattern, certain metadata objects are permanently locked:

| Object | Reason |
|--------|--------|
| `ConversationDefinitionDialog` | "System Dialog" internal protection flag |
| `ConversationDefinitionSession` | `deletable: false` at object level |
| `ConversationDefinitionEventLog` | `deletable: false` at object level |
| `BotVersion` | Locked by undeletable children above |
| `BotDefinition` | Locked by BotVersions |

**Practical implication**: Once a `BotDefinition` is created, it cannot be fully deleted via API. The UI "Delete Agent" button removes the `AiAuthoringBundle` and `GenAiPlannerBundle`, but NOT the `BotDefinition` itself. Contact Salesforce Support for full cleanup.

---

## Old Bundles Block Apex Deletion

Previous GenAiPlannerBundle versions retain `GenAiFunction` references to Apex class targets. This creates a dependency chain:

```
Old GenAiPlannerBundle (v5)
  └── GenAiPluginDefinition
       └── GenAiPluginActionDefinition
            └── References: apex://MyVerificationClass
```

**Impact**: `sf project delete source --metadata ApexClass:MyVerificationClass` fails with "setup object in use" even though the old bundle is inactive.

**Workaround**: Delete old bundles using the Orphan-Then-Delete pattern first, then delete the Apex class. Alternatively, accept orphaned Apex classes until bundles are cleaned up.

> **Note**: Apex **test** classes (not referenced by GenAiFunction) can be deleted freely.

---

## Shared Dependencies Between Agent Versions

When iterating on agent versions (V1 -> V2), Apex classes may be shared:

- V1 agent (original) created `MyVerificationClass`, `MySetVariable`, etc.
- V2 agent (rewrite) references the same Apex classes
- Deleting V1's metadata does NOT free the Apex classes if V2 still references them
- Orphaned V1 PluginDefinitions (PlannerId=null) also retain references

**Best practice**: Track which Apex classes are shared across agent versions. Only delete Apex classes after confirming no active agent OR orphaned PluginDefinition references them.

---

## Recommended Cleanup Workflow

When retiring old agent bundle versions:

1. **Inventory**: List all GenAiPlannerBundle versions (`sf project retrieve start --metadata GenAiPlannerBundle`)
2. **Identify active**: Query `BotVersion` for the currently active version number
3. **Map dependencies**: For each old bundle, note which Apex/Flow classes it references
4. **Orphan children**: PATCH each `GenAiPluginDefinition` to null `PlannerId`
5. **Delete bundles**: DELETE each old `GenAiPlannerBundle` via Tooling API
6. **Clean Apex** (optional): Delete unreferenced Apex classes after all referring bundles are gone

> **Cross-reference**: See [known-issues.md](known-issues.md) Issue 21 (old bundles block Apex deletion) and Issue 22 (Flow version drift).
