> For the complete documentation index, see [llms.txt](https://docs.labs.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.labs.ai/conversations-and-orchestration/deployment-management-of-agents.md).

# Deployment Management of Agents

## Overview

**Deployment Management** controls the lifecycle of your agents across different environments. In EDDI, agents go through a **create → configure → deploy** workflow before they can process conversations.

### Why Deployment Management?

Deployment management provides:

* **Environment Isolation**: Test agents without affecting production
* **Version Control**: Deploy specific agent versions, roll back if needed
* **Gradual Rollout**: Test agents in `test` environment before deploying to `production`
* **Zero-Downtime Updates**: Deploy new versions while old ones are still running
* **Audit Trail**: Track what's deployed, when, and by whom

### EDDI Environments

| Environment      | Purpose                    |
| ---------------- | -------------------------- |
| **`test`**       | Development and testing    |
| **`production`** | Live deployments (default) |

Authentication is deployment-wide and the same for both environments.

### Deployment Lifecycle

```
1. CREATE Agent
   POST /agentstore/agents
   → Agent exists but is NOT deployed

2. DEPLOY Agent
   POST /administration/production/deploy/agent123?version=1
   → Agent becomes active and can handle conversations

3. USE Agent
   POST /agents/agent123/start
   → Users can now interact with the agent

4. UPDATE Agent
   Create new version → Deploy new version
   → Old version still available if specified

5. UNDEPLOY Agent
   POST /administration/production/undeploy/agent123?version=1
   → Agent stops processing new conversations
```

### Auto-Deploy Feature

* **`autoDeploy=true`** (the default): the deployment is persisted, so this exact agent version is deployed again automatically after a restart
* **`autoDeploy=false`**: the agent is deployed into the running instance only — nothing is persisted, so the deployment is gone after a restart

Neither value deploys a new version created by an agent update: a new version always needs its own explicit deploy call.

This is useful for:

* **Development**: `autoDeploy=false` in `test`, so a throwaway version does not survive the next restart
* **Production**: `autoDeploy=true` in `production`, so the deployed version comes back up with the instance

### Checking Deployment Status

You can check:

* **Single Agent Status**: Is agent123 deployed in production?
* **All Deployments**: List all deployed agents across environments
* **Version Info**: Which version is currently deployed?

## Deployment Operations

In this section we will discuss the deployment management of Agents, including deployment/undeployment, checking deployment status, and listing all deployed Agents.

After all the required resources for the agent have been created and configured (**`Dictionary`**, **`Behavior Rules`**, **`Output`**, **`Workflow`**, etc.) and the Agent is created through **`POST`** to **`/agentstore/agents`**, deployment management is key to having granular control over deployed agents.

## **Deployment of an Agent :**

The deployment of a specific agent is done through a **`POST`** to **`/administration/{environment}/deploy/{agentId}`**

### Deploy Agent REST API Endpoint

| Element             | Value                                                                                                                                                                                                                                                                                                                                             |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP Method         | `POST`                                                                                                                                                                                                                                                                                                                                            |
| API endpoint        | `/administration/{environment}/deploy/{agentId}`                                                                                                                                                                                                                                                                                                  |
| {environment}       | (`Path parameter`):`String` deployment environment: `production` (default) or `test`                                                                                                                                                                                                                                                              |
| {agentId}           | (`Path parameter`):`String` id of the agent that you wish to **deploy**.                                                                                                                                                                                                                                                                          |
| `version`           | (`Query parameter`) agent version to deploy (required).                                                                                                                                                                                                                                                                                           |
| `autoDeploy`        | (`Query parameter`) default `true`.                                                                                                                                                                                                                                                                                                               |
| `waitForCompletion` | (`Query parameter`) default `false`. `true` waits up to 30 s and returns the final status; otherwise `202` is returned immediately.                                                                                                                                                                                                               |
| Refusals            | `404` agent not found; `429` when the tenant's `maxAgentsPerTenant` quota (distinct agent ids) is exceeded. `GET /administration/{environment}/deploy/{agentId}/preflight?version=N` runs the vault-grant check without deploying, see [Secrets Vault](https://docs.labs.ai/security-and-compliance/secrets-vault.md#preflight-before-deploying). |

### Example *:*

*Request URL:*

`http://localhost:7070/administration/production/deploy/5aaf98e19f7dd421ac3c7de9?version=1&autoDeploy=true`

*Response Body:*

`no content`

*Response Code:*

`202`

## **Undeployment of an Agent**

The undeployment of a specific agent is done through a **`POST`** to **`/administration/{environment}/undeploy/{agentId}`**

### Undeploy Agent REST API Endpoint

| Element                                 | Value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP Method                             | `POST`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| API endpoint                            | `/administration/{environment}/undeploy/{agentId}`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| {environment}                           | (`Path parameter`):`String` deployment environment: `production` (default) or `test`                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| {agentId}                               | (`Path parameter`):`String` id of the agent that you wish to **undeploy**.                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| version                                 | (`Query parameter`, **required**):`Integer` version of the agent that you wish to **undeploy**.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| endAllActiveConversations               | (`Query parameter`, optional, default `false`):`Boolean` end the agent's active conversations instead of refusing. Without it, undeploying an agent that has active conversations returns `409`. Conversations that can move to another deployed, compatible version are neither counted nor ended — see [Running conversations and new agent versions](#running-conversations-and-new-agent-versions).                                                                                                                                                 |
| undeployThisAndAllPreviousAgentVersions | (`Query parameter`, optional, default `false`):`Boolean` also undeploy every earlier version, counting down to version 1. `version` must then be a version the agent has (at most its current one, `400` otherwise; `404` for an agent with no documents and nothing deployed), so the range is bounded by the agent's real history. Every version is attempted: one that fails (`500`, naming the version) or that is refused for its open conversations (`409`) no longer stops the lower versions, and the response reports what was not undeployed. |

Ending the open conversations reads only a small projection of each (never the conversations themselves), so it is safe on a version with tens of thousands of open conversations. To end idle conversations across the whole deployment instead, see [Ending a backlog of idle conversations](https://docs.labs.ai/deployment-and-infrastructure/upgrading-from-5x.md#ending-a-backlog-of-idle-conversations-in-one-call).

### Example :

**Undeploy an agent**

*Request URL*

`http://localhost:7070/administration/production/undeploy/5aaf98e19f7dd421ac3c7de9?version=1`

*Response Body*

`no content`

*Response Code*

`202`

### Conflict: the agent has active conversations

If the agent has at least one active conversation and `endAllActiveConversations` is `false`, the endpoint answers `409 Conflict` with a `text/plain` body naming the count. Nothing is undeployed. This is the normal case for a live agent, so a caller that treats any non-2xx as a hard failure will abort a rollback here.

Retry with `endAllActiveConversations=true` to end those conversations and proceed:

`http://localhost:7070/administration/production/undeploy/5aaf98e19f7dd421ac3c7de9?version=1&endAllActiveConversations=true`

Conversations ended this way record the end reason `agent-version-retired`, so clients can tell their users that the assistant was updated: a Slack thread says so and continues in a fresh conversation, and managed conversations and the `/v1` API start a new one on the next message.

Conversations that another deployed version of the **same compatibility generation** can take over do not count here at all — see the next section.

## Landing resource changes in one pass

Nothing in EDDI changes in place: editing a behavior rule set, an LLM config or a workflow writes the *next version of that document*, while the workflow still references the old config version and the agent still references the old workflow version. Wiring a change in by hand is a chain — repoint the workflow, repoint the agent, deploy — and each hop writes a version of its own.

`POST /agentstore/agents/{id}/cascade?version=N` does the whole chain in one request, writing every changed workflow and the agent **once**:

```json
{
  "resourceMappings": [
    { "oldUri": "eddi://ai.labs.llm/llmstore/llms/6a1b…?version=1",
      "newUri": "eddi://ai.labs.llm/llmstore/llms/6a1b…?version=2" },
    { "oldUri": "eddi://ai.labs.workflow/workflowstore/workflows/9c2d…?version=1",
      "newUri": "eddi://ai.labs.workflow/workflowstore/workflows/9c2d…?version=2" }
  ],
  "redeploy": true,
  "environment": "production",
  "compatible": false
}
```

* **Mappings.** An `oldUri` must be a reference the agent really holds — a step of one of its workflows, or a workflow the agent itself references. A mapping naming a workflow moves the agent to another *version of that same workflow* (a different workflow is refused, as it is for `updateResourceUri`) and repoints the agent at that version first and applies the step mappings to *its* steps, so a workflow you edited in the same batch is picked up rather than overwritten by a rewrite of the version the agent still points at.
* **Validation, before anything is written.** Both URIs must carry a `?version=`, name the same kind of resource (a step cannot be re-aimed at a different type of document), and match a reference the agent holds. Any pair that does not answers `400` and **nothing is written**. A `version` that is not the agent's current one answers `409`, also before any write.
* **What it cannot change.** The request carries URI pairs and nothing else. The only fields touched are `config.uri` on workflow steps and the agent's workflow list; every other agent setting — the approval gate (`hitlConfig`) included — is the stored value, written back unchanged.
* **`redeploy`** goes through the normal deploy endpoint, so the tenant quota and the vault-grant check apply exactly as for `POST /administration/{environment}/deploy/{agentId}`. The documents are written either way; the response's `deployment` says whether it went live. When the deploy reports why it failed (a missing vault grant names the secrets and the exact grant calls), `deployment.failure` carries that, and the MCP tool reports it as `failureCode`, `secrets`, `fix` and `humanActionRequired`, as `deploy_agent` does.
* **Partial failure.** Workflows are written first, then the agent. If the agent save (or a later workflow write) fails, the error says the agent was **not** changed, names the workflow versions already written (unreferenced, harmless) and tells you to retry from the agent''s current version; a concurrent edit is a 409, anything else a 500. A store that does not report the version it wrote is an error, never a guessed version.
* **`compatible`** is the flag described in the next section.
* **Roles.** `eddi-admin` or `eddi-editor`, the same as the writes it composes, and the usual per-document edit access applies.

The response names the new agent version, each workflow version written, and the deployment outcome. The MCP tool `apply_agent_changes` is the same operation (it also reports the flat `updatedWorkflows` and `mappingsApplied` counts) and requires `eddi-admin`.

## Running conversations and new agent versions

A conversation can **follow** newer versions of its agent — but only versions its author declared **compatible**. Every save is a **breaking change** unless the save says otherwise, so nothing changes for anyone who does not opt in.

### The compatibility generation

Every agent version carries a `compatibilityGeneration`, assigned by the server on every save:

| Save                                                                                                                | Generation of the new version                                                                                                                                                                                       |
| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| New agent (create, duplicate, import of a new agent)                                                                | `1`                                                                                                                                                                                                                 |
| Update with `compatible=true`                                                                                       | the previous version's                                                                                                                                                                                              |
| Update without it (the default), and every import or sync of an existing agent unless it declares `compatible=true` | the previous version's + 1 — a breaking change (running conversations can be moved afterwards, see [Moving running conversations onto the current version](#moving-running-conversations-onto-the-current-version)) |
| Any update of a version stored before generations existed                                                           | `1` — a new chain starts                                                                                                                                                                                            |

Versions with the same generation are compatible. A value for the field in the request body is ignored: the Manager saves by sending back the configuration it read, and honouring that value would make every save compatible. Only the latest version of an agent can be updated, so generations only ever go up.

Declare a save compatible with the `compatible` query parameter:

```
PUT /agentstore/agents/{id}?version=4&compatible=true
PUT /agentstore/agents/{id}/updateResourceUri?version=4&compatible=true
```

In the Manager, the save dialogs that write a new agent version offer the same choice as a checkbox, unticked by default. Over MCP, `apply_agent_changes` takes a `compatible` argument (default `false`).

### Promoting an agent by import or sync

A ZIP import onto an existing agent (`strategy=upgrade` or `strategy=merge`) and an agent sync (`/backup/import/sync` and `/backup/import/sync/batch`) write a new version of the target the same way a save does, and they take the same declaration: `compatible=true` (the batch endpoint takes `"compatible": true` per request). Without it the new version is **breaking** and every conversation running in production stays on the version it started on, which is the safe default for a configuration that was developed elsewhere and judged against nothing running here.

Tick **compatible** on a promotion when the change is one of the compatible kinds in the table below (prompt wording, a different model, new tools, output text) and you want conversations that are already running to pick it up on their next turn — a promoted fix reaches everyone, not only new conversations. Leave it unticked when properties, actions or workflow steps were renamed or removed, or the new version needs conversation state older conversations lack.

The import and sync previews carry a `conversationImpact`, so the choice is made with the numbers in front of you. It answers for both declarations at once: the target's current version and generation, the generation each declaration would produce (`generationIfCompatible`, `generationIfBreaking`), the agent's open conversations (`activeConversations`) grouped by their own compatibility generation (`generations`), and how many of them would follow if the version is declared compatible (`followingIfCompatible`: those of the generation a compatible save would carry). Declared breaking, none follow. Conversations are counted by generation, not by the version they last ran on, because a conversation follows the newest ready version of its own generation: after a few compatible saves many idle ones are stored on versions that are no longer deployed and still follow. It is one grouped count, never the conversations themselves. It is absent when the preview writes nothing, the target does not exist yet, or the caller may not edit the target.

After the write, the answer says what the declaration did: an upgrade or sync result carries `compatible` and the `compatibilityGeneration` of the version it wrote, and a merge import answers with the headers `X-Agent-Compatible` and `X-Agent-Compatibility-Generation`.

If the target's current version predates generations (`startsNewChain: true`), a compatible import still starts generation `1`, and the conversations already running on the old version stay on it; from the next compatible promotion on they follow. Also, a failed merge puts the pre-import content back as a new version with the same declaration, so a compatible merge that is rolled back leaves generations unchanged and conversations that had already moved follow on to the restored content.

### What a conversation does on its next turn

| The conversation                                                                            | Runs on                                                                                                                                                                      |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| started on a version **with** a generation                                                  | the highest `READY` version of that generation on the serving node — a newer compatible version as soon as it is deployed, or an older one when the newer one was undeployed |
| started on a version **without** a generation (every conversation that existed before this) | its own version, exactly as before                                                                                                                                           |
| is paused for human approval                                                                | its own version until the resume completes — a pending approval is never re-evaluated against a newer version's gates                                                        |
| has no version of its generation ready on this node                                         | its own version, deployed on demand as before                                                                                                                                |

Each step records the version that ran it as step data `agent:version`, and the first step after a move records `agent:switch = {"from": 4, "to": 5}`. The conversation's descriptor, its `agentVersion` in snapshots, `{conversationInfo.agentVersion}` in templates and the audit ledger all name the version the turn actually ran on. Moves are logged at INFO and counted in `eddi_conversation_agent_version_switch_count`.

### What "compatible" means

**Compatible means either version can continue a conversation the other one started.** It has to hold in both directions: during a rollout, or after undeploying a faulty version, a conversation can move back to an older version of the same generation.

| Compatible — tick the box                       | Breaking — leave it unticked                                                   |
| ----------------------------------------------- | ------------------------------------------------------------------------------ |
| Prompt wording, a different model or parameters | A property renamed or removed, or its meaning changed                          |
| New tools                                       | An action renamed or removed (behavior rules matching `lastStep` stop firing)  |
| New behavior rules that need no new state       | Workflow steps removed or reordered in a way a flow depends on                 |
| Output text changes                             | An output or quick-reply contract a client relies on                           |
|                                                 | A version that **requires** conversation state older conversations do not have |

**Never mark a security fix as breaking unless the old version is undeployed with it.** A conversation that stays on the old version keeps its old configuration, including its HITL gates and tool whitelist. Declared compatible, the fix reaches every running conversation on its next turn.

### Deploying: preview the impact

Before deploying a version, ask what it does to the conversations already running:

| Element      | Value                                                                                                                                               |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP Method  | `GET`                                                                                                                                               |
| API endpoint | `/administration/{environment}/deploymentimpact/{agentId}?version={version}`                                                                        |
| Response     | `{"agentId", "version", "compatibilityGeneration", "deployedVersions": [{"version", "compatibilityGeneration", "activeConversations", "outcome"}]}` |

`deployedVersions` lists every other deployed version in the environment, highest first. `outcome` is `FOLLOW` when its conversations move to the new version on their next turn (same generation, older version) and `STAY` otherwise (another generation, no generation, or a newer version).

### Undeploying: old versions can be retired freely

Undeploying a version whose conversations have another deployed version of the same generation to go to answers `202` without ending them — they move on their next turn. Only conversations with nowhere to go are counted for the `409` and ended by `endAllActiveConversations`. "Deployed" means recorded as deployed, or running on the node that handles the request (a deployment made with `autoDeploy=false` is never recorded). A version undeployed by the same call — `undeployThisAndAllPreviousAgentVersions` — never counts as somewhere to go.

Undeploying no longer disables the agent's schedules while another version of it stays deployed in the environment; they are disabled only when the last deployed version goes.

### A breaking change and the conversations on the old version

There is no separate policy to configure; the existing options cover it:

* **Keep them**: leave the old version deployed. It serves its conversations until they end.
* **End them**: `undeploy?endAllActiveConversations=true`. They record `agent-version-retired`, and the channels that can start a fresh conversation do so (see above).
* **Move them**: declare them compatible after the fact with [`upgradeconversations`](#moving-running-conversations-onto-the-current-version) — for the case where the save could not say so itself, such as a promotion by ZIP import.

### Moving running conversations onto the current version

**Order of preference.** Declare compatibility when you save: use `compatible=true` on an update, and the compatible option of the ZIP upgrade-import and of agent sync when promoting an agent from a staging instance, so running conversations follow the new version from the start. This section is the **repair path for conversations that are already pinned**: the legacy conversations without a generation that every installation from before generations existed still has, and breaking saves (an import or sync made without the compatible option) that you later judge safe. Ending those conversations is a poor answer for a user in the middle of a conversation. If you know the new version can continue them, say so:

| Element       | Value                                                                                                                                                                         |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP Method   | `POST`                                                                                                                                                                        |
| API endpoint  | `/administration/{environment}/upgradeconversations/{agentId}`                                                                                                                |
| `dryRun`      | (`Query parameter`, optional, **default `true`**): `true` only reports, `false` writes                                                                                        |
| `fromVersion` | (`Query parameter`, optional, repeatable): only conversations stored on these versions. Default: every version whose conversations are on an older generation than the target |
| `limit`       | (`Query parameter`, optional, default `5000`, max `1000000`): the most conversations one call looks at. The response says when it stopped there                               |
| `after`       | (`Query parameter`, optional): continue after this conversation id — the `nextAfter` of a truncated response                                                                  |
| Roles         | `eddi-admin` or `eddi-editor`, plus edit access to the agent. MCP: `upgrade_conversations`, the same dry-run default                                                          |

**After a ZIP import or sync: dry run, check, then run it.**

```
# 1. Import (or sync) the agent, then deploy its new version and wait for READY
# 2. Preview. Nothing is written
POST /administration/production/upgradeconversations/{agentId}

# 3. Read the counts. If they match what you expect, run it
POST /administration/production/upgradeconversations/{agentId}?dryRun=false
```

```json
{
  "agentId": "5aaf98e19f7dd421ac3c7de9",
  "environment": "production",
  "dryRun": true,
  "currentVersion": 7,
  "targetGeneration": 3,
  "servingVersion": 7,
  "truncated": false,
  "nextAfter": null,
  "versions": [
    { "fromVersion": 5, "matched": 412, "eligible": 398, "upgraded": 0,
      "skipped": { "ended": 9, "awaitingHuman": 5 } },
    { "fromVersion": 6, "matched": 40, "eligible": 40, "upgraded": 0, "skipped": {} }
  ],
  "totals": { "matched": 452, "eligible": 438, "upgraded": 0, "skipped": { "ended": 9, "awaitingHuman": 5 } }
}
```

* **Target.** The generation of the agent's **latest** version. A version of that generation must be `READY` in the environment on the node that handles the request; otherwise the call answers `409` and does nothing — a conversation moved onto a generation nothing serves would fall back to its old version or deploy one on demand. A latest version stored before generations existed has no generation to move onto either (`409`; save the agent once).
* **What is written.** One field of the conversation, `compatibilityGeneration`. Nothing else — not its steps, not its version. The conversation's **next turn** runs on the newest `READY` version of the generation and records the move (`agent:switch`, the descriptor, the `eddi_conversation_agent_version_switch_count` metric), exactly as after a `compatible=true` save. A generation is **never lowered**, and conversations already on the target generation are not touched.
* **Which conversations.** `matched` counts every conversation on the chosen versions with no generation or a lower one. `eligible` are those in a state a turn can run from: `READY`, `ERROR` and `EXECUTION_INTERRUPTED`. **`ERROR` is included on purpose**: a failed turn does not block the next one (`say` refuses only ended and paused conversations), so such a conversation is live — and the new version is often what repairs it. **Skipped and counted**: `ended`; `awaitingHuman` (a resume must finish on the version that paused it); `inProgress` (a resume is running).
* **Concurrency.** Each conversation is moved by a task in *that conversation's own queue*, the one every turn goes through (cluster-wide, under its lease, with NATS), so the write never overlaps a running turn — it waits behind it. The write also moves the conversation's revision, so a turn that had loaded the conversation earlier cannot silently put the old generation back: a queued one is rebuilt over the new document when it starts, and any other writer is refused with a store conflict rather than reverting it. A conversation whose turn does not finish within `eddi.conversation-upgrade.turn-wait-ms` (30 s) is reported as `busy`; run it again.
* **Scale, the limit and the cursor.** Conversations are listed as a projection, a page at a time — never loaded in full. A call is synchronous and looks at no more than `limit` conversations (default 5000). **Keep it small enough to finish inside your reverse proxy's or load balancer's timeout** (often 60 s): when the proxy gives up the client sees a 504 but the server carries on, and re-running blind makes the numbers hard to read. When the response says `truncated: true`, call again with **`after=<nextAfter>`**. The cursor is needed because conversations that are skipped without being changed (`awaitingHuman`, `inProgress`, `busy`) stay candidates; a call that restarted from the beginning would meet them again before reaching new ones. `ended` conversations are not scanned at all: they are counted per version with one query on every call, so the preview still shows them. Dry run and real run share the shape, so the preview is the run. A dry run counts states as they are when listed; a real run may skip a few more (`changedConcurrently`, `busy`) if conversations change meanwhile.
* **Undeploying old versions afterwards.** Run the dry run again first, and undeploy an old version only when it reports `eligible: 0`. Conversations skipped as `busy`, `awaitingHuman` or `inProgress` still run on the old version; undeploying it would end them or refuse (see [Undeploying](#undeploying-old-versions-can-be-retired-freely)).
* **Audit and metrics.** Every `POST` is recorded in the audit ledger by the administrative-action record (caller, path, status). Each run writes one INFO line with the counts, and real runs add the number moved to `eddi_conversation_generation_upgrade_count`.

Only do this when the new version really can continue the old conversations — the same test as [What "compatible" means](#what-compatible-means). A conversation moved onto a version that requires state it does not have stays moved.

## **Check the deployment status of an agent:**

Check the deployment status of an agent is done through a **`GET`** to **`/administration/{environment}/deploymentstatus/{agentId}`**

Deployment status of an Agent REST API Endpoint

| Element       | Value                                                                                                                                                                                                                                                                                                                                             |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP Method   | `GET`                                                                                                                                                                                                                                                                                                                                             |
| Api endpoint  | `/administration/{environment}/deploymentstatus/{agentId}`                                                                                                                                                                                                                                                                                        |
| {environment} | (`Path parameter`):`String` deployment environment: `production` (default) or `test`                                                                                                                                                                                                                                                              |
| {agentId}     | (`Path parameter`):`String` id of the agent that you wish to **check** its **deployment status**.                                                                                                                                                                                                                                                 |
| `version`     | (`Query parameter`, **required**):`Integer` the agent version to check.                                                                                                                                                                                                                                                                           |
| Response      | JSON `{"status": ...}`, where `status` is one of `NOT_FOUND`, `IN_PROGRESS`, `ERROR` and `READY`. Add `?format=text` for the bare status word as plain text (deprecated), or `?format=detailed` to add a `failure` object (code, message, and for a missing vault grant the fix) for a deployment in `ERROR`, to a caller who may edit the agent. |

### Example\*:\*

*Request URL*

`http://localhost:7070/administration/production/deploymentstatus/5aaf98e19f7dd421ac3c7de9?version=1`

*Response Body*

`{"status":"READY"}`

*Response Code*

`200`

## **List all deployed Agents:**

To list all deployed Agents, send a `GET` to `/deploymentstore/deployments`:

### List of Deployed Agents REST API Endpoint

| Element      | Value                          |
| ------------ | ------------------------------ |
| HTTP Method  | `GET`                          |
| API endpoint | `/deploymentstore/deployments` |

### Example:

*Request URL*

`http://localhost:7070/deploymentstore/deployments`

*Response Code*

`200`

*Response Body*

```json
[
  {
    "agentId": "5aaf90e29f7dd421ac3c7dd4",
    "agentVersion": 1,
    "environment": "production",
    "deploymentStatus": "deployed"
  },
  {
    "agentId": "5aaf98e19f7dd421ac3c7de9",
    "agentVersion": 1,
    "environment": "production",
    "deploymentStatus": "deployed"
  }
]
```

***

## Deleting an Agent

### Simple Delete (Soft-Delete)

Marks the agent as deleted but keeps it in the database. The agent can potentially be restored.

| Element      | Value                                                                                       |
| ------------ | ------------------------------------------------------------------------------------------- |
| HTTP Method  | `DELETE`                                                                                    |
| API endpoint | `/agentstore/agents/{id}?version={version}`                                                 |
| {id}         | (`Path parameter`) `String` agent ID                                                        |
| version      | (`Query parameter`) `Integer` version                                                       |
| permanent    | (`Query parameter`) `Boolean` default `false`. If `true`, permanently removes from database |

```
DELETE /agentstore/agents/5aaf98e19f7dd421ac3c7de9?version=1
→ 200 OK (soft-deleted)

DELETE /agentstore/agents/5aaf98e19f7dd421ac3c7de9?version=1&permanent=true
→ 200 OK (permanently removed)
```

### Cascade Delete

Deletes the agent **and all its child resources** in one operation. This is the recommended way to fully clean up an agent and avoid orphaned resources.

```
Agent
 └── Workflow 1
 │    ├── Behavior Set
 │    ├── HTTP Calls
 │    ├── Output Set
 │    ├── LLM Config
 │    ├── Property Setter
 │    └── Parser (with dictionaries)
 └── Workflow 2
      └── ...
```

| Element      | Value                                                                                                   |
| ------------ | ------------------------------------------------------------------------------------------------------- |
| HTTP Method  | `DELETE`                                                                                                |
| API endpoint | `/agentstore/agents/{id}?version={version}&cascade=true&permanent=true`                                 |
| cascade      | (`Query parameter`) `Boolean` default `false`. If `true`, deletes workflows and all extension resources |
| permanent    | (`Query parameter`) `Boolean` default `false`. Applies to the **agent only** — see below                |

#### Example

```
DELETE /agentstore/agents/5aaf98e19f7dd421ac3c7de9?version=1&cascade=true&permanent=true
→ 200 OK
```

This will:

1. Read the agent configuration to discover its workflows
2. Resolve each workflow reference to the workflow's **current** version — references are version-pinned and are not re-pointed when the workflow is edited, so the pinned version frequently is not the one that exists
3. Skip any workflow another agent still references (at any version), and any workflow with no live version left
4. Delete the agent itself
5. Delete the agent's schedules, then soft-delete each remaining workflow, which cascades the same way into its extensions (behavior sets, HTTP calls, output sets, LLM configs, property setters, parser dictionaries)

The agent is deleted **before** the schedules and workflows. A failure in step 5 is logged as a warning and does not roll the agent deletion back, so the agent can be gone while some of its workflows remain.

> **`permanent=true` never cascades.** It applies to the resource named in the request — every version and every history row of that agent, plus its Ed25519 signing keys in the secrets vault. Those keys are destroyed for good: an agent restored from a backup afterwards cannot sign until an admin generates it a new key with `POST /agentstore/agents/{id}/signing-keys` (`eddi-admin`) and turns `security.signInterAgentMessages` back on. Cascaded resources are always **soft-deleted**, whatever `permanent` says: the "is anyone else using this?" check can only speak for the versions it can see, while `permanent` erases all of them. To erase a shared resource, delete it explicitly, without cascade.

> **`permanent=true` requires the current version.** It is ID-scoped, so a request naming a stale version is refused with **409** before anything is deleted — as `cascade=true` already was. A resource that is already soft-deleted has no current version to be stale against: purging its remaining history still works (and does remove its vault keys), and the cascade is skipped rather than refused.

> **Note:** Cascade delete is error-tolerant. If individual resource deletions fail (e.g., resource already deleted), the operation continues and the agent itself is still deleted. Failures are logged server-side.

> **Safety:** Cascade delete checks for shared references before deleting each resource. If a workflow is used by another agent, or an extension resource is used by another workflow, it will be **skipped** (not deleted). Only resources exclusively owned by the deleted agent are removed.

### Cascade Delete for Workflows

Workflows can also be individually cascade-deleted:

```
DELETE /workflowstore/workflows/{id}?version={version}&cascade=true
→ 200 OK (workflow deleted, exclusively-owned extension resources soft-deleted)
```

The workflow delete reports how many extensions the cascade left alone — still referenced, not routable, or a delete that failed — in the `X-Cascade-Skipped` response header. It is absent when nothing was skipped, so a cascade that removed everything it walked no longer looks exactly like one that removed half the graph. The header is **not** propagated onto the agent-delete response; the workflows a cascading agent delete skipped are named in the server log.

### Important: Undeploy Before Deleting

If the agent is currently deployed, you should **undeploy** it first:

```
POST /administration/production/undeploy/{agentId}?version=1&endAllActiveConversations=true
→ 202 Accepted

DELETE /agentstore/agents/{agentId}?version=1&cascade=true&permanent=true
→ 200 OK
```

***

## Orphan Detection and Cleanup

Over time, resources can become orphaned — they exist in the database but are no longer referenced by any agent or workflow. The orphan admin endpoint helps detect and clean up these resources.

### Scan for Orphans (Dry Run)

```
GET /administration/orphans
→ 200 OK
```

Returns a report listing all unreferenced resources across all stores (workflows, behavior sets, HTTP calls, output sets, LLMs, property setters, dictionaries, parsers).

| Element        | Value                                                                                      |
| -------------- | ------------------------------------------------------------------------------------------ |
| HTTP Method    | `GET`                                                                                      |
| API endpoint   | `/administration/orphans`                                                                  |
| includeDeleted | (`Query parameter`) `Boolean` default `false`. `true` also includes soft-deleted resources |

**Example Response:**

```json
{
  "totalOrphans": 3,
  "deletedCount": 0,
  "scanComplete": true,
  "scanWarning": null,
  "orphans": [
    {
      "resourceUri": "eddi://ai.labs.workflow/workflowstore/workflows/abc123?version=1",
      "type": "ai.labs.workflow",
      "name": "Unused Workflow",
      "deleted": false
    },
    {
      "resourceUri": "eddi://ai.labs.rules/rulestore/rulesets/def456?version=1",
      "type": "ai.labs.rules",
      "name": "Old Behavior Set",
      "deleted": true
    }
  ]
}
```

> **Check `scanComplete` before acting on this list.** It is `false` when part of the traversal failed — an unreadable agent, workflow or parser document, an unreadable deployment record, a store type past the scan ceiling — and `scanWarning` then says which. Every failure *removes* entries from the referenced set, so a partial scan lists live, in-use resources as orphans. The read-only scan still answers so you can see the cause; the purge refuses outright (409, below).

What counts as a reference: the current version of every agent, the current version of every workflow, **and** every agent version named by a `deployed` deployment record together with the exact workflow versions that version pins. Dictionaries are also referenced from **parser documents** (`extensions.dictionaries[n].config.uri`): every parser document's current version counts, and so does the parser version a workflow step pins. A parser that is itself an orphan keeps its dictionaries until it has been purged, so the next purge reaches them; an unreadable parser document makes the scan incomplete. A resource referenced only by a superseded *and* undeployed agent version is still reported as an orphan — history is not a reference — so rolling an agent back to an older version after a purge can leave it unresolvable. References are compared by resource identity, not by URI string, so a version-pinned reference protects every version of the resource, and a reference written with a legacy authority (`ai.labs.behavior`, `ai.labs.httpcalls`, `ai.labs.regulardictionary`) protects the same resource as the canonical one.

### Purge Orphans

```
DELETE /administration/orphans
→ 200 OK
```

Permanently deletes all orphaned resources. This is **irreversible** — it removes the current document *and* its entire version history.

| Element        | Value                                                                                                       |
| -------------- | ----------------------------------------------------------------------------------------------------------- |
| HTTP Method    | `DELETE`                                                                                                    |
| API endpoint   | `/administration/orphans`                                                                                   |
| includeDeleted | (`Query parameter`) `Boolean` default `false`. `true` also purges soft-deleted resources                    |
| 409 Conflict   | Returned when the reference scan is incomplete; **nothing is deleted**. Body: `{"error":"incomplete_scan"}` |

Pass the **same** `includeDeleted` value you used for the scan, so the purge acts on the set you reviewed.

In the Manager (**Orphans** page) each listed resource links to its detail page so you can inspect it before purging, and **Purge All** opens a confirmation dialog that requires typing the number of orphans. A failed scan is shown as an error with the server's message (it never falls back to the empty "Scan your platform" state), and a refused purge shows the server's reason, such as the 409 above.

> **Note:** `includeDeleted` is not an *equality* filter — `true` matched only soft-deleted resources instead of adding them to the live ones — and this endpoint defaulted to `true` while the scan defaulted to `false`, so a scan followed by a purge operated on **disjoint** sets. `true` now means "live and soft-deleted", and the default is `false`. A client relying on the old default now purges *less*; pass `includeDeleted=true` to restore the wider sweep.

The purge refuses with **409** rather than proceeding when the referenced-resource scan could not be completed (an unreadable Agent, workflow or parser document, an unreadable deployment record, or a store type exceeding the scan ceiling). A partial reference set makes live, in-use resources look unreferenced, so purging against one could destroy working configuration.

Each candidate is re-checked against a fresh reverse lookup immediately before it is deleted, so a resource that became referenced between the scan and the purge is skipped rather than erased. That narrows the mark/sweep window rather than closing it: there is no deployment-wide write lock, because taking one would block configuration editing for the duration of an administrative sweep.

The purge also removes each purged resource's descriptor, so the sweep converges. Descriptors are normally only *flagged* as deleted — the HTTP delete filter reads one back afterwards and a missing row would answer 404 to a delete that succeeded — but that filter does not run for `/administration/orphans`, and a flagged descriptor whose resource is gone is exactly what `includeDeleted=true` selects. Left in place, every purged resource came back as an orphan on the next `includeDeleted=true` run and was counted as deleted again, forever.
