> ## Documentation Index
> Fetch the complete documentation index at: https://codluv.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# cleo — Functions

> Functions and classes for the cleo package

Functions and classes exported by this package.

## engineError(code, message, options)

Create a typed engine error result with pino logging and correct exit code.

**Signature**

```typescript theme={null}
<T>(code: string, message: string, options?: { details?: Record<string, unknown>; fix?: string; alternatives?: Array<{ action: string; command: string; }>; }) => EngineResult<T>
```

**Parameters**

| Name      | Type                          | Description                                     |
| --------- | ----------------------------- | ----------------------------------------------- |
| `code`    | `string`                      | String error code (e.g., 'E\_NOT\_FOUND')       |
| `message` | `string`                      | Human-readable error message                    |
| `options` | `: { details?: Record<string` | Optional details, fix command, and alternatives |

**Returns** — EngineResult with success=false and properly structured error

**Example**

```typescript theme={null}
import { engineError } from './_error.js';

return engineError('E_NOT_FOUND', `Task ${id} not found`, {
  fix: `cleo show ${id}`,
  details: { taskId: id },
});
```

## engineSuccess(data)

Create an engine success result.

**Signature**

```typescript theme={null}
<T>(data: T) => EngineResult<T>
```

**Parameters**

| Name   | Type | Description     |
| ------ | ---- | --------------- |
| `data` | `T`  | The result data |

**Returns** — EngineResult with success=true

**Example**

```typescript theme={null}
import { engineSuccess } from './_error.js';

return engineSuccess({ tasks: filteredTasks, total: count });
```

## taskShow(projectRoot, taskId)

Get a single task by ID.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ task: TaskRecord; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `taskId`      | `string` | Task identifier (e.g. "T001")     |

**Returns** — EngineResult containing the task record

**Example**

```typescript theme={null}
const result = await taskShow('/project', 'T42');
if (result.success) console.log(result.data.task.title);
```

## taskList(projectRoot, params)

List tasks with optional filters.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { parent?: string; status?: string; priority?: string; type?: string; phase?: string; label?: string; children?: boolean; limit?: number; offset?: number; compact?: boolean; }) => Promise<EngineResult<{ tasks: TaskRecord[] | CompactTask[]; total: number; filtered: number; }>>
```

**Parameters**

| Name          | Type                                                                                                                                                                                | Description                                        |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `projectRoot` | `string`                                                                                                                                                                            | Absolute path to the project root                  |
| `params`      | `: { parent?: string; status?: string; priority?: string; type?: string; phase?: string; label?: string; children?: boolean; limit?: number; offset?: number; compact?: boolean; }` | Optional filter, pagination, and format parameters |

**Returns** — EngineResult with task array, total count, and filtered count

**Example**

```typescript theme={null}
const result = await taskList('/project', { status: 'active', limit: 10 });
```

## taskFind(projectRoot, query, limit, options)

Fuzzy search tasks by title/description/ID.

**Signature**

```typescript theme={null}
(projectRoot: string, query: string, limit?: number, options?: { id?: string; exact?: boolean; status?: string; includeArchive?: boolean; offset?: number; }) => Promise<EngineResult<{ results: MinimalTaskRecord[]; total: number; }>>
```

**Parameters**

| Name          | Type                                                                                              | Description                                              |
| ------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| `projectRoot` | `string`                                                                                          | Absolute path to the project root                        |
| `query`       | `string`                                                                                          | Search string to match against title, description, or ID |
| `limit`       | `: number`                                                                                        | Maximum number of results (defaults to 20)               |
| `options`     | `: { id?: string; exact?: boolean; status?: string; includeArchive?: boolean; offset?: number; }` | Additional search options                                |

**Returns** — EngineResult with matching tasks and total count

**Example**

```typescript theme={null}
const result = await taskFind('/project', 'authentication', 10);
```

## taskExists(projectRoot, taskId)

Check if a task exists.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ exists: boolean; taskId: string; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `taskId`      | `string` | Task identifier to check          |

**Returns** — EngineResult with exists flag and the queried taskId

**Example**

```typescript theme={null}
const result = await taskExists('/project', 'T42');
if (result.success && result.data.exists) { console.log('exists'); }
```

## taskCreate(projectRoot, params)

Create a new task.

**Signature**

```typescript theme={null}
(projectRoot: string, params: { title: string; description: string; parent?: string; depends?: string[]; priority?: string; labels?: string[]; type?: string; phase?: string; size?: string; acceptance?: string[]; notes?: string; files?: string[]; dryRun?: boolean; }) => Promise<EngineResult<{ task: TaskRecord; duplicate: boolean; dryRun?: boolean; }>>
```

**Parameters**

| Name          | Type                                                                                                                                                                                                                                          | Description                       |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| `projectRoot` | `string`                                                                                                                                                                                                                                      | Absolute path to the project root |
| `params`      | `{ title: string; description: string; parent?: string; depends?: string[]; priority?: string; labels?: string[]; type?: string; phase?: string; size?: string; acceptance?: string[]; notes?: string; files?: string[]; dryRun?: boolean; }` | Task creation parameters          |

**Returns** — EngineResult with the created task record and duplicate flag

**Example**

```typescript theme={null}
const result = await taskCreate('/project', {
  title: 'Implement auth',
  description: 'Add JWT-based authentication',
  priority: 'high',
});
```

## taskUpdate(projectRoot, taskId, updates)

Update a task's fields.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, updates: { title?: string; description?: string; status?: string; priority?: string; notes?: string; labels?: string[]; addLabels?: string[]; removeLabels?: string[]; depends?: string[]; addDepends?: string[]; removeDepends?: string[]; acceptance?: string[]; parent?: string | null; type?: string; size?: string; }) => Promise<EngineResult<{ task: TaskRecord; changes?: string[]; }>>
```

**Parameters**

| Name          | Type                                                                                                                                                                                                                                                                                                                 | Description                                         |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| `projectRoot` | `string`                                                                                                                                                                                                                                                                                                             | Absolute path to the project root                   |
| `taskId`      | `string`                                                                                                                                                                                                                                                                                                             | Task identifier to update                           |
| `updates`     | `{ title?: string; description?: string; status?: string; priority?: string; notes?: string; labels?: string[]; addLabels?: string[]; removeLabels?: string[]; depends?: string[]; addDepends?: string[]; removeDepends?: string[]; acceptance?: string[]; parent?: string \| null; type?: string; size?: string; }` | Fields to update (only provided fields are changed) |

**Returns** — EngineResult with the updated task record and list of changes

**Example**

```typescript theme={null}
const result = await taskUpdate('/project', 'T42', { status: 'active' });
```

## taskComplete(projectRoot, taskId, notes)

Complete a task (set status to done).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, notes?: string) => Promise<EngineResult<{ task: TaskRecord; autoCompleted?: string[]; unblockedTasks?: Array<{ id: string; title: string; }>; }>>
```

**Parameters**

| Name          | Type       | Description                       |
| ------------- | ---------- | --------------------------------- |
| `projectRoot` | `string`   | Absolute path to the project root |
| `taskId`      | `string`   | Task identifier to complete       |
| `notes`       | `: string` | Optional completion notes         |

**Returns** — EngineResult with the completed task, auto-completed parents, and unblocked tasks

**Example**

```typescript theme={null}
const result = await taskComplete('/project', 'T42', 'All tests passing');
```

## taskDelete(projectRoot, taskId, force)

Delete a task.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, force?: boolean) => Promise<EngineResult<{ deletedTask: TaskRecord; deleted: boolean; cascadeDeleted?: string[]; }>>
```

**Parameters**

| Name          | Type        | Description                                     |
| ------------- | ----------- | ----------------------------------------------- |
| `projectRoot` | `string`    | Absolute path to the project root               |
| `taskId`      | `string`    | Task identifier to delete                       |
| `force`       | `: boolean` | When true, enables cascade deletion of children |

**Returns** — EngineResult with the deleted task and optional cascade info

**Example**

```typescript theme={null}
const result = await taskDelete('/project', 'T42', true);
```

## taskArchive(projectRoot, taskId, before)

Archive completed tasks. Moves done/cancelled tasks from active task data to archive.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string, before?: string) => Promise<EngineResult<{ archivedCount: number; archivedTasks: Array<{ id: string; }>; }>>
```

**Parameters**

| Name          | Type       | Description                                                         |
| ------------- | ---------- | ------------------------------------------------------------------- |
| `projectRoot` | `string`   | Absolute path to the project root                                   |
| `taskId`      | `: string` | Optional specific task ID to archive                                |
| `before`      | `: string` | Optional ISO date string; archives tasks completed before this date |

**Returns** — EngineResult with count and list of archived task IDs

**Example**

```typescript theme={null}
const result = await taskArchive('/project', undefined, '2026-01-01');
```

## taskNext(projectRoot, params)

Suggest next task to work on based on priority, phase alignment, age, and dependency readiness.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { count?: number; explain?: boolean; }) => Promise<EngineResult<{ suggestions: Array<{ id: string; title: string; priority: string; phase: string | null; score: number; reasons?: string[]; }>; totalCandidates: number; }>>
```

**Parameters**

| Name          | Type                                       | Description                           |
| ------------- | ------------------------------------------ | ------------------------------------- |
| `projectRoot` | `string`                                   | Absolute path to the project root     |
| `params`      | `: { count?: number; explain?: boolean; }` | Optional count limit and explain flag |

**Returns** — EngineResult with scored suggestions and total candidate count

**Example**

```typescript theme={null}
const result = await taskNext('/project', { count: 3, explain: true });
```

## taskBlockers(projectRoot, params)

Show blocked tasks and analyze blocking chains.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { analyze?: boolean; limit?: number; }) => Promise<EngineResult<{ blockedTasks: Array<{ id: string; title: string; status: string; depends?: string[]; blockingChain: string[]; }>; criticalBlockers: Array<{ id: string; title: string; blocksCount: number; }>; summary: string; total: number; limit: number; }>>
```

**Parameters**

| Name          | Type                                       | Description                            |
| ------------- | ------------------------------------------ | -------------------------------------- |
| `projectRoot` | `string`                                   | Absolute path to the project root      |
| `params`      | `: { analyze?: boolean; limit?: number; }` | Optional analysis and limit parameters |

**Returns** — EngineResult with blocked tasks, critical blockers, and summary

**Example**

```typescript theme={null}
const result = await taskBlockers('/project', { analyze: true });
```

## taskTree(projectRoot, taskId)

Build hierarchy tree.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string) => Promise<EngineResult>
```

**Parameters**

| Name          | Type       | Description                       |
| ------------- | ---------- | --------------------------------- |
| `projectRoot` | `string`   | Absolute path to the project root |
| `taskId`      | `: string` | Optional root task ID for subtree |

**Returns** — EngineResult with the hierarchical tree data

**Example**

```typescript theme={null}
const result = await taskTree('/project', 'T1');
```

## taskDeps(projectRoot, taskId)

Show dependencies for a task - both what it depends on and what depends on it.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ taskId: string; dependsOn: Array<{ id: string; title: string; status: string; }>; dependedOnBy: Array<{ id: string; title: string; status: string; }>; unresolvedDeps: string[]; allDepsReady: boolean; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `taskId`      | `string` | Task identifier to inspect        |

**Returns** — EngineResult with dependency information in both directions

**Example**

```typescript theme={null}
const result = await taskDeps('/project', 'T42');
```

## taskRelates(projectRoot, taskId)

Show task relations (existing relates entries).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ taskId: string; relations: Array<{ taskId: string; type: string; reason?: string; }>; count: number; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `taskId`      | `string` | Task identifier to inspect        |

**Returns** — EngineResult with relations array and count

**Example**

```typescript theme={null}
const result = await taskRelates('/project', 'T42');
```

## taskRelatesAdd(projectRoot, taskId, relatedId, type, reason)

Add a relation between two tasks.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, relatedId: string, type: string, reason?: string) => Promise<EngineResult<{ from: string; to: string; type: string; added: boolean; }>>
```

**Parameters**

| Name          | Type       | Description                              |
| ------------- | ---------- | ---------------------------------------- |
| `projectRoot` | `string`   | Absolute path to the project root        |
| `taskId`      | `string`   | Source task identifier                   |
| `relatedId`   | `string`   | Target task identifier                   |
| `type`        | `string`   | Relation type (e.g. "blocks", "related") |
| `reason`      | `: string` | Optional explanation for the relation    |

**Returns** — EngineResult confirming the relation was added

**Example**

```typescript theme={null}
const result = await taskRelatesAdd('/project', 'T42', 'T43', 'blocks', 'Needs auth first');
```

## taskAnalyze(projectRoot, taskId, params)

Analyze a task for description quality, missing fields, and dependency health.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string, params?: { tierLimit?: number; }) => Promise<EngineResult<{ recommended: { id: string; title: string; leverage: number; reason: string; } | null; bottlenecks: Array<{ id: string; title: string; blocksCount: number; }>; tiers: { critical: Array<{ id: string; title: string; leverage: number; }>; high: Array<{ id: string; title: string; leverage: number; }>; normal: Array<{ id: string; title: string; leverage: number; }>; }; metrics: { totalTasks: number; actionable: number; blocked: number; avgLeverage: number; }; tierLimit: number; }>>
```

**Parameters**

| Name          | Type                        | Description                       |
| ------------- | --------------------------- | --------------------------------- |
| `projectRoot` | `string`                    | Absolute path to the project root |
| `taskId`      | `: string`                  | Optional specific task to analyze |
| `params`      | `: { tierLimit?: number; }` | Optional analysis parameters      |

**Returns** — EngineResult with recommended task, bottlenecks, tiers, and metrics

**Example**

```typescript theme={null}
const result = await taskAnalyze('/project');
```

## taskImpact(projectRoot, change, matchLimit)

Predict downstream impact of a free-text change description.  Delegates to `predictImpact` from the intelligence module. Uses keyword matching against task titles/descriptions, then traces the reverse dependency graph for transitive effects.

**Signature**

```typescript theme={null}
(projectRoot: string, change: string, matchLimit?: number) => Promise<EngineResult<ImpactReport>>
```

**Parameters**

| Name          | Type       | Description                                  |
| ------------- | ---------- | -------------------------------------------- |
| `projectRoot` | `string`   | Project root directory                       |
| `change`      | `string`   | Free-text description of the proposed change |
| `matchLimit`  | `: number` | Maximum seed tasks to match (default: 5)     |

**Returns** — Impact prediction report

**Example**

```typescript theme={null}
const result = await taskImpact('/project', 'Refactor authentication module');
```

## taskRestore(projectRoot, taskId, params)

Restore a cancelled task back to pending.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { cascade?: boolean; notes?: string; }) => Promise<EngineResult<{ task: string; restored: string[]; count: number; }>>
```

**Parameters**

| Name          | Type                                       | Description                        |
| ------------- | ------------------------------------------ | ---------------------------------- |
| `projectRoot` | `string`                                   | Absolute path to the project root  |
| `taskId`      | `string`                                   | Task identifier to restore         |
| `params`      | `: { cascade?: boolean; notes?: string; }` | Optional cascade and notes options |

**Returns** — EngineResult with restored task IDs and count

**Example**

```typescript theme={null}
const result = await taskRestore('/project', 'T42', { cascade: true });
```

## taskUnarchive(projectRoot, taskId, params)

Move an archived task back to active task data with status 'done' (or specified status).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { status?: string; preserveStatus?: boolean; }) => Promise<EngineResult<{ task: string; unarchived: boolean; title: string; status: string; }>>
```

**Parameters**

| Name          | Type                                               | Description                         |
| ------------- | -------------------------------------------------- | ----------------------------------- |
| `projectRoot` | `string`                                           | Absolute path to the project root   |
| `taskId`      | `string`                                           | Archived task identifier to restore |
| `params`      | `: { status?: string; preserveStatus?: boolean; }` | Optional status override parameters |

**Returns** — EngineResult with the unarchived task info

**Example**

```typescript theme={null}
const result = await taskUnarchive('/project', 'T42', { status: 'pending' });
```

## taskReorder(projectRoot, taskId, position)

Change task position within its sibling group.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, position: number) => Promise<EngineResult<{ task: string; reordered: boolean; newPosition: number; totalSiblings: number; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `taskId`      | `string` | Task identifier to reorder        |
| `position`    | `number` | Target zero-based position        |

**Returns** — EngineResult with new position and total siblings

**Example**

```typescript theme={null}
const result = await taskReorder('/project', 'T42', 0); // move to first
```

## taskReparent(projectRoot, taskId, newParentId)

Move task under a different parent.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, newParentId: string | null) => Promise<EngineResult<{ task: string; reparented: boolean; oldParent: string | null; newParent: string | null; newType?: string; }>>
```

**Parameters**

| Name          | Type             | Description                          |
| ------------- | ---------------- | ------------------------------------ |
| `projectRoot` | `string`         | Absolute path to the project root    |
| `taskId`      | `string`         | Task identifier to move              |
| `newParentId` | `string \| null` | New parent task ID, or null for root |

**Returns** — EngineResult with old and new parent information

**Example**

```typescript theme={null}
const result = await taskReparent('/project', 'T42', 'T1');
```

## taskPromote(projectRoot, taskId)

Promote a subtask to task or task to root (remove parent).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ task: string; promoted: boolean; previousParent: string | null; typeChanged: boolean; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `taskId`      | `string` | Task identifier to promote        |

**Returns** — EngineResult with promotion details

**Example**

```typescript theme={null}
const result = await taskPromote('/project', 'T42');
```

## taskReopen(projectRoot, taskId, params)

Reopen a completed task (set status back to pending).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { status?: string; reason?: string; }) => Promise<EngineResult<{ task: string; reopened: boolean; previousStatus: string; newStatus: string; }>>
```

**Parameters**

| Name          | Type                                      | Description                       |
| ------------- | ----------------------------------------- | --------------------------------- |
| `projectRoot` | `string`                                  | Absolute path to the project root |
| `taskId`      | `string`                                  | Task identifier to reopen         |
| `params`      | `: { status?: string; reason?: string; }` | Optional target status and reason |

**Returns** — EngineResult with reopen details including previous and new status

**Example**

```typescript theme={null}
const result = await taskReopen('/project', 'T42', { reason: 'Tests regressed' });
```

## taskCancel(projectRoot, taskId, reason)

Cancel a task (soft terminal state -- reversible via restore).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, reason?: string) => Promise<EngineResult<{ task: string; cancelled: boolean; reason?: string; cancelledAt: string; }>>
```

**Parameters**

| Name          | Type       | Description                       |
| ------------- | ---------- | --------------------------------- |
| `projectRoot` | `string`   | Absolute path to the project root |
| `taskId`      | `string`   | Task identifier to cancel         |
| `reason`      | `: string` | Optional cancellation reason      |

**Returns** — EngineResult with cancellation details

**Example**

```typescript theme={null}
const result = await taskCancel('/project', 'T42', 'No longer needed');
```

## taskComplexityEstimate(projectRoot, params)

Deterministic complexity scoring from task metadata.

**Signature**

```typescript theme={null}
(projectRoot: string, params: { taskId: string; }) => Promise<EngineResult<{ size: "small" | "medium" | "large"; score: number; factors: ComplexityFactor[]; dependencyDepth: number; subtaskCount: number; fileCount: number; }>>
```

**Parameters**

| Name          | Type                  | Description                                  |
| ------------- | --------------------- | -------------------------------------------- |
| `projectRoot` | `string`              | Absolute path to the project root            |
| `params`      | `{ taskId: string; }` | Parameters including the task ID to estimate |

**Returns** — EngineResult with size, score, factors, and structural metrics

**Example**

```typescript theme={null}
const result = await taskComplexityEstimate('/project', { taskId: 'T42' });
```

## taskDepends()

List dependencies for a task in a given direction.  T4657  T4790  T4654

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, direction?: "upstream" | "downstream" | "both", tree?: boolean) => Promise<EngineResult>
```

## taskDepsOverview()

Overview of all dependencies across the project.  T5157

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ totalTasks: number; tasksWithDeps: number; blockedTasks: Array<{ id: string; title: string; status: string; unblockedBy: string[]; }>; readyTasks: Array<{ id: string; title: string; status: string; }>; validation: { valid: boolean; errorCount: number; warningCount: number; }; }>>
```

## taskDepsCycles()

Detect circular dependencies across the project.  T5157

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ hasCycles: boolean; cycles: Array<{ path: string[]; tasks: Array<{ id: string; title: string; }>; }>; }>>
```

## taskStats()

Compute task statistics, optionally scoped to an epic.  T4657  T4790  T4654

**Signature**

```typescript theme={null}
(projectRoot: string, epicId?: string) => Promise<EngineResult<{ total: number; pending: number; active: number; blocked: number; done: number; cancelled: number; byPriority: Record<string, number>; byType: Record<string, number>; }>>
```

## taskExport()

Export tasks as JSON or CSV.  T4657  T4790  T4654

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { format?: "json" | "csv"; status?: string; parent?: string; }) => Promise<EngineResult<unknown>>
```

## taskHistory()

Get task history from the log file.  T4657  T4790  T4654

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, limit?: number) => Promise<EngineResult<Array<Record<string, unknown>>>>
```

## taskLint()

Lint tasks for common issues.  T4657  T4790  T4654

**Signature**

```typescript theme={null}
(projectRoot: string, taskId?: string) => Promise<EngineResult<Array<{ taskId: string; severity: "error" | "warning"; rule: string; message: string; }>>>
```

## taskBatchValidate()

Validate multiple tasks at once.  T4657  T4790  T4654

**Signature**

```typescript theme={null}
(projectRoot: string, taskIds: string[], checkMode?: "full" | "quick") => Promise<EngineResult<{ results: Record<string, Array<{ severity: "error" | "warning"; rule: string; message: string; }>>; summary: { totalTasks: number; validTasks: number; invalidTasks: number; totalIssues: number; errors: number; warnings: number; }; }>>
```

## taskImport()

Import tasks from a JSON source string or export package.  T4790

**Signature**

```typescript theme={null}
(projectRoot: string, source: string, overwrite?: boolean) => Promise<EngineResult<{ imported: number; skipped: number; errors: string[]; remapTable?: Record<string, string>; }>>
```

## taskPlan()

Compute a ranked plan: in-progress epics, ready tasks, blockers, bugs.  T4815

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult>
```

## taskRelatesFind()

Find related tasks using semantic search or keyword matching.  T5672

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, params?: { mode?: "suggest" | "discover"; threshold?: number; }) => Promise<EngineResult<Record<string, unknown>>>
```

## taskLabelList()

List all labels used in tasks.  T5672

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ labels: unknown[]; count: number; }>>
```

## taskLabelShow()

Show tasks associated with a label.  T5672

**Signature**

```typescript theme={null}
(projectRoot: string, label: string) => Promise<EngineResult<Record<string, unknown>>>
```

## taskSyncReconcile()

Reconcile external tasks with CLEO as SSoT.

**Signature**

```typescript theme={null}
(projectRoot: string, params: { providerId: string; externalTasks: Array<import("@cleocode/contracts").ExternalTask>; dryRun?: boolean; conflictPolicy?: string; defaultPhase?: string; defaultLabels?: string[]; }) => Promise<EngineResult<import("@cleocode/contracts").ReconcileResult>>
```

## taskSyncLinks()

List external task links by provider or task ID.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { providerId?: string; taskId?: string; }) => Promise<EngineResult<{ links: import("@cleocode/contracts").ExternalTaskLink[]; count: number; }>>
```

## taskSyncLinksRemove()

Remove all external task links for a provider.

**Signature**

```typescript theme={null}
(projectRoot: string, providerId: string) => Promise<EngineResult<{ providerId: string; removed: number; }>>
```

## taskClaim()

Atomically claim a task for an agent.  Fails if the task is already claimed by a different agent. No-op if the task is already claimed by the same agent (idempotent).

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string, agentId: string) => Promise<EngineResult<{ taskId: string; agentId: string; }>>
```

## taskUnclaim()

Release an agent's claim on a task, setting assignee to null.  No-op if the task is not currently claimed.

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ taskId: string; }>>
```

## sessionStatus(projectRoot)

Get current session status.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ hasActiveSession: boolean; session?: Session | null; taskWork?: TaskWorkState | null; }>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |

**Returns** — EngineResult with active session flag, session record, and task work state

**Example**

```typescript theme={null}
const result = await sessionStatus('/project');
if (result.success && result.data.hasActiveSession) {
  console.log(result.data.session?.id);
}
```

## sessionList(projectRoot, params)

List sessions with budget enforcement.  When a limit is applied (explicit or default), the response includes `_meta.truncated` and `_meta.total` so agents know the result set was capped.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { active?: boolean; status?: string; limit?: number; offset?: number; }) => Promise<EngineResult<{ sessions: Session[]; total: number; filtered: number; _meta: { truncated: boolean; total: number; }; }>>
```

**Parameters**

| Name          | Type                                                                        | Description                               |
| ------------- | --------------------------------------------------------------------------- | ----------------------------------------- |
| `projectRoot` | `string`                                                                    | Absolute path to the project root         |
| `params`      | `: { active?: boolean; status?: string; limit?: number; offset?: number; }` | Optional filter and pagination parameters |

**Returns** — EngineResult with sessions array, total, filtered count, and truncation metadata

**Example**

```typescript theme={null}
const result = await sessionList('/project', { active: true, limit: 5 });
```

## sessionFind(projectRoot, params)

Lightweight session discovery -- returns minimal session records.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: FindSessionsParams) => Promise<EngineResult<MinimalSessionRecord[]>>
```

**Parameters**

| Name          | Type                   | Description                       |
| ------------- | ---------------------- | --------------------------------- |
| `projectRoot` | `string`               | Absolute path to the project root |
| `params`      | `: FindSessionsParams` | Optional search parameters        |

**Returns** — EngineResult with array of minimal session records

**Example**

```typescript theme={null}
const result = await sessionFind('/project', { status: 'active' });
```

## sessionShow(projectRoot, sessionId)

Show a specific session by ID.

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<EngineResult<Session>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |
| `sessionId`   | `string` | Session identifier to look up     |

**Returns** — EngineResult with the full Session record

**Example**

```typescript theme={null}
const result = await sessionShow('/project', 'ses_20260401_abc123');
```

## taskCurrentGet()

Get current task being worked on. Delegates to core/task-work/currentTask.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ currentTask: string | null; currentPhase: string | null; }>>
```

## taskStart()

Start working on a specific task. Delegates to core/task-work/startTask.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, taskId: string) => Promise<EngineResult<{ taskId: string; previousTask: string | null; }>>
```

## taskStop()

Stop working on the current task. Delegates to core/task-work/stopTask.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ cleared: boolean; previousTask: string | null; }>>
```

## taskWorkHistory()

Get task work history from session notes.  T5323

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ history: TaskWorkHistoryEntry[]; count: number; }>>
```

## sessionStart()

Start a new session. Note: This function has engine-specific logic for task file focus management and session store updates, so it remains in the engine layer.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, params: { scope: string; name?: string; autoStart?: boolean; startTask?: string; grade?: boolean; }) => Promise<EngineResult<Session>>
```

## sessionEnd()

End the current session. Note: This function has engine-specific logic for task file focus management and session store management, so it remains in the engine layer.  T4782  T140  T134 - Summarization wiring

**Signature**

```typescript theme={null}
(projectRoot: string, notes?: string, params?: { sessionSummary?: import("@cleocode/contracts").SessionSummaryInput; }) => Promise<EngineResult<{ sessionId: string; ended: boolean; memoryPrompt?: string; }>>
```

## sessionResume()

Resume an ended or suspended session. Note: This function has engine-specific logic for task file focus sync, so it remains in the engine layer.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<EngineResult<Session>>
```

## sessionGc()

Garbage collect old sessions.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, maxAgeDays?: number) => Promise<EngineResult<{ orphaned: string[]; removed: string[]; }>>
```

## sessionSuspend()

Suspend an active session.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string, reason?: string) => Promise<EngineResult<Session>>
```

## sessionHistory()

List session history with focus changes and completed tasks.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { sessionId?: string; limit?: number; }) => Promise<EngineResult<{ sessions: Array<{ id: string; name?: string; status: string; startedAt: string; endedAt?: string | null; tasksCompleted: number; focusChanges: number; focusHistory: Array<{ taskId: string; timestamp: string; }>; }>; }>>
```

## sessionCleanup()

Remove orphaned sessions and clean up stale data.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ removed: string[]; autoEnded: string[]; cleaned: boolean; }>>
```

## sessionRecordDecision()

Record a decision to the audit trail.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, params: { sessionId: string; taskId: string; decision: string; rationale: string; alternatives?: string[]; }) => Promise<EngineResult<DecisionRecord>>
```

## sessionDecisionLog()

Read the decision log, optionally filtered by sessionId and/or taskId.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { sessionId?: string; taskId?: string; }) => Promise<EngineResult<DecisionRecord[]>>
```

## sessionContextDrift()

Compute context drift score for the current session.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { sessionId?: string; }) => Promise<EngineResult<{ score: number; factors: string[]; completedInScope: number; totalInScope: number; outOfScope: number; }>>
```

## sessionRecordAssumption()

Record an assumption made during a session.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, params: { sessionId?: string; taskId?: string; assumption: string; confidence: "high" | "medium" | "low"; }) => Promise<EngineResult<{ id: string; sessionId: string; taskId: string | null; assumption: string; confidence: string; timestamp: string; }>>
```

## sessionStats()

Compute session statistics, optionally for a specific session.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId?: string) => Promise<EngineResult<{ totalSessions: number; activeSessions: number; suspendedSessions: number; endedSessions: number; archivedSessions: number; totalTasksCompleted: number; totalFocusChanges: number; averageResumeCount: number; session?: { id: string; status: string; tasksCompleted: number; focusChanges: number; resumeCount: number; durationMinutes: number; }; }>>
```

## sessionSwitch()

Switch to a different session.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<EngineResult<Session>>
```

## sessionArchive()

Archive old/ended sessions.  T4782

**Signature**

```typescript theme={null}
(projectRoot: string, olderThan?: string) => Promise<EngineResult<{ archived: string[]; count: number; }>>
```

## sessionHandoff()

Get handoff data for the most recent ended session.  T4915, T5123

**Signature**

```typescript theme={null}
(projectRoot: string, scope?: { type: string; epicId?: string; }) => Promise<EngineResult<{ sessionId: string; handoff: HandoffData; } | null>>
```

## sessionComputeHandoff()

Compute and persist handoff data for a session.  T4915

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string, options?: { note?: string; nextAction?: string; }) => Promise<EngineResult<HandoffData>>
```

## sessionBriefing()

Compute session briefing - composite view for session start. Aggregates data from handoff, current focus, next tasks, bugs, blockers, and epics.  T4916

**Signature**

```typescript theme={null}
(projectRoot: string, options?: { maxNextTasks?: number; maxBugs?: number; maxBlocked?: number; maxEpics?: number; scope?: string; }) => Promise<EngineResult<SessionBriefing>>
```

## sessionComputeDebrief()

Compute and persist rich debrief data for a session. Persists as both handoffJson (backward compat) and debriefJson (rich data).  T4959

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string, options?: { note?: string; nextAction?: string; }) => Promise<EngineResult<DebriefData>>
```

## sessionDebriefShow()

Read a session's debrief data. Falls back to handoff data if no debrief is available.  T4959

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<EngineResult<DebriefData | { handoff: unknown; fallback: true; } | null>>
```

## sessionChainShow()

Show the session chain for a given session. Returns ordered list of sessions linked via previousSessionId/nextSessionId.  T4959

**Signature**

```typescript theme={null}
(projectRoot: string, sessionId: string) => Promise<EngineResult<Array<{ id: string; status: string; startedAt: string; endedAt: string | null; agentIdentifier: string | null; position: number; }>>>
```

## sessionContextInject()

Inject context protocol content.  T5673

**Signature**

```typescript theme={null}
(protocolType: string, params?: { taskId?: string; variant?: string; }, projectRoot?: string) => EngineResult<ContextInjectionData>
```

## listRcsdEpics()

List all epic IDs that have RCASD pipeline data.

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<string[]>
```

## lifecycleStatus()

lifecycle.check / lifecycle.status - Get lifecycle status for epic.  T4785

**Signature**

```typescript theme={null}
(epicId: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleHistory()

lifecycle.history - Stage transition history.  T4785

**Signature**

```typescript theme={null}
(taskId: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleGates()

lifecycle.gates - Get all gate statuses for an epic.  T4785

**Signature**

```typescript theme={null}
(taskId: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecyclePrerequisites()

lifecycle.prerequisites - Get required prior stages for a target stage.  T4785

**Signature**

```typescript theme={null}
(targetStage: string, _projectRoot?: string) => Promise<EngineResult>
```

## lifecycleCheck()

lifecycle.check - Check if a stage's prerequisites are met.  T4785

**Signature**

```typescript theme={null}
(epicId: string, targetStage: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleProgress()

lifecycle.progress / lifecycle.record - Record stage completion.  T4785

**Signature**

```typescript theme={null}
(taskId: string, stage: string, status: string, notes?: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleSkip()

lifecycle.skip - Skip a stage with reason.  T4785

**Signature**

```typescript theme={null}
(taskId: string, stage: string, reason: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleReset()

lifecycle.reset - Reset a stage (emergency).  T4785

**Signature**

```typescript theme={null}
(taskId: string, stage: string, reason: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleGatePass()

lifecycle.gate.pass - Mark gate as passed.  T4785

**Signature**

```typescript theme={null}
(taskId: string, gateName: string, agent?: string, notes?: string, projectRoot?: string) => Promise<EngineResult>
```

## lifecycleGateFail()

lifecycle.gate.fail - Mark gate as failed.  T4785

**Signature**

```typescript theme={null}
(taskId: string, gateName: string, reason?: string, projectRoot?: string) => Promise<EngineResult>
```

## createGatewayMeta(gateway, domain, operation, startTime)

Create a fully typed GatewayMeta for domain responses.

**Signature**

```typescript theme={null}
(gateway: string, domain: string, operation: string, startTime: number) => GatewayMetaRecord
```

**Parameters**

| Name        | Type     | Description                                   |
| ----------- | -------- | --------------------------------------------- |
| `gateway`   | `string` | Gateway name (e.g., 'query', 'mutate')        |
| `domain`    | `string` | Domain name (e.g., 'tasks', 'session')        |
| `operation` | `string` | Operation name (e.g., 'show', 'list')         |
| `startTime` | `number` | Timestamp from Date.now() at start of request |

**Returns** — GatewayMeta with all LAFS and CLEO-specific fields   T4700  T4663

## enforceBudget(response, budget)

Apply budget enforcement to a dispatch response envelope.  Converts the DomainResponse into an LAFSEnvelope shape for budget checking, then applies truncation if the response exceeds the budget.

**Signature**

```typescript theme={null}
(response: Record<string, unknown>, budget?: number) => { response: Record<string, unknown>; enforcement: BudgetEnforcementResult; }
```

**Parameters**

| Name       | Type            | Description                                          |
| ---------- | --------------- | ---------------------------------------------------- |
| `response` | `Record<string` | The domain response object                           |
| `budget`   | `: number`      | Maximum allowed tokens (defaults to DEFAULT\_BUDGET) |

**Returns** — The response, potentially truncated, with budget metadata   T4701  T4663

## isWithinBudget()

Quick check whether a response exceeds a token budget without modifying it.   T4701  T4663

**Signature**

```typescript theme={null}
(response: Record<string, unknown>, budget?: number) => boolean
```

## ShimCommand

Minimal Commander-compatible Command class. Captures command definitions for later translation into citty commands.

**Signature**

```typescript theme={null}
typeof ShimCommand
```

**Methods**

### command()

Register a subcommand. Returns the new subcommand for chaining.

```typescript theme={null}
(nameAndArgs: string, opts?: { isDefault?: boolean; }) => ShimCommand
```

### description()

Set description (chaining).

```typescript theme={null}
{ (desc: string): this; (): string; }
```

### description()

Get description (Commander compat).

```typescript theme={null}
{ (desc: string): this; (): string; }
```

### description()

```typescript theme={null}
{ (desc: string): this; (): string; }
```

### alias()

```typescript theme={null}
(name: string) => this
```

### option()

```typescript theme={null}
(flags: string, description: string, parseOrDefault?: unknown, defaultVal?: unknown) => this
```

### requiredOption()

```typescript theme={null}
(flags: string, description: string) => this
```

### argument()

Add a positional argument after command creation. Commander compat: .argument('\[name]', 'description')

```typescript theme={null}
(spec: string, _description?: string) => this
```

### action()

```typescript theme={null}
(fn: (...args: any[]) => Promise<void> | void) => this
```

### allowUnknownOption()

No-op for Commander compatibility. citty handles unknown options gracefully.

```typescript theme={null}
(_allow?: boolean) => this
```

### allowExcessArguments()

No-op for Commander compatibility.

```typescript theme={null}
(_allow?: boolean) => this
```

### name()

Get the command name. Commander compat method.

```typescript theme={null}
() => string
```

### optsWithGlobals()

Return parsed global flags from process.argv. Commander compat: returns parent + own options merged.

```typescript theme={null}
() => Record<string, unknown>
```

### opts()

Return parsed options. For shim purposes, same as optsWithGlobals().

```typescript theme={null}
() => Record<string, unknown>
```

## setFieldContext()

Set the field extraction context for this CLI invocation. Called once from the preAction hook in src/cli/index.ts.

**Signature**

```typescript theme={null}
(ctx: FieldExtractionResolution) => void
```

## getFieldContext()

Get the current field extraction context.

**Signature**

```typescript theme={null}
() => FieldExtractionResolution
```

## resolveFieldContext()

Parse global field options from Commander.js parsed opts and resolve via the canonical LAFS SDK resolver (conflict detection, type narrowing).

**Signature**

```typescript theme={null}
(opts: Record<string, unknown>) => FieldExtractionResolution
```

## setFormatContext()

Set the resolved format for this CLI invocation. Called once from the preAction hook in src/cli/index.ts.

**Signature**

```typescript theme={null}
(resolution: FlagResolution) => void
```

## getFormatContext()

Get the current resolved format.

**Signature**

```typescript theme={null}
() => FlagResolution
```

## isJsonFormat()

Check if output should be JSON format.

**Signature**

```typescript theme={null}
() => boolean
```

## isHumanFormat()

Check if output should be human-readable format.

**Signature**

```typescript theme={null}
() => boolean
```

## isQuiet()

Check if quiet mode is enabled (suppress non-essential output).

**Signature**

```typescript theme={null}
() => boolean
```

## resolveFormat(opts, defaults)

Resolve output format from Commander.js option values.  Reads --json, --human, and --quiet flags and delegates to the canonical LAFS resolveOutputFormat(). Project/user defaults can be passed via the optional `defaults` parameter.

**Signature**

```typescript theme={null}
(opts: Record<string, unknown>, defaults?: { projectDefault?: "json" | "human"; userDefault?: "json" | "human"; }) => FlagResolution
```

**Parameters**

| Name       | Type                                                                         | Description                        |
| ---------- | ---------------------------------------------------------------------------- | ---------------------------------- |
| `opts`     | `Record<string`                                                              | Commander.js parsed options object |
| `defaults` | `: { projectDefault?: "json" \| "human"; userDefault?: "json" \| "human"; }` | Optional project/user defaults     |

**Returns** — Resolved format with source provenance   T4703  T4663

## validateLafsShape(envelope)

Validate a LAFS envelope shape and report violations.  Full envelopes are delegated to `@cleocode/lafs.validateEnvelope()` (which uses the canonical schema via lafs-napi/AJV). Minimal envelopes are checked against the lightweight invariants in this module.

**Signature**

```typescript theme={null}
(envelope: unknown) => LafsShapeViolation
```

**Parameters**

| Name       | Type      | Description                                          |
| ---------- | --------- | ---------------------------------------------------- |
| `envelope` | `unknown` | The candidate envelope (serialized string or object) |

**Returns** — A `LafsShapeViolation` report. `.reasons.length === 0` when valid.

## assertLafsShape(envelope)

Assert that a LAFS envelope conforms to the shape contract, throwing an error with a LAFS-shaped diagnostic if it does not.  Used by the renderer middleware to fail LOUDLY when CLEO itself emits a malformed envelope — this is a developer bug, not an operator issue.

**Signature**

```typescript theme={null}
(envelope: unknown) => void
```

**Parameters**

| Name       | Type      | Description            |
| ---------- | --------- | ---------------------- |
| `envelope` | `unknown` | The candidate envelope |

**Throws**

* `LafsViolationError` if the envelope fails any shape invariant

## LafsViolationError

Error thrown by `assertLafsShape` when an envelope fails validation.  Carries the full `LafsShapeViolation` report so diagnostic tooling can report which specific invariants were violated.

**Signature**

```typescript theme={null}
typeof LafsViolationError
```

## emitLafsViolation()

Emit a LAFS-shaped error envelope describing a validation failure and set `process.exitCode` to `ExitCode.LAFS_VIOLATION`.  Called by the renderer middleware as a recovery path when a previously- emitted envelope turns out to be malformed.

**Signature**

```typescript theme={null}
(err: LafsViolationError) => void
```

## normalizeForHuman()

Normalize data shape for human renderers.  Each command expects data with specific named keys (e.g., `data.task` for 'show', `data.tasks` for 'list'). This function detects and corrects flat/array data from the engine layer.

**Signature**

```typescript theme={null}
(command: string, data: Record<string, unknown>) => Record<string, unknown>
```

## statusSymbol()

Map task status to a display symbol. Falls back to '?' for unknown values.

**Signature**

```typescript theme={null}
(status: string) => string
```

## statusColor()

Map task status to a color escape.

**Signature**

```typescript theme={null}
(status: string) => string
```

## prioritySymbol()

Map task priority to a display symbol.

**Signature**

```typescript theme={null}
(priority: string) => string
```

## priorityColor()

Map task priority to a color escape.

**Signature**

```typescript theme={null}
(priority: string) => string
```

## hRule()

Create a horizontal rule with box-drawing characters.

**Signature**

```typescript theme={null}
(width?: number) => string
```

## shortDate()

Format a date string as YYYY-MM-DD.

**Signature**

```typescript theme={null}
(isoDate: string | null | undefined) => string
```

## renderDoctor()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderStats()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderNext()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderBlockers()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderTree()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderStart()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderStop()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderCurrent()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderSession()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderVersion()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderPlan()

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderGeneric()

Generic human renderer for commands that don't have a specific renderer. Renders data as indented key-value pairs.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderShow()

Render a single task in a box format (mirrors bash display\_text).

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderList()

Render a list of tasks (mirrors bash list.sh text output).

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderFind()

Render search results.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderAdd()

Render add result.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderUpdate()

Render update result.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderComplete()

Render complete result.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderDelete()

Render delete result.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderArchive()

Render archive result.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## renderRestore()

Render restore result.

**Signature**

```typescript theme={null}
(data: Record<string, unknown>, quiet: boolean) => string
```

## cliOutput()

Output data to stdout in the resolved format (JSON or human-readable).  Replaces `console.log(formatSuccess(data))` in all V2 commands. When format is 'human', normalizes the data shape then dispatches to the appropriate renderer. When format is 'json', delegates to existing formatSuccess().   T4665  T4666  T4813

**Signature**

```typescript theme={null}
(data: unknown, opts: CliOutputOptions) => void
```

## cliError()

Output an error in the resolved format. For JSON: delegates to formatError (already handled in command catch blocks). For human: prints a plain error message to stderr.   T4666  T4813

**Signature**

```typescript theme={null}
(message: string, code?: number | string, _details?: CliErrorDetails) => void
```

## createDispatchMeta(gateway, domain, operation, startTime, source, requestId, sessionId)

Create metadata for a dispatch response.

**Signature**

```typescript theme={null}
(gateway: string, domain: string, operation: string, startTime: number, source?: Source, requestId?: string, sessionId?: string | null) => DispatchResponse["_meta"]
```

**Parameters**

| Name        | Type               | Description                                   |
| ----------- | ------------------ | --------------------------------------------- |
| `gateway`   | `string`           | Gateway name (e.g., 'query', 'mutate')        |
| `domain`    | `string`           | Domain name (e.g., 'tasks', 'session')        |
| `operation` | `string`           | Operation name (e.g., 'show', 'list')         |
| `startTime` | `number`           | Timestamp from Date.now() at start of request |
| `source`    | `: Source`         | Where the request originated                  |
| `requestId` | `: string`         | Optional pre-generated request ID             |
| `sessionId` | `: string \| null` | Optional session ID to include in metadata    |

**Returns** — Metadata conforming to DispatchResponse\['\_meta']   T4772  T4959

## compose(middlewares)

Composes an array of Middleware functions into a single Middleware function. Execution flows through the array from first to last, and returns bubble back up from last to first.

**Signature**

```typescript theme={null}
(middlewares: Middleware[]) => Middleware
```

**Parameters**

| Name          | Type           | Description                            |
| ------------- | -------------- | -------------------------------------- |
| `middlewares` | `Middleware[]` | Array of middleware functions to chain |

**Returns** — A single composed Middleware function

**Example**

```typescript theme={null}
import { compose } from './pipeline.js';

const pipeline = compose([sanitizer, rateLimiter, protocolEnforcement]);
const response = await pipeline(request, handler);
```

## deriveGatewayMatrix()

Derive a gateway operation matrix from the registry.  Returns `Record<string, string[]>` containing: - All canonical domains with their operations  This is the SINGLE derivation point — gateways use this instead of maintaining independent operation lists.

**Signature**

```typescript theme={null}
(gateway: Gateway) => Record<string, string[]>
```

## getGatewayDomains()

Get all accepted domain names for a gateway (canonical only).

**Signature**

```typescript theme={null}
(gateway: Gateway) => string[]
```

## resolve()

Resolves a domain + operation to its registered definition.

**Signature**

```typescript theme={null}
(gateway: Gateway, domain: string, operation: string) => Resolution | undefined
```

## validateRequiredParams()

Validates that all required parameters are present in the request. Returns an array of missing parameter keys.

**Signature**

```typescript theme={null}
(def: OperationDef, params?: Record<string, unknown>) => string[]
```

## getByDomain()

Get all operations for a specific canonical domain.

**Signature**

```typescript theme={null}
(domain: CanonicalDomain) => OperationDef[]
```

## getByGateway()

Get all operations for a specific gateway.

**Signature**

```typescript theme={null}
(gateway: Gateway) => OperationDef[]
```

## getByTier()

Get all operations available at or below a specific tier.

**Signature**

```typescript theme={null}
(tier: Tier) => OperationDef[]
```

## getActiveDomains()

Get a list of canonical domains that actually have operations registered.

**Signature**

```typescript theme={null}
() => CanonicalDomain[]
```

## getCounts()

Returns summary counts of operations for module validation.

**Signature**

```typescript theme={null}
() => { query: number; mutate: number; total: number; }
```

## Dispatcher

**Signature**

```typescript theme={null}
typeof Dispatcher
```

**Methods**

### dispatch()

```typescript theme={null}
(request: DispatchRequest) => Promise<DispatchResponse>
```

## mapCodebase(projectRoot, options)

Analyze a codebase and return structured mapping. When storeToBrain is true, findings are persisted to brain.db.

**Signature**

```typescript theme={null}
(projectRoot: string, options?: { focus?: string; storeToBrain?: boolean; }) => Promise<EngineResult>
```

**Parameters**

| Name          | Type                                            | Description                       |
| ------------- | ----------------------------------------------- | --------------------------------- |
| `projectRoot` | `string`                                        | Absolute path to the project root |
| `options`     | `: { focus?: string; storeToBrain?: boolean; }` | Optional analysis options         |

**Returns** — EngineResult containing the structured codebase map

**Example**

```typescript theme={null}
const result = await mapCodebase('/path/to/project', { focus: 'architecture' });
```

## configGet()

Get config value by key (dot-notation supported)

**Signature**

```typescript theme={null}
(projectRoot: string, key?: string) => Promise<EngineResult<unknown>>
```

## configSet()

Set a config value by key (dot-notation supported)

**Signature**

```typescript theme={null}
(projectRoot: string, key: string, value: unknown) => Promise<EngineResult<{ key: string; value: unknown; }>>
```

## configSetPreset()

Apply a strictness preset to the project config.  T067

**Signature**

```typescript theme={null}
(projectRoot: string, preset: string) => Promise<EngineResult<unknown>>
```

## configListPresets()

List all available strictness presets.  T067

**Signature**

```typescript theme={null}
() => EngineResult<unknown>
```

## queryHookProviders(event)

Query providers that support a specific hook event  Returns detailed provider information including which hooks each provider supports, enabling intelligent routing and filtering of hook handlers.

**Signature**

```typescript theme={null}
(event: HookEvent) => Promise<EngineResult<{ event: HookEvent; providers: ProviderHookInfo[]; }>>
```

**Parameters**

| Name    | Type        | Description                           |
| ------- | ----------- | ------------------------------------- |
| `event` | `HookEvent` | The hook event to query providers for |

**Returns** — Engine result with provider hook capability data

## queryCommonHooks(providerIds)

Get hook events common to specified providers  Analyzes which hook events are supported by all providers in the given list, useful for determining the intersection of hook capabilities.

**Signature**

```typescript theme={null}
(providerIds?: string[]) => Promise<EngineResult<{ providerIds?: string[]; commonEvents: ProviderHookEvent[]; }>>
```

**Parameters**

| Name          | Type         | Description                                                            |
| ------------- | ------------ | ---------------------------------------------------------------------- |
| `providerIds` | `: string[]` | Optional array of provider IDs to analyze (uses all active if omitted) |

**Returns** — Engine result with common hook events

## systemHooksMatrix(params)

Build a cross-provider hook support matrix using CAAMP APIs.  Calls `buildHookMatrix()` to assemble the two-dimensional grid, then augments each provider row with `getProviderSummary()` coverage stats. Optionally runs `detectAllProviders()` to surface the active runtime.

**Signature**

```typescript theme={null}
(params?: { providerIds?: string[]; detectProvider?: boolean; }) => Promise<EngineResult<HookMatrixResult>>
```

**Parameters**

| Name     | Type                                                      | Description                       |
| -------- | --------------------------------------------------------- | --------------------------------- |
| `params` | `: { providerIds?: string[]; detectProvider?: boolean; }` | Optional filter/detection options |

**Returns** — Engine result with the full hook matrix  T167

## initProject()

Initialize a CLEO project directory.  Creates the .cleo/ directory structure with empty data files. Returns error if already initialized (unless force=true).

**Signature**

```typescript theme={null}
(projectRoot: string, options?: { projectName?: string; force?: boolean; mapCodebase?: boolean; }) => Promise<EngineResult<{ initialized: boolean; projectRoot: string; filesCreated: string[]; skipped: string[]; warnings: string[]; classification?: { kind: "greenfield" | "brownfield"; signalCount: number; topLevelFileCount: number; hasGit: boolean; }; nextSteps?: Array<{ action: string; command: string; }>; }>>
```

## isAutoInitEnabled()

Check if auto-init is enabled via environment variable

**Signature**

```typescript theme={null}
() => boolean
```

## ensureInitialized()

Check initialization status and auto-init if configured

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ initialized: boolean; }>>
```

## getVersion()

Get current version (native implementation)

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ version: string; }>>
```

## orchestrateStatus()

orchestrate.status - Get orchestrator status  T4478

**Signature**

```typescript theme={null}
(epicId?: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateAnalyze()

orchestrate.analyze - Dependency analysis  T4478

**Signature**

```typescript theme={null}
(epicId?: string, projectRoot?: string, mode?: string) => Promise<EngineResult>
```

## orchestrateReady()

orchestrate.ready - Get parallel-safe tasks (ready to execute)  T4478

**Signature**

```typescript theme={null}
(epicId: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateNext()

orchestrate.next - Next task to spawn  T4478

**Signature**

```typescript theme={null}
(epicId: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateWaves()

orchestrate.waves - Compute dependency waves  T4478

**Signature**

```typescript theme={null}
(epicId: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateContext()

orchestrate.context - Context usage check  T4478

**Signature**

```typescript theme={null}
(epicId?: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateValidate()

orchestrate.validate - Validate spawn readiness for a task  T4478

**Signature**

```typescript theme={null}
(taskId: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateSpawnSelectProvider()

orchestrate.spawn.select - Select best provider for spawn based on required capabilities  T5236

**Signature**

```typescript theme={null}
(capabilities: Array<"supportsSubagents" | "supportsProgrammaticSpawn" | "supportsInterAgentComms" | "supportsParallelSpawn">, _projectRoot?: string) => Promise<EngineResult>
```

## orchestrateSpawnExecute()

orchestrate.spawn.execute - Execute spawn for a task using adapter registry  T5236

**Signature**

```typescript theme={null}
(taskId: string, adapterId?: string, protocolType?: string, projectRoot?: string, tier?: 0 | 1 | 2) => Promise<EngineResult>
```

## orchestrateSpawn()

orchestrate.spawn - Generate spawn prompt for a task  T4478

**Signature**

```typescript theme={null}
(taskId: string, protocolType?: string, projectRoot?: string, tier?: 0 | 1 | 2) => Promise<EngineResult>
```

## orchestrateStartup()

orchestrate.startup - Initialize orchestration for an epic  T4478

**Signature**

```typescript theme={null}
(epicId: string, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateBootstrap()

orchestrate.bootstrap - Load brain state for agent bootstrapping  T4478  T4657

**Signature**

```typescript theme={null}
(projectRoot?: string, params?: { speed?: "fast" | "full" | "complete"; }) => Promise<EngineResult<BrainState>>
```

## orchestrateCriticalPath()

orchestrate.critical-path - Find the longest dependency chain  T4478

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult>
```

## orchestrateUnblockOpportunities()

orchestrate.unblock-opportunities - Analyze dependency graph for unblocking opportunities  T4478

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult>
```

## orchestrateParallel()

orchestrate.parallel - Manage parallel execution (start/end)  T4632

**Signature**

```typescript theme={null}
(action: "start" | "end", epicId: string, wave?: number, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateParallelStart()

orchestrate.parallel.start - Start parallel execution for a wave  T4632

**Signature**

```typescript theme={null}
(epicId: string, wave: number, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateParallelEnd()

orchestrate.parallel.end - End parallel execution for a wave  T4632

**Signature**

```typescript theme={null}
(epicId: string, wave: number, projectRoot?: string) => Promise<EngineResult>
```

## orchestrateCheck()

orchestrate.check - Check current orchestration state  T4632

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult>
```

## orchestrateSkillInject()

orchestrate.skill.inject - Read skill content for injection into agent context  T4632

**Signature**

```typescript theme={null}
(skillName: string, projectRoot?: string) => EngineResult
```

## orchestrateHandoff()

orchestrate.handoff - Composite session handoff + successor spawn  Step order is explicit and fixed: 1) session.context.inject 2) session.end 3) orchestrate.spawn  Idempotency policy: - Non-idempotent overall. A retry after step 2 can duplicate spawn output. - Failures include exact step state and a safe retry entry point.

**Signature**

```typescript theme={null}
(params: OrchestrateHandoffParams, projectRoot?: string) => Promise<EngineResult>
```

## phaseList()

phase.list - List all project phases

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult>
```

## phaseShow()

phase.show - Show details of a specific phase

**Signature**

```typescript theme={null}
(phaseId?: string, projectRoot?: string) => Promise<EngineResult>
```

## phaseSet()

phase.set - Set the current phase

**Signature**

```typescript theme={null}
(params: { phaseId: string; rollback?: boolean; force?: boolean; dryRun?: boolean; }, projectRoot?: string) => Promise<EngineResult>
```

## phaseStart()

phase.start - Start a pending phase

**Signature**

```typescript theme={null}
(phaseId: string, projectRoot?: string) => Promise<EngineResult>
```

## phaseComplete()

phase.complete - Complete an active phase

**Signature**

```typescript theme={null}
(phaseId: string, projectRoot?: string) => Promise<EngineResult>
```

## phaseAdvance()

phase.advance - Advance to the next phase

**Signature**

```typescript theme={null}
(force?: boolean, projectRoot?: string) => Promise<EngineResult>
```

## phaseRename()

phase.rename - Rename a phase

**Signature**

```typescript theme={null}
(oldName: string, newName: string, projectRoot?: string) => Promise<EngineResult>
```

## phaseDelete()

phase.delete - Delete a phase

**Signature**

```typescript theme={null}
(phaseId: string, params?: { reassignTo?: string; force?: boolean; }, projectRoot?: string) => Promise<EngineResult>
```

## releasePrepare()

release.prepare - Prepare a release  T4788

**Signature**

```typescript theme={null}
(version: string, tasks?: string[], notes?: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseChangelog()

release.changelog - Generate changelog  T4788

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseList()

release.list - List all releases (query operation via data read)  T4788

**Signature**

```typescript theme={null}
(optionsOrProjectRoot?: ReleaseListOptions | string, projectRoot?: string) => Promise<EngineResult>
```

## releaseShow()

release.show - Show release details (query operation via data read)  T4788

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseCommit()

release.commit - Mark release as committed (metadata only)  T4788

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseTag()

release.tag - Mark release as tagged (metadata only)  T4788

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseGatesRun()

release.gates.run - Run release gates (validation checks)  T4788

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseRollback()

release.rollback - Rollback a release  T4788

**Signature**

```typescript theme={null}
(version: string, reason?: string, projectRoot?: string) => Promise<EngineResult>
```

## releaseCancel()

release.cancel - Cancel and remove a release in draft or prepared state  T5602

**Signature**

```typescript theme={null}
(version: string, projectRoot?: string) => Promise<EngineResult>
```

## releasePush()

release.push - Push release to remote via git Uses execFileSync (no shell) for safety. Respects config.release.push policy.  Agent protocol guard (T4279): When running in agent context (detected via CLEO\_SESSION\_ID or CLAUDE\_AGENT\_TYPE env vars), requires a release manifest entry for the version. This ensures agents go through the proper release.ship workflow rather than calling release.push directly, maintaining provenance tracking.   T4788  T4276  T4279

**Signature**

```typescript theme={null}
(version: string, remote?: string, projectRoot?: string, opts?: { explicitPush?: boolean; }) => Promise<EngineResult>
```

## releaseShip()

release.ship - Composite release operation  Sequence: validate gates → epic completeness → double-listing check → write CHANGELOG → git commit/tag/push (or PR) → record provenance   T5582  T5586  T5576

**Signature**

```typescript theme={null}
(params: { version: string; epicId: string; remote?: string; dryRun?: boolean; bump?: boolean; }, projectRoot?: string) => Promise<EngineResult>
```

## systemDash(projectRoot, params)

Project dashboard: task counts by status, active session info, current focus, recent completions.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { blockedTasksLimit?: number; }) => Promise<EngineResult<DashboardData>>
```

**Parameters**

| Name          | Type                                | Description                                                |
| ------------- | ----------------------------------- | ---------------------------------------------------------- |
| `projectRoot` | `string`                            | Absolute path to the project root                          |
| `params`      | `: { blockedTasksLimit?: number; }` | Optional parameters to control blocked tasks display limit |

**Returns** — EngineResult with comprehensive dashboard data

**Example**

```typescript theme={null}
const result = await systemDash('/project', { blockedTasksLimit: 5 });
```

## systemStats()

Detailed statistics: tasks by status/priority/type/phase, completion rate, average cycle time.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { period?: number; }) => Promise<EngineResult<StatsData>>
```

## systemLabels()

List all unique labels across tasks with counts and task IDs per label.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").LabelsResult>>
```

## systemArchiveStats()

Archive metrics: total archived, by reason, average cycle time, archive rate.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { period?: number; }) => Promise<EngineResult<import("@cleocode/core/internal").ArchiveStatsResult>>
```

## systemLog()

Query audit log with optional filters. Reads from SQLite audit\_log table.   T4837

**Signature**

```typescript theme={null}
(projectRoot: string, filters?: { operation?: string; taskId?: string; since?: string; until?: string; limit?: number; offset?: number; }) => Promise<EngineResult<LogQueryData>>
```

## systemContext()

Context window tracking: estimate token usage from current session/state.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { session?: string; }) => EngineResult<ContextData>
```

## systemSequence()

Read task ID sequence state from canonical SQLite metadata. Supports 'show' and 'check' actions.  T4815

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { action?: "show" | "check"; }) => Promise<EngineResult<SequenceData | Record<string, unknown>>>
```

## systemInjectGenerate()

Generate Minimum Viable Injection (MVI).

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult<import("@cleocode/core/internal").InjectGenerateResult>>
```

## systemMetrics()

System metrics: token usage, compliance summary, session counts.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { scope?: string; since?: string; }) => Promise<EngineResult<import("@cleocode/core/internal").SystemMetricsResult>>
```

## systemHealth()

System health check: verify core data files exist and are valid.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { detailed?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").HealthResult>>
```

## systemDiagnostics()

System diagnostics: extended health checks with fix suggestions.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { checks?: string[]; }) => Promise<EngineResult<import("@cleocode/core/internal").DiagnosticsResult>>
```

## systemHelp()

Return help text for the system.  T4631

**Signature**

```typescript theme={null}
(_projectRoot: string, params?: { topic?: string; }) => EngineResult<HelpData>
```

## systemRoadmap()

Generate roadmap from pending epics and optional CHANGELOG history.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { includeHistory?: boolean; upcomingOnly?: boolean; }) => Promise<EngineResult>
```

## systemCompliance()

System compliance report from COMPLIANCE.jsonl.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { subcommand?: string; days?: number; epic?: string; }) => EngineResult<ComplianceData>
```

## systemBackup()

Create a backup of CLEO data files.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { type?: string; note?: string; }) => EngineResult<import("@cleocode/core/internal").BackupResult>
```

## systemListBackups()

List available system backups (read-only).  T4783

**Signature**

```typescript theme={null}
(projectRoot: string) => EngineResult<import("@cleocode/core/internal").BackupEntry[]>
```

## systemRestore()

Restore from a backup.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params: { backupId: string; force?: boolean; }) => EngineResult<import("@cleocode/core/internal").RestoreResult>
```

## backupRestore()

Restore an individual file from backup.  T5329

**Signature**

```typescript theme={null}
(projectRoot: string, fileName: string, options?: { dryRun?: boolean; }) => Promise<EngineResult<{ restored: boolean; file: string; from: string; targetPath: string; dryRun?: boolean; }>>
```

## systemMigrate()

Check/run schema migrations.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { target?: string; dryRun?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").MigrateResult>>
```

## systemCleanup()

Cleanup stale data (sessions, backups, logs).  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params: { target: string; olderThan?: string; dryRun?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").CleanupResult>>
```

## systemAudit()

Audit data integrity.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { scope?: string; fix?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").AuditResult>>
```

## systemSync()

Sync check (no external sync targets in native mode).  T4631

**Signature**

```typescript theme={null}
(_projectRoot: string, params?: { direction?: string; }) => EngineResult<SyncData>
```

## systemSafestop()

Safe stop: signal clean shutdown for agents.  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params?: { reason?: string; commit?: boolean; handoff?: string; noSessionEnd?: boolean; dryRun?: boolean; }) => EngineResult<import("@cleocode/core/internal").SafestopResult>
```

## systemUncancel()

Uncancel a cancelled task (restore to pending).  T4631

**Signature**

```typescript theme={null}
(projectRoot: string, params: { taskId: string; cascade?: boolean; notes?: string; dryRun?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").UncancelResult>>
```

## systemDoctor()

Run comprehensive doctor diagnostics.  T4795

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").DoctorReport>>
```

## systemFix()

Run auto-fix for failed doctor checks.  T4795

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").FixResult[]>>
```

## systemRuntime()

Runtime/channel diagnostics for CLI installation mode checks.  T4815

**Signature**

```typescript theme={null}
(_projectRoot: string, params?: { detailed?: boolean; }) => Promise<EngineResult<RuntimeData>>
```

## systemPaths()

Report all resolved CleoOS paths (project + global hub).  Backs the `cleo admin paths` CLI command. Read-only: reports current state without mutating the filesystem. Use `systemScaffoldHub()` to create missing hub directories and seed the starter justfile.   Phase 1 — XDG Foundation + Justfile Hub Skeleton

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<PathsData>>
```

## systemScaffoldHub()

Create the CleoOS Hub directories and seed the starter justfile if absent.  Idempotent: safe to call repeatedly. Never overwrites existing user-edited justfile or README content. Backs the `cleo admin scaffold-hub` CLI command and is invoked automatically by `cleo init` (Phase 5).   Phase 1 — XDG Foundation + Justfile Hub Skeleton

**Signature**

```typescript theme={null}
() => Promise<EngineResult<ScaffoldHubData>>
```

## systemSequenceRepair()

Repair task ID sequence using canonical core implementation.  T4815

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<Record<string, unknown>>>
```

## systemSmoke()

Run operational smoke tests across all domains.  Dispatches one read-only query per domain through the full CLI dispatch pipeline and reports pass/fail with timing. Catches crashes (TypeError, ReferenceError, etc.) not just structured error responses.   T130

**Signature**

```typescript theme={null}
() => Promise<EngineResult<SmokeResult>>
```

## parseIssueTemplates(projectRoot)

Parse all templates from the repo's .github/ISSUE\_TEMPLATE/ directory.

**Signature**

```typescript theme={null}
(projectRoot: string) => EngineResult<import("@cleocode/core/internal").TemplateConfig>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |

**Returns** — EngineResult containing the parsed template configuration

**Example**

```typescript theme={null}
const result = parseIssueTemplates('/path/to/project');
if (result.success) {
  console.log(result.data.templates);
}
```

## getTemplateForSubcommand(projectRoot, subcommand)

Get template config for a specific subcommand (bug/feature/help).

**Signature**

```typescript theme={null}
(projectRoot: string, subcommand: string) => EngineResult<import("@cleocode/core/internal").IssueTemplate>
```

**Parameters**

| Name          | Type     | Description                                            |
| ------------- | -------- | ------------------------------------------------------ |
| `projectRoot` | `string` | Absolute path to the project root                      |
| `subcommand`  | `string` | Template subcommand identifier (e.g. "bug", "feature") |

**Returns** — EngineResult containing the matched issue template

**Example**

```typescript theme={null}
const result = getTemplateForSubcommand('/path/to/project', 'bug');
```

## generateTemplateConfig(projectRoot)

Generate and cache the config as .cleo/issue-templates.json.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").TemplateConfig>>
```

**Parameters**

| Name          | Type     | Description                       |
| ------------- | -------- | --------------------------------- |
| `projectRoot` | `string` | Absolute path to the project root |

**Returns** — EngineResult containing the generated template configuration

**Example**

```typescript theme={null}
const result = await generateTemplateConfig('/path/to/project');
```

## validateLabels(labels, repoLabels)

Validate that labels exist on a GitHub repo.

**Signature**

```typescript theme={null}
(labels: string[], repoLabels: string[]) => EngineResult<{ existing: string[]; missing: string[]; }>
```

**Parameters**

| Name         | Type       | Description                          |
| ------------ | ---------- | ------------------------------------ |
| `labels`     | `string[]` | Labels required by the template      |
| `repoLabels` | `string[]` | Labels that exist on the GitHub repo |

**Returns** — EngineResult with existing and missing label lists

**Example**

```typescript theme={null}
const result = validateLabels(['bug', 'enhancement'], repoLabels);
```

## validateSchemaOp()

validate.schema - JSON Schema validation  T4477

**Signature**

```typescript theme={null}
(type: string, data?: unknown, projectRoot?: string) => EngineResult
```

## validateTask()

validate.task - Anti-hallucination task validation  T4477

**Signature**

```typescript theme={null}
(taskId: string, projectRoot?: string) => Promise<EngineResult>
```

## validateProtocol()

validate.protocol - Protocol compliance check  T4477

**Signature**

```typescript theme={null}
(taskId: string, protocolType?: string, projectRoot?: string) => Promise<EngineResult>
```

## validateManifest()

validate.manifest - Manifest entry validation  T4477

**Signature**

```typescript theme={null}
(projectRoot?: string) => EngineResult
```

## validateOutput()

validate.output - Output file validation  T4477

**Signature**

```typescript theme={null}
(filePath: string, taskId?: string, projectRoot?: string) => EngineResult
```

## validateComplianceSummary()

validate.compliance.summary - Aggregated compliance metrics  T4477

**Signature**

```typescript theme={null}
(projectRoot?: string) => EngineResult
```

## validateComplianceViolations()

validate.compliance.violations - List compliance violations  T4477

**Signature**

```typescript theme={null}
(limit?: number, projectRoot?: string) => EngineResult
```

## validateComplianceRecord()

validate.compliance.record - Record compliance check result  T4477

**Signature**

```typescript theme={null}
(taskId: string, result: string, protocol?: string, violations?: Array<{ code: string; message: string; severity: "warning" | "error"; }>, projectRoot?: string) => EngineResult
```

## validateTestStatus()

validate.test.status - Test suite status  T4477

**Signature**

```typescript theme={null}
(projectRoot?: string) => EngineResult
```

## validateCoherenceCheck()

validate.coherence-check - Cross-validate task graph for consistency  T4477

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult<{ coherent: boolean; issues: CoherenceIssue[]; }>>
```

## validateTestRun()

validate.test.run - Execute test suite via subprocess  T4632

**Signature**

```typescript theme={null}
(params?: { scope?: string; pattern?: string; parallel?: boolean; }, projectRoot?: string) => EngineResult
```

## validateBatchValidate()

validate.batch-validate - Batch validate all tasks against schema and rules  T4632

**Signature**

```typescript theme={null}
(projectRoot?: string) => Promise<EngineResult>
```

## validateTestCoverage()

validate.test.coverage - Coverage metrics  T4477

**Signature**

```typescript theme={null}
(projectRoot?: string) => EngineResult
```

## validateProtocolConsensus()

check.protocol.consensus - Validate consensus protocol compliance  T5327

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolContribution()

check.protocol.contribution - Validate contribution protocol compliance  T5327

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolDecomposition()

check.protocol.decomposition - Validate decomposition protocol compliance  T5327

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolImplementation()

check.protocol.implementation - Validate implementation protocol compliance  T5327

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolSpecification()

check.protocol.specification - Validate specification protocol compliance  T5327

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolResearch()

check.protocol.research - Validate research protocol compliance  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolArchitectureDecision()

check.protocol.architecture-decision - Validate ADR protocol compliance  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolValidation()

check.protocol.validation - Validate validation-stage protocol compliance  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolTesting()

check.protocol.testing - Validate testing-stage protocol compliance (IVT loop)  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolRelease()

check.protocol.release - Validate release protocol compliance  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolArtifactPublish()

check.protocol.artifact-publish - Validate artifact-publish protocol compliance  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateProtocolProvenance()

check.protocol.provenance - Validate provenance protocol compliance  T260

**Signature**

```typescript theme={null}
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>
```

## validateGateVerify()

check.gate.verify - View or modify verification gates for a task  T5327

**Signature**

```typescript theme={null}
(params: GateVerifyParams, projectRoot?: string) => Promise<EngineResult<GateVerifyResult>>
```

## dispatchMeta(gateway, domain, operation, startTime, source)

Build metadata for a dispatch domain response.

**Signature**

```typescript theme={null}
(gateway: string, domain: string, operation: string, startTime: number, source?: Source) => DispatchResponse["_meta"]
```

**Parameters**

| Name        | Type       | Description                                   |
| ----------- | ---------- | --------------------------------------------- |
| `gateway`   | `string`   | Gateway name (e.g., 'query', 'mutate')        |
| `domain`    | `string`   | Domain name (e.g., 'tasks', 'session')        |
| `operation` | `string`   | Operation name (e.g., 'show', 'list')         |
| `startTime` | `number`   | Timestamp from Date.now() at start of request |
| `source`    | `: Source` | Where the request originated                  |

**Returns** — Metadata conforming to DispatchResponse\['\_meta']   T4772

## wrapResult()

Wrap a native engine result into a DispatchResponse. Handles success data, page metadata, and structured errors.

**Signature**

```typescript theme={null}
(result: EngineResult, gateway: string, domain: string, operation: string, startTime: number) => DispatchResponse
```

## errorResult()

Return a standard error response.

**Signature**

```typescript theme={null}
(gateway: string, domain: string, operation: string, code: string, message: string, startTime: number) => DispatchResponse
```

## unsupportedOp()

Return a standard "unsupported operation" error response.

**Signature**

```typescript theme={null}
(gateway: string, domain: string, operation: string, startTime: number) => DispatchResponse
```

## getListParams()

Extract limit and offset pagination params from a params dict.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>) => { limit?: number; offset?: number; }
```

## handleErrorResult()

Handle a caught error: extract message and return an internal error response. Callers should log the error themselves (with their domain-specific logger) before or after calling this.

**Signature**

```typescript theme={null}
(gateway: string, domain: string, operation: string, error: unknown, startTime: number) => DispatchResponse
```

## routeByParam()

Shared parameter-based routing for merged operations. DRY utility -- all domain handlers use this instead of re-implementing action dispatch.   T5671

**Signature**

```typescript theme={null}
<T>(params: Record<string, unknown> | undefined, paramName: string, routes: Record<string, () => T>, defaultRoute?: string) => T
```

## BackgroundJobManager

Manages background jobs for long-running operations

**Signature**

```typescript theme={null}
typeof BackgroundJobManager
```

**Methods**

### startJob()

Start a new background job

```typescript theme={null}
(operation: string, executor: () => Promise<unknown>) => Promise<string>
```

### getJob()

Get a specific job by ID

```typescript theme={null}
(jobId: string) => BackgroundJob | undefined
```

### listJobs()

List all jobs, optionally filtered by status

```typescript theme={null}
(status?: string) => BackgroundJob[]
```

### cancelJob()

Cancel a running job

```typescript theme={null}
(jobId: string) => boolean
```

### updateProgress()

Update job progress (0-100)

```typescript theme={null}
(jobId: string, progress: number) => boolean
```

### cleanup()

Cleanup old completed/failed/cancelled jobs past retention period

```typescript theme={null}
() => number
```

### destroy()

Destroy the manager: cancel all running jobs and clear state

```typescript theme={null}
() => void
```

### executeJob()

Execute a job's executor function and update status on completion/failure

```typescript theme={null}
(jobId: string, executor: () => Promise<unknown>, signal: AbortSignal) => Promise<void>
```

## setJobManager()

**Signature**

```typescript theme={null}
(manager: BackgroundJobManager) => void
```

## getJobManager()

**Signature**

```typescript theme={null}
() => BackgroundJobManager | null
```

## AdminHandler

**Signature**

```typescript theme={null}
typeof AdminHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## CheckHandler

**Signature**

```typescript theme={null}
typeof CheckHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## ConduitHandler

Conduit dispatch handler for agent messaging operations.

**Signature**

```typescript theme={null}
typeof ConduitHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

### resolveCredential()

Resolve agent credential from the registry.

```typescript theme={null}
(agentId?: string) => Promise<import("/mnt/projects/cleocode/packages/contracts/dist/agent-registry").AgentCredential>
```

### getStatus()

Get connection status and unread count.

```typescript theme={null}
(agentId?: string) => Promise<{ success: boolean; data: { agentId: string; connected: boolean; pollerRunning: boolean; error: string; unreadTotal?: undefined; actionItems?: undefined; }; } | { success: boolean; data: { agentId: string; connected: boolean; pollerRunning: boolean; unreadTotal: number; actionItems: number; error?: undefined; }; }>
```

### peek()

One-shot peek for messages.

```typescript theme={null}
(agentId?: string, limit?: number) => Promise<{ success: boolean; data: { agentId: string; messages: { id: string; from: string; content: string; conversationId: string | undefined; timestamp: string | undefined; }[]; }; }>
```

### startPolling()

Start continuous polling via cleocode/runtime AgentPoller.

```typescript theme={null}
(agentId?: string, pollIntervalMs?: number, groupConversationIds?: string[]) => Promise<{ success: boolean; data: { agentId: string | null; message: string; alreadyRunning: boolean; pollIntervalMs?: undefined; groupConversationIds?: undefined; }; } | { success: boolean; data: { agentId: string; pollIntervalMs: number; groupConversationIds: string[]; message: string; alreadyRunning?: undefined; }; }>
```

### stopPolling()

Stop the active polling loop.

```typescript theme={null}
() => { success: boolean; data: { message: string; agentId?: undefined; }; } | { success: boolean; data: { agentId: string | null; message: string; }; }
```

### sendMessage()

Send a message to an agent or conversation.

```typescript theme={null}
(content: string, to?: string, conversationId?: string, agentId?: string) => Promise<{ success: boolean; error: { code: string; message: string; }; data?: undefined; } | { success: boolean; data: { messageId: string; from: string; to: string | undefined; sentAt: string; }; error?: undefined; }>
```

## MemoryHandler

**Signature**

```typescript theme={null}
typeof MemoryHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## nexusStatus()

Get nexus status (initialized, project count, last updated).

**Signature**

```typescript theme={null}
() => Promise<EngineResult<{ initialized: boolean; projectCount: number; lastUpdated: string | null; }>>
```

## nexusListProjects()

List all registered projects.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => Promise<EngineResult<{ projects: Awaited<ReturnType<typeof nexusList>>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>>
```

## nexusShowProject()

Show a single project by name.

**Signature**

```typescript theme={null}
(name: string) => Promise<EngineResult<Awaited<ReturnType<typeof nexusGetProject>>>>
```

## nexusResolve()

Resolve a cross-project task query.

**Signature**

```typescript theme={null}
(query: string, currentProject?: string) => Promise<EngineResult<Awaited<ReturnType<typeof resolveTask>>>>
```

## nexusDepsQuery()

Get cross-project dependencies for a task query.

**Signature**

```typescript theme={null}
(query: string, direction?: "forward" | "reverse") => Promise<EngineResult<Awaited<ReturnType<typeof nexusDeps>>>>
```

## nexusGraph()

Build the global dependency graph.

**Signature**

```typescript theme={null}
() => Promise<EngineResult<Awaited<ReturnType<typeof buildGlobalGraph>>>>
```

## nexusCriticalPath()

Get the critical path across projects.

**Signature**

```typescript theme={null}
() => Promise<EngineResult<Awaited<ReturnType<typeof criticalPath>>>>
```

## nexusBlockers()

Analyze blockers for a task query.

**Signature**

```typescript theme={null}
(query: string) => Promise<EngineResult<Awaited<ReturnType<typeof blockingAnalysis>>>>
```

## nexusOrphans()

List orphaned cross-project tasks.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => Promise<EngineResult<{ orphans: Awaited<ReturnType<typeof orphanDetection>>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>>
```

## nexusDiscover()

Discover tasks related to a given task query across projects. Delegates all business logic to src/core/nexus/discover.ts.

**Signature**

```typescript theme={null}
(taskQuery: string, method?: string, limit?: number) => Promise<EngineResult<{ query: string; method: string; results: Array<{ project: string; taskId: string; title: string; score: number; type: string; reason: string; }>; total: number; }>>
```

## nexusSearch()

Search for tasks across all registered projects. Delegates all business logic to src/core/nexus/discover.ts.

**Signature**

```typescript theme={null}
(pattern: string, projectFilter?: string, limit?: number) => Promise<EngineResult<{ pattern: string; results: Array<{ id: string; title: string; status: string; priority?: string; description?: string; _project: string; }>; resultCount: number; }>>
```

## nexusInitialize()

Initialize the nexus.

**Signature**

```typescript theme={null}
() => Promise<EngineResult<{ message: string; }>>
```

## nexusRegisterProject()

Register a project in the nexus.

**Signature**

```typescript theme={null}
(path: string, name?: string, permission?: NexusPermissionLevel) => Promise<EngineResult<{ hash: string; message: string; }>>
```

## nexusUnregisterProject()

Unregister a project from the nexus.

**Signature**

```typescript theme={null}
(name: string) => Promise<EngineResult<{ message: string; }>>
```

## nexusSyncProject()

Sync a specific project or all projects.

**Signature**

```typescript theme={null}
(name?: string) => Promise<EngineResult<unknown>>
```

## nexusSetPermission()

Set permission level for a project.

**Signature**

```typescript theme={null}
(name: string, level: NexusPermissionLevel) => Promise<EngineResult<{ message: string; }>>
```

## nexusReconcileProject()

Reconcile the nexus registry with the filesystem.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<Awaited<ReturnType<typeof nexusReconcile>>>>
```

## nexusShareStatus()

Get sharing status for a project.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<Awaited<ReturnType<typeof getSharingStatus>>>>
```

## nexusShareSnapshotExport()

Export a snapshot of the project's tasks.

**Signature**

```typescript theme={null}
(projectRoot: string, outputPath?: string) => Promise<EngineResult<{ path: string; taskCount: number; checksum: string; }>>
```

## nexusShareSnapshotImport()

Import a snapshot into the project.

**Signature**

```typescript theme={null}
(projectRoot: string, inputPath: string) => Promise<EngineResult<Awaited<ReturnType<typeof importSnapshot>>>>
```

## nexusTransferPreview()

Preview a cross-project task transfer (dry run).

**Signature**

```typescript theme={null}
(params: TransferParams) => Promise<EngineResult<TransferResult>>
```

## nexusTransferExecute()

Execute a cross-project task transfer.

**Signature**

```typescript theme={null}
(params: TransferParams) => Promise<EngineResult<TransferResult>>
```

## NexusHandler

**Signature**

```typescript theme={null}
typeof NexusHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## OrchestrateHandler

**Signature**

```typescript theme={null}
typeof OrchestrateHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## PipelineHandler

**Signature**

```typescript theme={null}
typeof PipelineHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

### queryStage()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateStage()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### queryRelease()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateRelease()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### queryManifest()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### queryPhase()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateManifest()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutatePhase()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### queryChain()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateChain()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

## bindSession()

Bind a session to the current process. Called by session.start mutation handler after successful session creation.

**Signature**

```typescript theme={null}
(ctx: Omit<SessionContext, "agentPid" | "boundAt">) => SessionContext
```

**Throws**

* if a session is already bound (call unbindSession first).

## getBoundSession()

Get the currently bound session context, or null if none is bound.

**Signature**

```typescript theme={null}
() => SessionContext | null
```

## hasSession()

Check whether a session is currently bound.

**Signature**

```typescript theme={null}
() => boolean
```

## unbindSession()

Unbind the current session context. Called by session.end mutation handler.

**Signature**

```typescript theme={null}
() => SessionContext | null
```

**Returns** — The unbound context, or null if nothing was bound.

## resetSessionContext()

Reset the session context (for testing only).

**Signature**

```typescript theme={null}
() => void
```

## SessionHandler

**Signature**

```typescript theme={null}
typeof SessionHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## stickyAdd(projectRoot, params)

Create a new sticky note.

**Signature**

```typescript theme={null}
(projectRoot: string, params: CreateStickyParams) => Promise<EngineResult<StickyNote>>
```

**Parameters**

| Name          | Type                 | Description         |
| ------------- | -------------------- | ------------------- |
| `projectRoot` | `string`             | Project root path   |
| `params`      | `CreateStickyParams` | Creation parameters |

**Returns** — EngineResult with created sticky note

## stickyList(projectRoot, params)

List sticky notes with optional filtering.

**Signature**

```typescript theme={null}
(projectRoot: string, params?: ListStickiesParams) => Promise<EngineResult<{ stickies: StickyNote[]; total: number; }>>
```

**Parameters**

| Name          | Type                   | Description       |
| ------------- | ---------------------- | ----------------- |
| `projectRoot` | `string`               | Project root path |
| `params`      | `: ListStickiesParams` | Filter parameters |

**Returns** — EngineResult with array of sticky notes

## stickyShow(projectRoot, id)

Get a single sticky note by ID.

**Signature**

```typescript theme={null}
(projectRoot: string, id: string) => Promise<EngineResult<StickyNote | null>>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `projectRoot` | `string` | Project root path |
| `id`          | `string` | Sticky note ID    |

**Returns** — EngineResult with sticky note or null

## stickyConvertToTask(projectRoot, stickyId, title)

Convert a sticky note to a task.

**Signature**

```typescript theme={null}
(projectRoot: string, stickyId: string, title?: string) => Promise<EngineResult<{ taskId: string; }>>
```

**Parameters**

| Name          | Type       | Description         |
| ------------- | ---------- | ------------------- |
| `projectRoot` | `string`   | Project root path   |
| `stickyId`    | `string`   | Sticky note ID      |
| `title`       | `: string` | Optional task title |

**Returns** — EngineResult with new task ID

## stickyConvertToMemory(projectRoot, stickyId, memoryType)

Convert a sticky note to a memory observation.

**Signature**

```typescript theme={null}
(projectRoot: string, stickyId: string, memoryType?: string) => Promise<EngineResult<{ memoryId: string; }>>
```

**Parameters**

| Name          | Type       | Description          |
| ------------- | ---------- | -------------------- |
| `projectRoot` | `string`   | Project root path    |
| `stickyId`    | `string`   | Sticky note ID       |
| `memoryType`  | `: string` | Optional memory type |

**Returns** — EngineResult with new memory entry ID

## stickyArchive(projectRoot, id)

Archive a sticky note.

**Signature**

```typescript theme={null}
(projectRoot: string, id: string) => Promise<EngineResult<StickyNote>>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `projectRoot` | `string` | Project root path |
| `id`          | `string` | Sticky note ID    |

**Returns** — EngineResult with archived sticky note

## stickyConvertToTaskNote(projectRoot, stickyId, taskId)

Convert a sticky note to a task note.

**Signature**

```typescript theme={null}
(projectRoot: string, stickyId: string, taskId: string) => Promise<EngineResult<{ taskId: string; }>>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `projectRoot` | `string` | Project root path |
| `stickyId`    | `string` | Sticky note ID    |
| `taskId`      | `string` | Target task ID    |

**Returns** — EngineResult with updated task ID

## stickyConvertToSessionNote(projectRoot, stickyId, sessionId)

Convert a sticky note to a session note.

**Signature**

```typescript theme={null}
(projectRoot: string, stickyId: string, sessionId?: string) => Promise<EngineResult<{ sessionId: string; }>>
```

**Parameters**

| Name          | Type       | Description                |
| ------------- | ---------- | -------------------------- |
| `projectRoot` | `string`   | Project root path          |
| `stickyId`    | `string`   | Sticky note ID             |
| `sessionId`   | `: string` | Optional target session ID |

**Returns** — EngineResult with session ID

## stickyPurge(projectRoot, id)

Purge (permanently delete) a sticky note.

**Signature**

```typescript theme={null}
(projectRoot: string, id: string) => Promise<EngineResult<StickyNote>>
```

**Parameters**

| Name          | Type     | Description       |
| ------------- | -------- | ----------------- |
| `projectRoot` | `string` | Project root path |
| `id`          | `string` | Sticky note ID    |

**Returns** — EngineResult with purged sticky note

## StickyHandler

**Signature**

```typescript theme={null}
typeof StickyHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## TasksHandler

**Signature**

```typescript theme={null}
typeof TasksHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

## codeOutline()

code.outline — file structural skeleton.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>) => Promise<EngineResult>
```

## codeSearch()

code.search — cross-codebase symbol search.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>) => Promise<EngineResult>
```

## codeUnfold()

code.unfold — single symbol extraction.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>) => Promise<EngineResult>
```

## codeParse()

code.parse — raw AST parse for a single file.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>) => Promise<EngineResult>
```

## toolsIssueDiagnostics()

Collect issue diagnostics.

**Signature**

```typescript theme={null}
() => EngineResult<ReturnType<typeof collectDiagnostics>>
```

## toolsSkillList()

List all discovered skills.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => Promise<EngineResult<{ skills: Awaited<ReturnType<typeof discoverSkills>>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>>
```

## toolsSkillShow()

Show a single skill by name.

**Signature**

```typescript theme={null}
(name: string) => Promise<EngineResult<{ skill: Awaited<ReturnType<typeof discoverSkill>>; }>>
```

## toolsSkillFind()

Find skills matching a query string.

**Signature**

```typescript theme={null}
(query?: string) => Promise<EngineResult<{ skills: Awaited<ReturnType<typeof discoverSkills>>; count: number; query: string; }>>
```

## toolsSkillDispatch()

Get dispatch matrix entries for a skill.

**Signature**

```typescript theme={null}
(name: string) => EngineResult<{ skill: string; dispatch: { byTaskType: string[]; byKeyword: string[]; byProtocol: string[]; }; }>
```

## toolsSkillVerify()

Verify a skill's installation and catalog status.

**Signature**

```typescript theme={null}
(name: string) => Promise<EngineResult<{ skill: string; installed: boolean; inCatalog: boolean; installPath: string | null; }>>
```

## toolsSkillDependencies()

Get dependency tree for a skill.

**Signature**

```typescript theme={null}
(name: string) => EngineResult<{ skill: string; direct: ReturnType<typeof catalog.getSkillDependencies>; tree: ReturnType<typeof catalog.resolveDependencyTree>; }>
```

## toolsSkillSpawnProviders()

Get spawn-capable providers by capability.

**Signature**

```typescript theme={null}
(capability?: "supportsSubagents" | "supportsProgrammaticSpawn" | "supportsInterAgentComms" | "supportsParallelSpawn") => Promise<EngineResult<{ providers: unknown[]; capability: string; count: number; }>>
```

## toolsSkillCatalogInfo()

Get catalog info (protocols, profiles, resources, or summary).

**Signature**

```typescript theme={null}
() => EngineResult<{ available: boolean; version: string | null; libraryRoot: string | null; skillCount: number; protocolCount: number; profileCount: number; }>
```

## toolsSkillCatalogProtocols()

List catalog protocols.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => EngineResult<{ protocols: Array<{ name: string; path: string | null; }>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>
```

## toolsSkillCatalogProfiles()

List catalog profiles.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => EngineResult<{ profiles: Array<{ name: string; description: string; extends: string | undefined; skillCount: number; skills: string[]; }>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>
```

## toolsSkillCatalogResources()

List catalog shared resources.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => EngineResult<{ resources: Array<{ name: string; path: string | null; }>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>
```

## toolsSkillPrecedenceShow()

Show skill precedence map.

**Signature**

```typescript theme={null}
() => Promise<EngineResult<{ precedenceMap: unknown; }>>
```

## toolsSkillPrecedenceResolve()

Resolve skill paths for a specific provider.

**Signature**

```typescript theme={null}
(providerId: string, scope: "global" | "project", projectRoot: string) => Promise<EngineResult<{ providerId: string; scope: string; paths: unknown; }>>
```

## toolsSkillInstall()

Install a skill to one or more providers.

**Signature**

```typescript theme={null}
(name: string, projectRoot: string, source?: string, isGlobal?: boolean) => Promise<EngineResult<{ results: Array<{ providerId: string; success: boolean; errors: string[]; }>; targets: string[]; }>>
```

## toolsSkillUninstall()

Uninstall a skill from all providers.

**Signature**

```typescript theme={null}
(name: string, projectRoot: string, isGlobal?: boolean) => Promise<EngineResult<{ removed: string[]; errors: string[]; }>>
```

## toolsSkillRefresh()

Refresh all tracked skills that have updates available.

**Signature**

```typescript theme={null}
(projectRoot: string) => Promise<EngineResult<{ updated: string[]; failed: Array<{ name: string; error: string; }>; checked: number; }>>
```

## toolsProviderList()

List all registered providers.

**Signature**

```typescript theme={null}
(limit?: number, offset?: number) => EngineResult<{ providers: ReturnType<typeof getAllProviders>; count: number; total: number; filtered: number; page: ReturnType<typeof paginate>["page"]; }>
```

## toolsProviderDetect()

Detect all available providers in the environment.

**Signature**

```typescript theme={null}
() => EngineResult<{ providers: ReturnType<typeof detectAllProviders>; count: number; }>
```

## toolsProviderInjectStatus()

Check injection status for all installed providers.

**Signature**

```typescript theme={null}
(projectRoot: string, scope?: "project" | "global", content?: string) => Promise<EngineResult<{ checks: unknown[]; count: number; }>>
```

## toolsProviderSupports()

Check if a provider supports a specific capability.

**Signature**

```typescript theme={null}
(providerId: string, capability: string) => Promise<EngineResult<{ providerId: string; capability: string; supported: boolean; }>>
```

## toolsProviderHooks()

Query hook providers for a specific event.

**Signature**

```typescript theme={null}
(event: string) => Promise<EngineResult<unknown>>
```

## toolsProviderInject()

Inject CLEO directives into all installed provider instruction files.

**Signature**

```typescript theme={null}
(projectRoot: string, scope?: "project" | "global", references?: string[], content?: string) => Promise<EngineResult<{ actions: Array<{ file: string; action: string; }>; count: number; }>>
```

## toolsAdapterList()

List all discovered adapters.

**Signature**

```typescript theme={null}
(projectRoot: string) => EngineResult<{ adapters: ReturnType<AdapterManager["listAdapters"]>; count: number; }>
```

## toolsAdapterShow()

Show a single adapter by ID.

**Signature**

```typescript theme={null}
(projectRoot: string, id: string) => EngineResult<{ manifest: unknown; initialized: boolean; active: boolean; }>
```

## toolsAdapterDetect()

Detect active adapters.

**Signature**

```typescript theme={null}
(projectRoot: string) => EngineResult<{ detected: string[]; count: number; }>
```

## toolsAdapterHealth()

Get adapter health status.

**Signature**

```typescript theme={null}
(projectRoot: string, id?: string) => EngineResult<{ adapters: ReturnType<AdapterManager["listAdapters"]>; count: number; }>
```

## toolsAdapterActivate()

Activate an adapter by ID.

**Signature**

```typescript theme={null}
(projectRoot: string, id: string) => Promise<EngineResult<{ id: string; name: string; version: string; active: boolean; }>>
```

## toolsAdapterDispose()

Dispose one or all adapters.

**Signature**

```typescript theme={null}
(projectRoot: string, id?: string) => Promise<EngineResult<{ disposed: string; }>>
```

## ToolsHandler

**Signature**

```typescript theme={null}
typeof ToolsHandler
```

**Methods**

### query()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### mutate()

```typescript theme={null}
(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

### getSupportedOperations()

```typescript theme={null}
() => { query: string[]; mutate: string[]; }
```

### queryIssue()

```typescript theme={null}
(sub: string, _params: Record<string, unknown> | undefined, startTime: number) => DispatchResponse
```

### mutateIssue()

```typescript theme={null}
(sub: string, _params: Record<string, unknown> | undefined, startTime: number) => DispatchResponse
```

### querySkill()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateSkill()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### queryProvider()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateProvider()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### queryAdapter()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => DispatchResponse
```

### queryCode()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### mutateAdapter()

```typescript theme={null}
(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>
```

### handleError()

```typescript theme={null}
(gateway: string, domain: string, operation: string, error: unknown, startTime: number) => DispatchResponse
```

## createDomainHandlers()

Create a Map of all canonical domain handlers.

**Signature**

```typescript theme={null}
() => Map<string, DomainHandler>
```

## RateLimiter

Sliding-window rate limiter for the dispatch pipeline.

**Signature**

```typescript theme={null}
typeof RateLimiter
```

**Methods**

### check()

```typescript theme={null}
(req: DispatchRequest) => RateLimitMeta & { allowed: boolean; }
```

### resolveCategory()

```typescript theme={null}
(gateway: string, domain: string, operation: string) => "query" | "mutate" | "spawn"
```

### getLimitConfig()

```typescript theme={null}
(category: "query" | "mutate" | "spawn") => RateLimitConfig
```

## createRateLimiter(config)

Creates a rate limiting middleware for the dispatch pipeline.

**Signature**

```typescript theme={null}
(config?: Partial<RateLimitingConfig>) => Middleware
```

**Parameters**

| Name     | Type                            | Description                                  |
| -------- | ------------------------------- | -------------------------------------------- |
| `config` | `: Partial<RateLimitingConfig>` | Optional partial config to override defaults |

**Returns** — Middleware function that enforces rate limits

**Example**

```typescript theme={null}
import { createRateLimiter } from './rate-limiter.js';

const limiter = createRateLimiter({ query: { maxRequests: 50, windowMs: 30_000 } });
```

## ConfigValidationError

Configuration validation error

**Signature**

```typescript theme={null}
typeof ConfigValidationError
```

## validateConfig()

Validate complete configuration

**Signature**

```typescript theme={null}
(config: DispatchConfig) => void
```

## loadConfig()

Load configuration from all sources  Priority order: 1. Environment variables (CLEO\_\*) 2. Config file (.cleo/config.json) 3. Defaults

**Signature**

```typescript theme={null}
(projectRoot?: string) => DispatchConfig
```

## getConfig()

Get global configuration (singleton)

**Signature**

```typescript theme={null}
() => DispatchConfig
```

## resetConfig()

Reset global configuration (for testing)

**Signature**

```typescript theme={null}
() => void
```

## createAudit()

Creates an audit middleware that logs all mutate operations (and query operations during grade sessions) to Pino + SQLite.

**Signature**

```typescript theme={null}
() => Middleware
```

## createFieldFilter()

Create the LAFS field-filter middleware.  Handles: - \_fields: filter response data to specified fields (delegates to SDK applyFieldFilter) - \_mvi: envelope verbosity — stored on request for downstream use  \_fields and \_mvi are extracted from req.params (for callers that pass them as params) and stored on the DispatchRequest before the domain handler runs.

**Signature**

```typescript theme={null}
() => Middleware
```

## createSanitizer(getProjectRoot)

Creates a middleware that sanitizes incoming request parameters. Uses the canonical sanitization logic from security.ts to handle Task IDs, paths, string lengths, and enum validation.

**Signature**

```typescript theme={null}
(getProjectRoot?: () => string) => Middleware
```

**Parameters**

| Name             | Type  | Description                                                                 |
| ---------------- | ----- | --------------------------------------------------------------------------- |
| `getProjectRoot` | `: (` | Optional function to resolve the current project root for path sanitization |

**Returns** — Middleware function that sanitizes request params

**Example**

```typescript theme={null}
import { createSanitizer } from './sanitizer.js';

const sanitizer = createSanitizer(() => process.cwd());
```

## createSessionResolver(cliSessionLookup)

Creates the session resolver middleware.

**Signature**

```typescript theme={null}
(cliSessionLookup?: () => Promise<string | null>) => Middleware
```

**Parameters**

| Name               | Type  | Description                                                                                                                                                  |
| ------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `cliSessionLookup` | `: (` | Optional async function that resolves the active   session ID from SQLite for CLI commands. If not provided, the resolver   falls through to env var / null. |

## getCliDispatcher()

Get or create the singleton CLI dispatcher.  Creates a Dispatcher with all 9 domain handlers and sanitizer middleware. No rate limiter — CLI is a single-user tool.

**Signature**

```typescript theme={null}
() => Dispatcher
```

## createCliDispatcher()

Factory: creates a Dispatcher with all domain handlers + session-resolver, sanitizer, field-filter, and audit middleware.   T4959 — added session-resolver + audit to CLI pipeline

**Signature**

```typescript theme={null}
() => Dispatcher
```

## resetCliDispatcher()

Reset the singleton dispatcher (for testing).

**Signature**

```typescript theme={null}
() => void
```

## dispatchFromCli()

Build a DispatchRequest, dispatch it, and handle output/errors.  This is the primary entry point for migrated CLI commands:   await dispatchFromCli('query', 'tasks', 'show',  taskId ,  command: 'show' );  Automatically honors global --field/--fields/--mvi flags from the FieldContext: - --field    → plain-text extraction, no JSON envelope - --fields   → field-filter middleware filters the JSON response - --mvi     → envelope verbosity passed to field-filter middleware  On success: calls cliOutput(response.data, outputOpts) On error: calls cliError(message, exitCode) + process.exit(exitCode)   T4953  T4955

**Signature**

```typescript theme={null}
(gateway: Gateway, domain: string, operation: string, params?: Record<string, unknown>, outputOpts?: CliOutputOptions) => Promise<void>
```

## handleRawError()

Handle an error response from dispatchRaw().  Calls cliError() and process.exit() when the response indicates failure. No-op when response.success is true.

**Signature**

```typescript theme={null}
(response: DispatchResponse, _opts: { command: string; operation: string; }) => void
```

## dispatchRaw()

Dispatch and return the raw response without handling output.  For commands that need custom output logic (pagination, conditional messages, etc.), call this instead of dispatchFromCli().

**Signature**

```typescript theme={null}
(gateway: Gateway, domain: string, operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>
```

## registerAddCommand()

Register the add command.  T4460

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerAdminCommand()

Register the admin command group.

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerAdrCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerAgentCommand()

Register the `cleo agent` command group.

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerAgentsCommand()

Register `agents` as an alias that prints deprecation notice. Health monitoring is now under `cleo agent health`.

**Signature**

```typescript theme={null}
(_program: Command) => void
```

## registerAnalyzeCommand()

Register the analyze command.  T4538

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerArchiveCommand()

Register the archive command.  T4461

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerArchiveStatsCommand()

Register the archive-stats command. Routes through dispatch layer to admin.archive.stats.  T4555

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerBackfillCommand(program)

Register the `cleo backfill` CLI command.

**Signature**

```typescript theme={null}
(program: Command) => void
```

**Parameters**

| Name      | Type      | Description                       |
| --------- | --------- | --------------------------------- |
| `program` | `Command` | The root CLI command to attach to |

**Example**

```ts theme={null}
registerBackfillCommand(rootCommand);
// Adds: cleo backfill [--dry-run] [--rollback] [--embeddings]
```

## registerBackupCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerBlockersCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerBrainCommand(program)

Register the `cleo brain` command group.  Registers a `brain` parent command and a `maintenance` subcommand that combines temporal decay, memory consolidation, and embedding backfill into one idempotent pass.

**Signature**

```typescript theme={null}
(program: Command) => void
```

**Parameters**

| Name      | Type      | Description                       |
| --------- | --------- | --------------------------------- |
| `program` | `Command` | The root CLI command to attach to |

**Example**

```ts theme={null}
registerBrainCommand(rootCommand);
// Adds: cleo brain maintenance [--skip-decay] [--skip-consolidation] [--skip-embeddings] [--json]
```

## registerBriefingCommand()

Register the briefing command.  T4916

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerBugCommand()

Register the bug command.  T4913

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerCantCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerCheckCommand()

Register the check command group.

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerCheckpointCommand()

Register the checkpoint command. Delegates to src/store/git-checkpoint.ts for isolated .cleo/.git operations.  T4551  T4872

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerCommandsCommand()

Register the commands command.  T4551, T5671

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerCompleteCommand()

Register the complete command.  T4461

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerComplianceCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerConfigCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerConsensusCommand()

Register the consensus command group.  T4537

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerContextCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerContributionCommand()

Register the contribution command group.  T4537

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerCurrentCommand()

Register the current command.  T4756  T4666

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerDashCommand()

Register the dash command.  T4535

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerDecompositionCommand()

Register the decomposition command group.  T4537

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerDeleteCommand()

Register the delete command.  T4461

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerDepsCommand(program)

Register the deps command group and its subcommands.

**Signature**

```typescript theme={null}
(program: Command) => void
```

**Parameters**

| Name      | Type      | Description                |
| --------- | --------- | -------------------------- |
| `program` | `Command` | Root CLI program instance. |

## registerTreeCommand(program)

Register the tree command.

**Signature**

```typescript theme={null}
(program: Command) => void
```

**Parameters**

| Name      | Type      | Description                |
| --------- | --------- | -------------------------- |
| `program` | `Command` | Root CLI program instance. |

## registerDetectCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerDetectDriftCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerDocsCommand()

Register the docs command.  T4551

**Signature**

```typescript theme={null}
(program: Command) => void
```

## ProgressTracker

Simple progress tracker for CLI operations.

**Signature**

```typescript theme={null}
typeof ProgressTracker
```

**Methods**

### start()

Start the progress tracker.

```typescript theme={null}
() => void
```

### step()

Update to a specific step.

```typescript theme={null}
(index: number, message?: string) => void
```

### next()

Move to next step.

```typescript theme={null}
(message?: string) => void
```

### complete()

Mark as complete with optional summary.

```typescript theme={null}
(summary?: string) => void
```

### error()

Report an error.

```typescript theme={null}
(message: string) => void
```

## Spinner

Simple spinner for indeterminate progress.

**Signature**

```typescript theme={null}
typeof Spinner
```

**Methods**

### start()

Start the spinner.

```typescript theme={null}
() => void
```

### stop()

Stop the spinner.

```typescript theme={null}
(finalMessage?: string) => void
```

### update()

Update the spinner message.

```typescript theme={null}
(message: string) => void
```

## createSelfUpdateProgress()

Create a progress tracker for self-update operations.

**Signature**

```typescript theme={null}
(enabled: boolean) => ProgressTracker
```

## createDoctorProgress()

Create a progress tracker for doctor operations.

**Signature**

```typescript theme={null}
(enabled: boolean) => ProgressTracker
```

## createUpgradeProgress()

Create a progress tracker for upgrade operations.

**Signature**

```typescript theme={null}
(enabled: boolean) => ProgressTracker
```

## registerDoctorCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerEnvCommand()

Register the env command group.  T4581

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerExistsCommand(program)

Register the exists command.

**Signature**

```typescript theme={null}
(program: Command) => void
```

**Parameters**

| Name      | Type      | Description                |
| --------- | --------- | -------------------------- |
| `program` | `Command` | Root CLI program instance. |

**Example**

```ts theme={null}
registerExistsCommand(rootCommand);
// cleo exists T001 → exit 0 if found, exit 4 if not
```

## registerExportCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerExportTasksCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerFindCommand()

Register the find command.  T4460  T4668

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerGenerateChangelogCommand()

Register the generate-changelog command.  T4555

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerGradeCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerHistoryCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerImplementationCommand()

Register the implementation command group.  T4537

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerImportCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerImportTasksCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## getGitignoreTemplate()

Load the gitignore template from the package's templates/ directory. Falls back to embedded content if file not found.  Kept as export for backward compatibility (used by upgrade.ts).  T4700

**Signature**

```typescript theme={null}
() => string
```

## registerInitCommand()

Register the init command.  T4681  T4663

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerInjectCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerIssueCommand()

Register the issue command with all subcommands.  T4555

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerLabelsCommand()

Register the labels command group.  T4538

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerLifecycleCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerListCommand()

Register the list command.  T4460  T4668

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerLogCommand()

Register the log command.  T4538

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerMapCommand()

Register the map command.

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerMemoryBrainCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerMigrateClaudeMemCommand()

Register the `migrate claude-mem` command under a migrate parent command.  Usage:   cleo migrate claude-mem \[--dry-run] \[--source ] \[--project ]

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerNextCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerNexusCommand()

Register the nexus command group.  T4554

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerObserveCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerOpsCommand()

Register the ops command.

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerOrchestrateCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerOtelCommand()

Register the otel command group.  T4535

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerPhaseCommand()

Register the phase command group.  T4464, T5326

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerPhasesCommand()

Register the phases command group.  T4538, T5326

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerPlanCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerPromoteCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerReasonCommand(program)

Register the `cleo reason` command group and its subcommands.

**Signature**

```typescript theme={null}
(program: Command) => void
```

**Parameters**

| Name      | Type      | Description                                 |
| --------- | --------- | ------------------------------------------- |
| `program` | `Command` | Root CLI program instance (commander shim). |

**Example**

```ts theme={null}
registerReasonCommand(rootCommand);
// Adds: cleo reason why|similar|impact|timeline
```

## registerRefreshMemoryCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerRelatesCommand()

Register the relates command group.  T4538

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerReleaseCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerRemoteCommand()

Register the remote command with add/remove/list/push/pull subcommands.  T4884

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerReorderCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerReparentCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerResearchCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerRestoreCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerRoadmapCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSafestopCommand()

Register the safestop command.  T4551

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSelfUpdateCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSequenceCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSessionCommand()

Register the session command group.  T4463

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerShowCommand()

Register the show command.  T4460  T4666

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSkillsCommand()

Register the skills command with all subcommands.  T4555

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSnapshotCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerSpecificationCommand()

Register the specification command group.  T4537

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerStartCommand()

Register the start command.  T4756  T4666

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerStatsCommand()

Register the stats command.  T4535

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerStickyCommand()

Register the sticky command group.  T5281

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerStopCommand()

Register the stop command.  T4756  T4666

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerTestingCommand()

Register the testing command.  T4551

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerTokenCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerUpdateCommand()

Register the update command.  T4461

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerUpgradeCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerValidateCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerVerifyCommand()

**Signature**

```typescript theme={null}
(program: Command) => void
```

## registerWebCommand()

Register the web command.  T4551

**Signature**

```typescript theme={null}
(program: Command) => void
```

## initCliLogger()

Initialize CLI logger with optional projectHash correlation context.

**Signature**

```typescript theme={null}
(cwd: string, loggingConfig: LoggerConfig) => void
```

## registerDynamicCommands()

Register dynamically-generated commands onto the Commander program.  Stub implementation: no commands registered until T4897 populates OperationDef.params arrays for all operations.

**Signature**

```typescript theme={null}
(_program: Command) => void
```

## renderErrorMarkdown()

Render a CleoError as structured markdown for CLI display.

**Signature**

```typescript theme={null}
(error: CleoError) => string
```

## createProtocolEnforcement(strictMode)

Creates a middleware that enforces protocol compliance.  Delegates to ProtocolEnforcer.enforceProtocol() which: - Passes through query operations untouched - Passes through mutate operations that don't require validation - Validates protocol compliance on validated mutate operations after execution - In strict mode, blocks operations with protocol violations (exit codes 60-70)

**Signature**

```typescript theme={null}
(strictMode?: boolean) => Middleware
```

**Parameters**

| Name         | Type        | Description                                              |
| ------------ | ----------- | -------------------------------------------------------- |
| `strictMode` | `: boolean` | When true, blocks operations that violate protocol rules |

**Returns** — Middleware function that enforces protocol compliance

**Example**

```typescript theme={null}
import { createProtocolEnforcement } from './protocol-enforcement.js';

const enforcement = createProtocolEnforcement(true);
```

## createVerificationGates(strictMode)

Creates a middleware that enforces verification gates on task operations.

**Signature**

```typescript theme={null}
(strictMode?: boolean) => Middleware
```

**Parameters**

| Name         | Type        | Description                                               |
| ------------ | ----------- | --------------------------------------------------------- |
| `strictMode` | `: boolean` | When true, blocks operations that fail verification gates |

**Returns** — Middleware function that enforces verification gates

**Example**

```typescript theme={null}
import { createVerificationGates } from './verification-gates.js';

const gates = createVerificationGates(true);
```

## getOperationSchema(domain, operation, gateway)

Look up an operation in the OPERATIONS registry and return a JSON Schema object suitable for use as `input_schema.properties.params` or as a stand-alone per-operation schema.

**Signature**

```typescript theme={null}
(domain: string, operation: string, gateway: Gateway) => JSONSchemaObject
```

**Parameters**

| Name        | Type      | Description                                     |
| ----------- | --------- | ----------------------------------------------- |
| `domain`    | `string`  | Canonical domain name (e.g. 'tasks', 'session') |
| `operation` | `string`  | Operation name (e.g. 'show', 'add')             |
| `gateway`   | `Gateway` | Gateway ('query' or 'mutate')                   |

**Returns** — JSONSchemaObject derived from ParamDef\[], or permissive fallback

## getAllOperationSchemas()

Return schemas for ALL operations of a given gateway.  Useful for documentation generation and tool introspection endpoints.

**Signature**

```typescript theme={null}
(gateway: Gateway) => Record<string, JSONSchemaObject>
```

**Returns** — Record keyed by "." → JSONSchemaObject

## resolveTier(params, sessionScope)

Resolve tier from request params, defaulting to 'standard'.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>, sessionScope?: { type: string; epicId?: string; } | null) => MviTier
```

**Parameters**

| Name           | Type                                           | Description                                        |
| -------------- | ---------------------------------------------- | -------------------------------------------------- |
| `params`       | `: Record<string`                              | Request params that may contain a `_mviTier` field |
| `sessionScope` | `: { type: string; epicId?: string; } \| null` | Current session scope for auto-tier detection      |

**Returns** — The resolved MVI tier

**Example**

```typescript theme={null}
import { resolveTier } from './projections.js';

const tier = resolveTier(req.params, currentSession?.scope);
```

## isOperationAllowed()

Check if a domain is allowed at the given tier.

**Signature**

```typescript theme={null}
(domain: string, tier: MviTier) => boolean
```

## applyProjection()

Apply field projection to a result object. Removes fields that are excluded at the given tier and prunes depth.

**Signature**

```typescript theme={null}
<T>(data: T, config: ProjectionConfig) => T
```

## createProjectionContext()

Create projection context from request params.

**Signature**

```typescript theme={null}
(params?: Record<string, unknown>) => ProjectionContext
```

## createProjectionMiddleware()

Create the MVI projection middleware.  Extracts \_mviTier from params, checks domain access, and applies field exclusions to the response.

**Signature**

```typescript theme={null}
() => Middleware
```
