# Feature Spec: CLI `delete` Command with Deterministic Feature Cleanup (AOP)

> **Purpose of this document**: Define an implementation-ready, safety-first `aop delete` command that replaces the current CLI placeholder behavior with deterministic cleanup of feature runtime artifacts, index/session references, locks/queue residue, and optional git worktree/branch state.

---

## 1. Objectives

### 1.1 Must-Have Outcomes

- Provide a real `aop delete` command for feature cleanup.
- Keep deterministic behavior aligned with MCP/kernel architecture:
  - schema-validated tool contracts
  - atomic canonical state mutation
  - role authorization and idempotent mutation semantics
- Delete command MUST safely clean orchestration residue for a feature:
  - feature runtime files
  - index references (`active`, `blocked`, `merged`, blocked queue entries, runtime session assignment)
  - held lock references and lock leases
  - optional git worktree cleanup
  - optional local branch cleanup
- Command MUST be safe-by-default (preview path before destructive mutation).
- Preserve current `run/status/resume/stop` behavior while introducing `delete`.

### 1.2 Non-Goals

- No change to orchestration algorithm, gate policy, or merge semantics.
- No implementation of remote branch deletion.
- No stop-command redesign in this phase beyond clarifying placeholder status.

---

## 2. Current State Analysis (Codebase)

1. CLI supports only `run|status|resume|stop` (`apps/control-plane/src/interfaces/cli/bootstrap.ts`).
2. Placeholder behavior exists in `StopCommandHandler` only:
   - returns `{ status: "stop_not_implemented_yet" }`
   - no lease/session/worktree cleanup (`apps/control-plane/src/cli/stop-command-handler.ts`).
3. There is no `delete` command parser path and no `DeleteCommandHandler`.
4. There is no MCP tool contract for feature deletion:
   - no `feature.delete` in `agentic/orchestrator/tools/catalog.json`
   - no input/output schemas for deletion.
5. Kernel/service layer has no cohesive feature cleanup use case:
   - no API for deleting feature artifacts + index/runtime/lock residue in one deterministic operation.

---

## 3. CLI Contract for `delete`

### 3.1 Primary Command

```bash
aop delete --feature-id <feature_id> [options]
```

### 3.2 Options

- `--feature-id <id>` (required)
- `--dry-run` (optional; default when `--yes` is absent)
- `--yes` (required for destructive execution)
- `--remove-worktree` (optional; default `true`)
- `--remove-branch <none|safe|force>` (optional; default `none`)
- `--transport <mcp|inprocess>` (existing behavior retained)

### 3.3 Safety Rules

- If `--yes` is not provided, command MUST run preview-only and perform no mutations.
- `--dry-run` and `--yes` MAY both be provided only if `--dry-run=true` semantics are explicitly chosen; otherwise fail `invalid_cli_args`.
- If a fresh active run lease exists, deletion MUST fail with `run_already_active` (unless later explicitly expanded by policy in a separate spec).

### 3.4 Response Contract

On success:

- `ok: true`
- `data.command: "delete"`
- `data.feature_id`
- `data.dry_run`
- `data.plan` (preview) and/or `data.applied` (execution)
- `data.summary` with explicit booleans/counts:
  - `feature_dir_removed`
  - `worktree_removed`
  - `branch_removed`
  - `index_updated`
  - `locks_released[]`
  - `blocked_queue_entries_removed`
  - `runtime_session_assignment_removed`

On failure:

- standard normalized error envelope already used by CLI.

---

## 4. Core Capabilities (Required)

1. Deterministic preview:
   - enumerate exactly what will be removed/updated before execution.
2. Active-run guard:
   - block deletion when lease is fresh to prevent state/session races.
3. Lock and queue residue cleanup:
   - release held locks for target feature.
   - remove blocked-queue entries for target feature.
4. Canonical index/session cleanup:
   - remove feature from `active`, `blocked`, `merged`.
   - remove `runtime_sessions.feature_sessions[feature_id]`.
5. Runtime artifact deletion:
   - remove feature runtime directory recursively.
6. Git cleanup options:
   - remove feature worktree (`git worktree remove --force`).
   - optional local branch delete (`git branch -d` safe, `-D` force).
7. Idempotent mutation behavior:
   - tool-level mutation participates in existing operation ledger semantics.

---

## 5. Optimal Architecture

### 5.1 Implement as MCP Mutating Tool, not CLI-Local FS Logic

Add new tool: `feature.delete`

- Rationale:
  - keeps deterministic mutation in control plane (kernel/service), not ad-hoc CLI code
  - preserves MCP/in-process parity
  - preserves RBAC + schema + idempotency guarantees
  - enables future orchestrator/system-initiated cleanup reuse

### 5.2 Add Dedicated Service

- New application service:
  - `apps/control-plane/src/application/services/feature-deletion-service.ts`
- Kernel registers tool handler that delegates to service.
- Service owns cleanup algorithm and returns structured deterministic summary.

### 5.3 Path Layout Compatibility

- Service MUST use kernel/path accessors (`featurePath`, `worktreePath`, etc.) and MUST NOT hardcode layout roots.
- This keeps compatibility with current `agentic/features/**` and upcoming `.aop/**` runtime-root migration spec.

---

## 6. Tool Contract Additions

### 6.1 Catalog and Metadata

- Add `feature.delete` entry to:
  - `agentic/orchestrator/tools/catalog.json`
  - `apps/control-plane/src/core/constants.ts` (`TOOLS.FEATURE_DELETE`)
  - `apps/control-plane/src/application/tools/tool-metadata.ts` (mutating, requires operation id)
  - `agentic/orchestrator/policy.yaml` RBAC:
    - allow `system`
    - optional `orchestrator` (recommended)

### 6.2 Schemas

Add:

- `agentic/orchestrator/tools/schemas/input/feature.delete.input.schema.json`
- `agentic/orchestrator/tools/schemas/output/feature.delete.output.schema.json`

Input MUST include:

- `operation_id`
- `feature_id`
- execution mode fields (`dry_run`/`confirm` or equivalent)
- cleanup toggles (`remove_worktree`, `remove_branch`)

Output MUST include:

- target `feature_id`
- mode (`dry_run`)
- deterministic summary fields listed in Section 3.4.

### 6.3 Tools Markdown and Contract Validation

- Regenerate `agentic/orchestrator/tools.md`.
- `npm run validate:mcp-contracts` MUST pass with the new tool included.

---

## 7. Deterministic Delete Algorithm (Normative)

For target `feature_id`:

1. Validate arguments and feature identifier.
2. Load index/runtime sessions and fail if run lease is fresh.
3. Build preflight snapshot:
   - feature files present/missing
   - held locks in state
   - blocked queue entries
   - runtime session assignment
   - worktree/branch existence
4. If preview mode: return preflight summary only.
5. Execution mode:
   - release each held lock via existing lock service path
   - remove blocked queue entries for feature
   - atomically update index:
     - remove feature from `active|blocked|merged`
     - clear any `locks`/`lock_leases` still pointing to feature
     - remove `runtime_sessions.feature_sessions[feature_id]`
     - increment index version and timestamp
   - remove feature runtime directory recursively
   - remove worktree if enabled
   - remove local branch per `remove_branch` policy
6. Return applied summary with explicit per-step results.

---

## 8. File-Level Change Targets

- CLI:
  - `apps/control-plane/src/cli/cli-argument-parser.ts`
  - `apps/control-plane/src/cli/types.ts`
  - `apps/control-plane/src/cli/delete-command-handler.ts` (new)
  - `apps/control-plane/src/interfaces/cli/bootstrap.ts`
- Core/Application:
  - `apps/control-plane/src/core/constants.ts`
  - `apps/control-plane/src/core/kernel.ts`
  - `apps/control-plane/src/application/services/feature-deletion-service.ts` (new)
  - `apps/control-plane/src/application/tools/tool-metadata.ts`
  - `apps/control-plane/src/core/error-codes.ts` (if new delete-specific codes are introduced)
- MCP contracts:
  - `agentic/orchestrator/tools/catalog.json`
  - `agentic/orchestrator/tools/schemas/input/feature.delete.input.schema.json` (new)
  - `agentic/orchestrator/tools/schemas/output/feature.delete.output.schema.json` (new)
  - `agentic/orchestrator/tools.md` (generated)
  - `agentic/orchestrator/policy.yaml` (rbac entries as needed)
- Docs:
  - `README.md`

---

## 9. Test Plan (Vitest, Normative)

### 9.1 CLI Tests

- `delete` command recognized by parser/bootstrap.
- `--feature-id` required.
- preview mode default (no `--yes`) performs no mutation.
- destructive mode requires explicit confirmation.
- invalid option combinations return `invalid_cli_args`.

### 9.2 Service and Kernel Tests

- delete fails when fresh run lease exists (`run_already_active`).
- delete releases locks and removes blocked-queue entries.
- delete removes index membership and feature session assignment.
- delete removes feature directory and optional worktree.
- branch deletion mode `safe` vs `force` behavior.
- idempotent re-run behavior on already-deleted feature (defined and tested).

### 9.3 MCP Contract Tests

- `feature.delete` listed in tools list with expected mutating contract.
- input/output schema validation enforced.
- role authorization intersection behavior verified.

---

## 10. Milestones

### M23: CLI + Contract Surface

- Add `delete` command parsing/dispatch and command handler.
- Add tool catalog entry + schemas + generated tools doc.

### M24: Service Implementation

- Implement `FeatureDeletionService` and kernel handler wiring.
- Implement deterministic cleanup algorithm and summaries.

### M25: Safety and Git Cleanup

- Implement fresh-lease guard, preview/confirm flow, optional worktree/branch cleanup.

### M26: Docs + Validation

- Update README command docs and examples.
- Re-verify with `lint`, `typecheck`, `test`, and `validate:mcp-contracts`.

---

## 11. Acceptance Criteria

1. `aop delete --feature-id <id>` exists and returns deterministic preview output by default.
2. Destructive execution requires explicit confirmation and returns explicit cleanup summary.
3. No deletion proceeds while a fresh run lease is active.
4. Feature deletion clears feature state from index + runtime session assignment + blocked queue + lock residue.
5. Optional worktree/branch cleanup behaves as specified.
6. MCP contract artifacts and validation gates remain green.
7. Existing `run/status/resume` behavior remains unchanged; `stop` placeholder remains explicitly documented until separately implemented.

---

## 12. Risks and Mitigations

- Risk: accidental destructive deletion.
  - Mitigation: preview-by-default + explicit `--yes` requirement.
- Risk: deleting during active run corrupts orchestration state.
  - Mitigation: hard fresh-lease guard (`run_already_active`).
- Risk: partial cleanup leaves stale references.
  - Mitigation: ordered deterministic algorithm + summary assertions + tests.
- Risk: contract drift after adding tool.
  - Mitigation: catalog/schema/tools.md regeneration and contract CI validation.

---

## 13. Dependency Notes

- Aligns with:
  - `spec-files/agentic_orchestrator_spec.md` (CLI/runtime deterministic contract)
  - `spec-files/agentic_orchestrator_mcp_formalization_spec.md` (formal tool contract + idempotency requirements)
  - `spec-files/agentic_orchestrator_oop_refactor_spec.md` (service-oriented extension points)
  - `spec-files/agentic_orchestrator_dot_aop_generated_artifacts_spec.md` (runtime path abstraction compatibility)
