Skip to main content
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
<T>(code: string, message: string, options?: { details?: Record<string, unknown>; fix?: string; alternatives?: Array<{ action: string; command: string; }>; }) => EngineResult<T>
Parameters
NameTypeDescription
codestringString error code (e.g., ‘E_NOT_FOUND’)
messagestringHuman-readable error message
options: { details?: Record<stringOptional details, fix command, and alternatives
Returns — EngineResult with success=false and properly structured error Example
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
<T>(data: T) => EngineResult<T>
Parameters
NameTypeDescription
dataTThe result data
Returns — EngineResult with success=true Example
import { engineSuccess } from './_error.js';

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

taskShow(projectRoot, taskId)

Get a single task by ID. Signature
(projectRoot: string, taskId: string) => Promise<EngineResult<{ task: TaskRecord; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier (e.g. “T001”)
Returns — EngineResult containing the task record Example
const result = await taskShow('/project', 'T42');
if (result.success) console.log(result.data.task.title);

taskList(projectRoot, params)

List tasks with optional filters. Signature
(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
NameTypeDescription
projectRootstringAbsolute 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
const result = await taskList('/project', { status: 'active', limit: 10 });

taskFind(projectRoot, query, limit, options)

Fuzzy search tasks by title/description/ID. Signature
(projectRoot: string, query: string, limit?: number, options?: { id?: string; exact?: boolean; status?: string; includeArchive?: boolean; offset?: number; }) => Promise<EngineResult<{ results: MinimalTaskRecord[]; total: number; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
querystringSearch string to match against title, description, or ID
limit: numberMaximum 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
const result = await taskFind('/project', 'authentication', 10);

taskExists(projectRoot, taskId)

Check if a task exists. Signature
(projectRoot: string, taskId: string) => Promise<EngineResult<{ exists: boolean; taskId: string; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to check
Returns — EngineResult with exists flag and the queried taskId Example
const result = await taskExists('/project', 'T42');
if (result.success && result.data.exists) { console.log('exists'); }

taskCreate(projectRoot, params)

Create a new task. Signature
(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
NameTypeDescription
projectRootstringAbsolute 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
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
(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
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask 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
const result = await taskUpdate('/project', 'T42', { status: 'active' });

taskComplete(projectRoot, taskId, notes)

Complete a task (set status to done). Signature
(projectRoot: string, taskId: string, notes?: string) => Promise<EngineResult<{ task: TaskRecord; autoCompleted?: string[]; unblockedTasks?: Array<{ id: string; title: string; }>; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to complete
notes: stringOptional completion notes
Returns — EngineResult with the completed task, auto-completed parents, and unblocked tasks Example
const result = await taskComplete('/project', 'T42', 'All tests passing');

taskDelete(projectRoot, taskId, force)

Delete a task. Signature
(projectRoot: string, taskId: string, force?: boolean) => Promise<EngineResult<{ deletedTask: TaskRecord; deleted: boolean; cascadeDeleted?: string[]; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to delete
force: booleanWhen true, enables cascade deletion of children
Returns — EngineResult with the deleted task and optional cascade info Example
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
(projectRoot: string, taskId?: string, before?: string) => Promise<EngineResult<{ archivedCount: number; archivedTasks: Array<{ id: string; }>; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskId: stringOptional specific task ID to archive
before: stringOptional ISO date string; archives tasks completed before this date
Returns — EngineResult with count and list of archived task IDs Example
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
(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
NameTypeDescription
projectRootstringAbsolute 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
const result = await taskNext('/project', { count: 3, explain: true });

taskBlockers(projectRoot, params)

Show blocked tasks and analyze blocking chains. Signature
(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
NameTypeDescription
projectRootstringAbsolute 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
const result = await taskBlockers('/project', { analyze: true });

taskTree(projectRoot, taskId)

Build hierarchy tree. Signature
(projectRoot: string, taskId?: string) => Promise<EngineResult>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskId: stringOptional root task ID for subtree
Returns — EngineResult with the hierarchical tree data Example
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
(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
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to inspect
Returns — EngineResult with dependency information in both directions Example
const result = await taskDeps('/project', 'T42');

taskRelates(projectRoot, taskId)

Show task relations (existing relates entries). Signature
(projectRoot: string, taskId: string) => Promise<EngineResult<{ taskId: string; relations: Array<{ taskId: string; type: string; reason?: string; }>; count: number; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to inspect
Returns — EngineResult with relations array and count Example
const result = await taskRelates('/project', 'T42');

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

Add a relation between two tasks. Signature
(projectRoot: string, taskId: string, relatedId: string, type: string, reason?: string) => Promise<EngineResult<{ from: string; to: string; type: string; added: boolean; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringSource task identifier
relatedIdstringTarget task identifier
typestringRelation type (e.g. “blocks”, “related”)
reason: stringOptional explanation for the relation
Returns — EngineResult confirming the relation was added Example
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
(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
NameTypeDescription
projectRootstringAbsolute path to the project root
taskId: stringOptional specific task to analyze
params: { tierLimit?: number; }Optional analysis parameters
Returns — EngineResult with recommended task, bottlenecks, tiers, and metrics Example
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
(projectRoot: string, change: string, matchLimit?: number) => Promise<EngineResult<ImpactReport>>
Parameters
NameTypeDescription
projectRootstringProject root directory
changestringFree-text description of the proposed change
matchLimit: numberMaximum seed tasks to match (default: 5)
Returns — Impact prediction report Example
const result = await taskImpact('/project', 'Refactor authentication module');

taskRestore(projectRoot, taskId, params)

Restore a cancelled task back to pending. Signature
(projectRoot: string, taskId: string, params?: { cascade?: boolean; notes?: string; }) => Promise<EngineResult<{ task: string; restored: string[]; count: number; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to restore
params: { cascade?: boolean; notes?: string; }Optional cascade and notes options
Returns — EngineResult with restored task IDs and count Example
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
(projectRoot: string, taskId: string, params?: { status?: string; preserveStatus?: boolean; }) => Promise<EngineResult<{ task: string; unarchived: boolean; title: string; status: string; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringArchived task identifier to restore
params: { status?: string; preserveStatus?: boolean; }Optional status override parameters
Returns — EngineResult with the unarchived task info Example
const result = await taskUnarchive('/project', 'T42', { status: 'pending' });

taskReorder(projectRoot, taskId, position)

Change task position within its sibling group. Signature
(projectRoot: string, taskId: string, position: number) => Promise<EngineResult<{ task: string; reordered: boolean; newPosition: number; totalSiblings: number; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to reorder
positionnumberTarget zero-based position
Returns — EngineResult with new position and total siblings Example
const result = await taskReorder('/project', 'T42', 0); // move to first

taskReparent(projectRoot, taskId, newParentId)

Move task under a different parent. Signature
(projectRoot: string, taskId: string, newParentId: string | null) => Promise<EngineResult<{ task: string; reparented: boolean; oldParent: string | null; newParent: string | null; newType?: string; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to move
newParentIdstring | nullNew parent task ID, or null for root
Returns — EngineResult with old and new parent information Example
const result = await taskReparent('/project', 'T42', 'T1');

taskPromote(projectRoot, taskId)

Promote a subtask to task or task to root (remove parent). Signature
(projectRoot: string, taskId: string) => Promise<EngineResult<{ task: string; promoted: boolean; previousParent: string | null; typeChanged: boolean; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to promote
Returns — EngineResult with promotion details Example
const result = await taskPromote('/project', 'T42');

taskReopen(projectRoot, taskId, params)

Reopen a completed task (set status back to pending). Signature
(projectRoot: string, taskId: string, params?: { status?: string; reason?: string; }) => Promise<EngineResult<{ task: string; reopened: boolean; previousStatus: string; newStatus: string; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to reopen
params: { status?: string; reason?: string; }Optional target status and reason
Returns — EngineResult with reopen details including previous and new status Example
const result = await taskReopen('/project', 'T42', { reason: 'Tests regressed' });

taskCancel(projectRoot, taskId, reason)

Cancel a task (soft terminal state — reversible via restore). Signature
(projectRoot: string, taskId: string, reason?: string) => Promise<EngineResult<{ task: string; cancelled: boolean; reason?: string; cancelledAt: string; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
taskIdstringTask identifier to cancel
reason: stringOptional cancellation reason
Returns — EngineResult with cancellation details Example
const result = await taskCancel('/project', 'T42', 'No longer needed');

taskComplexityEstimate(projectRoot, params)

Deterministic complexity scoring from task metadata. Signature
(projectRoot: string, params: { taskId: string; }) => Promise<EngineResult<{ size: "small" | "medium" | "large"; score: number; factors: ComplexityFactor[]; dependencyDepth: number; subtaskCount: number; fileCount: number; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute 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
const result = await taskComplexityEstimate('/project', { taskId: 'T42' });

taskDepends()

List dependencies for a task in a given direction. T4657 T4790 T4654 Signature
(projectRoot: string, taskId: string, direction?: "upstream" | "downstream" | "both", tree?: boolean) => Promise<EngineResult>

taskDepsOverview()

Overview of all dependencies across the project. T5157 Signature
(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
(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
(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
(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
(projectRoot: string, taskId: string, limit?: number) => Promise<EngineResult<Array<Record<string, unknown>>>>

taskLint()

Lint tasks for common issues. T4657 T4790 T4654 Signature
(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
(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
(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
(projectRoot: string) => Promise<EngineResult>

taskRelatesFind()

Find related tasks using semantic search or keyword matching. T5672 Signature
(projectRoot: string, taskId: string, params?: { mode?: "suggest" | "discover"; threshold?: number; }) => Promise<EngineResult<Record<string, unknown>>>

taskLabelList()

List all labels used in tasks. T5672 Signature
(projectRoot: string) => Promise<EngineResult<{ labels: unknown[]; count: number; }>>

taskLabelShow()

Show tasks associated with a label. T5672 Signature
(projectRoot: string, label: string) => Promise<EngineResult<Record<string, unknown>>>

taskSyncReconcile()

Reconcile external tasks with CLEO as SSoT. Signature
(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>>
List external task links by provider or task ID. Signature
(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
(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
(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
(projectRoot: string, taskId: string) => Promise<EngineResult<{ taskId: string; }>>

sessionStatus(projectRoot)

Get current session status. Signature
(projectRoot: string) => Promise<EngineResult<{ hasActiveSession: boolean; session?: Session | null; taskWork?: TaskWorkState | null; }>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
Returns — EngineResult with active session flag, session record, and task work state Example
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
(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
NameTypeDescription
projectRootstringAbsolute 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
const result = await sessionList('/project', { active: true, limit: 5 });

sessionFind(projectRoot, params)

Lightweight session discovery — returns minimal session records. Signature
(projectRoot: string, params?: FindSessionsParams) => Promise<EngineResult<MinimalSessionRecord[]>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
params: FindSessionsParamsOptional search parameters
Returns — EngineResult with array of minimal session records Example
const result = await sessionFind('/project', { status: 'active' });

sessionShow(projectRoot, sessionId)

Show a specific session by ID. Signature
(projectRoot: string, sessionId: string) => Promise<EngineResult<Session>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
sessionIdstringSession identifier to look up
Returns — EngineResult with the full Session record Example
const result = await sessionShow('/project', 'ses_20260401_abc123');

taskCurrentGet()

Get current task being worked on. Delegates to core/task-work/currentTask. T4782 Signature
(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
(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
(projectRoot: string) => Promise<EngineResult<{ cleared: boolean; previousTask: string | null; }>>

taskWorkHistory()

Get task work history from session notes. T5323 Signature
(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
(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
(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
(projectRoot: string, sessionId: string) => Promise<EngineResult<Session>>

sessionGc()

Garbage collect old sessions. T4782 Signature
(projectRoot: string, maxAgeDays?: number) => Promise<EngineResult<{ orphaned: string[]; removed: string[]; }>>

sessionSuspend()

Suspend an active session. T4782 Signature
(projectRoot: string, sessionId: string, reason?: string) => Promise<EngineResult<Session>>

sessionHistory()

List session history with focus changes and completed tasks. T4782 Signature
(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
(projectRoot: string) => Promise<EngineResult<{ removed: string[]; autoEnded: string[]; cleaned: boolean; }>>

sessionRecordDecision()

Record a decision to the audit trail. T4782 Signature
(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
(projectRoot: string, params?: { sessionId?: string; taskId?: string; }) => Promise<EngineResult<DecisionRecord[]>>

sessionContextDrift()

Compute context drift score for the current session. T4782 Signature
(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
(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
(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
(projectRoot: string, sessionId: string) => Promise<EngineResult<Session>>

sessionArchive()

Archive old/ended sessions. T4782 Signature
(projectRoot: string, olderThan?: string) => Promise<EngineResult<{ archived: string[]; count: number; }>>

sessionHandoff()

Get handoff data for the most recent ended session. T4915, T5123 Signature
(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
(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
(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
(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
(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
(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
(protocolType: string, params?: { taskId?: string; variant?: string; }, projectRoot?: string) => EngineResult<ContextInjectionData>

listRcsdEpics()

List all epic IDs that have RCASD pipeline data. Signature
(projectRoot?: string) => Promise<string[]>

lifecycleStatus()

lifecycle.check / lifecycle.status - Get lifecycle status for epic. T4785 Signature
(epicId: string, projectRoot?: string) => Promise<EngineResult>

lifecycleHistory()

lifecycle.history - Stage transition history. T4785 Signature
(taskId: string, projectRoot?: string) => Promise<EngineResult>

lifecycleGates()

lifecycle.gates - Get all gate statuses for an epic. T4785 Signature
(taskId: string, projectRoot?: string) => Promise<EngineResult>

lifecyclePrerequisites()

lifecycle.prerequisites - Get required prior stages for a target stage. T4785 Signature
(targetStage: string, _projectRoot?: string) => Promise<EngineResult>

lifecycleCheck()

lifecycle.check - Check if a stage’s prerequisites are met. T4785 Signature
(epicId: string, targetStage: string, projectRoot?: string) => Promise<EngineResult>

lifecycleProgress()

lifecycle.progress / lifecycle.record - Record stage completion. T4785 Signature
(taskId: string, stage: string, status: string, notes?: string, projectRoot?: string) => Promise<EngineResult>

lifecycleSkip()

lifecycle.skip - Skip a stage with reason. T4785 Signature
(taskId: string, stage: string, reason: string, projectRoot?: string) => Promise<EngineResult>

lifecycleReset()

lifecycle.reset - Reset a stage (emergency). T4785 Signature
(taskId: string, stage: string, reason: string, projectRoot?: string) => Promise<EngineResult>

lifecycleGatePass()

lifecycle.gate.pass - Mark gate as passed. T4785 Signature
(taskId: string, gateName: string, agent?: string, notes?: string, projectRoot?: string) => Promise<EngineResult>

lifecycleGateFail()

lifecycle.gate.fail - Mark gate as failed. T4785 Signature
(taskId: string, gateName: string, reason?: string, projectRoot?: string) => Promise<EngineResult>

createGatewayMeta(gateway, domain, operation, startTime)

Create a fully typed GatewayMeta for domain responses. Signature
(gateway: string, domain: string, operation: string, startTime: number) => GatewayMetaRecord
Parameters
NameTypeDescription
gatewaystringGateway name (e.g., ‘query’, ‘mutate’)
domainstringDomain name (e.g., ‘tasks’, ‘session’)
operationstringOperation name (e.g., ‘show’, ‘list’)
startTimenumberTimestamp 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
(response: Record<string, unknown>, budget?: number) => { response: Record<string, unknown>; enforcement: BudgetEnforcementResult; }
Parameters
NameTypeDescription
responseRecord<stringThe domain response object
budget: numberMaximum 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
(response: Record<string, unknown>, budget?: number) => boolean

ShimCommand

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

command()

Register a subcommand. Returns the new subcommand for chaining.
(nameAndArgs: string, opts?: { isDefault?: boolean; }) => ShimCommand

description()

Set description (chaining).
{ (desc: string): this; (): string; }

description()

Get description (Commander compat).
{ (desc: string): this; (): string; }

description()

{ (desc: string): this; (): string; }

alias()

(name: string) => this

option()

(flags: string, description: string, parseOrDefault?: unknown, defaultVal?: unknown) => this

requiredOption()

(flags: string, description: string) => this

argument()

Add a positional argument after command creation. Commander compat: .argument(‘[name]’, ‘description’)
(spec: string, _description?: string) => this

action()

(fn: (...args: any[]) => Promise<void> | void) => this

allowUnknownOption()

No-op for Commander compatibility. citty handles unknown options gracefully.
(_allow?: boolean) => this

allowExcessArguments()

No-op for Commander compatibility.
(_allow?: boolean) => this

name()

Get the command name. Commander compat method.
() => string

optsWithGlobals()

Return parsed global flags from process.argv. Commander compat: returns parent + own options merged.
() => Record<string, unknown>

opts()

Return parsed options. For shim purposes, same as optsWithGlobals().
() => 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
(ctx: FieldExtractionResolution) => void

getFieldContext()

Get the current field extraction context. Signature
() => FieldExtractionResolution

resolveFieldContext()

Parse global field options from Commander.js parsed opts and resolve via the canonical LAFS SDK resolver (conflict detection, type narrowing). Signature
(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
(resolution: FlagResolution) => void

getFormatContext()

Get the current resolved format. Signature
() => FlagResolution

isJsonFormat()

Check if output should be JSON format. Signature
() => boolean

isHumanFormat()

Check if output should be human-readable format. Signature
() => boolean

isQuiet()

Check if quiet mode is enabled (suppress non-essential output). Signature
() => 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
(opts: Record<string, unknown>, defaults?: { projectDefault?: "json" | "human"; userDefault?: "json" | "human"; }) => FlagResolution
Parameters
NameTypeDescription
optsRecord<stringCommander.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
(envelope: unknown) => LafsShapeViolation
Parameters
NameTypeDescription
envelopeunknownThe 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
(envelope: unknown) => void
Parameters
NameTypeDescription
envelopeunknownThe 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
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
(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
(command: string, data: Record<string, unknown>) => Record<string, unknown>

statusSymbol()

Map task status to a display symbol. Falls back to ’?’ for unknown values. Signature
(status: string) => string

statusColor()

Map task status to a color escape. Signature
(status: string) => string

prioritySymbol()

Map task priority to a display symbol. Signature
(priority: string) => string

priorityColor()

Map task priority to a color escape. Signature
(priority: string) => string

hRule()

Create a horizontal rule with box-drawing characters. Signature
(width?: number) => string

shortDate()

Format a date string as YYYY-MM-DD. Signature
(isoDate: string | null | undefined) => string

renderDoctor()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderStats()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderNext()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderBlockers()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderTree()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderStart()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderStop()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderCurrent()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderSession()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderVersion()

Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderPlan()

Signature
(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
(data: Record<string, unknown>, quiet: boolean) => string

renderShow()

Render a single task in a box format (mirrors bash display_text). Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderList()

Render a list of tasks (mirrors bash list.sh text output). Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderFind()

Render search results. Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderAdd()

Render add result. Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderUpdate()

Render update result. Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderComplete()

Render complete result. Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderDelete()

Render delete result. Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderArchive()

Render archive result. Signature
(data: Record<string, unknown>, quiet: boolean) => string

renderRestore()

Render restore result. Signature
(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
(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
(message: string, code?: number | string, _details?: CliErrorDetails) => void

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

Create metadata for a dispatch response. Signature
(gateway: string, domain: string, operation: string, startTime: number, source?: Source, requestId?: string, sessionId?: string | null) => DispatchResponse["_meta"]
Parameters
NameTypeDescription
gatewaystringGateway name (e.g., ‘query’, ‘mutate’)
domainstringDomain name (e.g., ‘tasks’, ‘session’)
operationstringOperation name (e.g., ‘show’, ‘list’)
startTimenumberTimestamp from Date.now() at start of request
source: SourceWhere the request originated
requestId: stringOptional pre-generated request ID
sessionId: string | nullOptional 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
(middlewares: Middleware[]) => Middleware
Parameters
NameTypeDescription
middlewaresMiddleware[]Array of middleware functions to chain
Returns — A single composed Middleware function Example
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
(gateway: Gateway) => Record<string, string[]>

getGatewayDomains()

Get all accepted domain names for a gateway (canonical only). Signature
(gateway: Gateway) => string[]

resolve()

Resolves a domain + operation to its registered definition. Signature
(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
(def: OperationDef, params?: Record<string, unknown>) => string[]

getByDomain()

Get all operations for a specific canonical domain. Signature
(domain: CanonicalDomain) => OperationDef[]

getByGateway()

Get all operations for a specific gateway. Signature
(gateway: Gateway) => OperationDef[]

getByTier()

Get all operations available at or below a specific tier. Signature
(tier: Tier) => OperationDef[]

getActiveDomains()

Get a list of canonical domains that actually have operations registered. Signature
() => CanonicalDomain[]

getCounts()

Returns summary counts of operations for module validation. Signature
() => { query: number; mutate: number; total: number; }

Dispatcher

Signature
typeof Dispatcher
Methods

dispatch()

(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
(projectRoot: string, options?: { focus?: string; storeToBrain?: boolean; }) => Promise<EngineResult>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
options: { focus?: string; storeToBrain?: boolean; }Optional analysis options
Returns — EngineResult containing the structured codebase map Example
const result = await mapCodebase('/path/to/project', { focus: 'architecture' });

configGet()

Get config value by key (dot-notation supported) Signature
(projectRoot: string, key?: string) => Promise<EngineResult<unknown>>

configSet()

Set a config value by key (dot-notation supported) Signature
(projectRoot: string, key: string, value: unknown) => Promise<EngineResult<{ key: string; value: unknown; }>>

configSetPreset()

Apply a strictness preset to the project config. T067 Signature
(projectRoot: string, preset: string) => Promise<EngineResult<unknown>>

configListPresets()

List all available strictness presets. T067 Signature
() => 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
(event: HookEvent) => Promise<EngineResult<{ event: HookEvent; providers: ProviderHookInfo[]; }>>
Parameters
NameTypeDescription
eventHookEventThe 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
(providerIds?: string[]) => Promise<EngineResult<{ providerIds?: string[]; commonEvents: ProviderHookEvent[]; }>>
Parameters
NameTypeDescription
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
(params?: { providerIds?: string[]; detectProvider?: boolean; }) => Promise<EngineResult<HookMatrixResult>>
Parameters
NameTypeDescription
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
(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
() => boolean

ensureInitialized()

Check initialization status and auto-init if configured Signature
(projectRoot: string) => Promise<EngineResult<{ initialized: boolean; }>>

getVersion()

Get current version (native implementation) Signature
(projectRoot: string) => Promise<EngineResult<{ version: string; }>>

orchestrateStatus()

orchestrate.status - Get orchestrator status T4478 Signature
(epicId?: string, projectRoot?: string) => Promise<EngineResult>

orchestrateAnalyze()

orchestrate.analyze - Dependency analysis T4478 Signature
(epicId?: string, projectRoot?: string, mode?: string) => Promise<EngineResult>

orchestrateReady()

orchestrate.ready - Get parallel-safe tasks (ready to execute) T4478 Signature
(epicId: string, projectRoot?: string) => Promise<EngineResult>

orchestrateNext()

orchestrate.next - Next task to spawn T4478 Signature
(epicId: string, projectRoot?: string) => Promise<EngineResult>

orchestrateWaves()

orchestrate.waves - Compute dependency waves T4478 Signature
(epicId: string, projectRoot?: string) => Promise<EngineResult>

orchestrateContext()

orchestrate.context - Context usage check T4478 Signature
(epicId?: string, projectRoot?: string) => Promise<EngineResult>

orchestrateValidate()

orchestrate.validate - Validate spawn readiness for a task T4478 Signature
(taskId: string, projectRoot?: string) => Promise<EngineResult>

orchestrateSpawnSelectProvider()

orchestrate.spawn.select - Select best provider for spawn based on required capabilities T5236 Signature
(capabilities: Array<"supportsSubagents" | "supportsProgrammaticSpawn" | "supportsInterAgentComms" | "supportsParallelSpawn">, _projectRoot?: string) => Promise<EngineResult>

orchestrateSpawnExecute()

orchestrate.spawn.execute - Execute spawn for a task using adapter registry T5236 Signature
(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
(taskId: string, protocolType?: string, projectRoot?: string, tier?: 0 | 1 | 2) => Promise<EngineResult>

orchestrateStartup()

orchestrate.startup - Initialize orchestration for an epic T4478 Signature
(epicId: string, projectRoot?: string) => Promise<EngineResult>

orchestrateBootstrap()

orchestrate.bootstrap - Load brain state for agent bootstrapping T4478 T4657 Signature
(projectRoot?: string, params?: { speed?: "fast" | "full" | "complete"; }) => Promise<EngineResult<BrainState>>

orchestrateCriticalPath()

orchestrate.critical-path - Find the longest dependency chain T4478 Signature
(projectRoot?: string) => Promise<EngineResult>

orchestrateUnblockOpportunities()

orchestrate.unblock-opportunities - Analyze dependency graph for unblocking opportunities T4478 Signature
(projectRoot?: string) => Promise<EngineResult>

orchestrateParallel()

orchestrate.parallel - Manage parallel execution (start/end) T4632 Signature
(action: "start" | "end", epicId: string, wave?: number, projectRoot?: string) => Promise<EngineResult>

orchestrateParallelStart()

orchestrate.parallel.start - Start parallel execution for a wave T4632 Signature
(epicId: string, wave: number, projectRoot?: string) => Promise<EngineResult>

orchestrateParallelEnd()

orchestrate.parallel.end - End parallel execution for a wave T4632 Signature
(epicId: string, wave: number, projectRoot?: string) => Promise<EngineResult>

orchestrateCheck()

orchestrate.check - Check current orchestration state T4632 Signature
(projectRoot?: string) => Promise<EngineResult>

orchestrateSkillInject()

orchestrate.skill.inject - Read skill content for injection into agent context T4632 Signature
(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
(params: OrchestrateHandoffParams, projectRoot?: string) => Promise<EngineResult>

phaseList()

phase.list - List all project phases Signature
(projectRoot?: string) => Promise<EngineResult>

phaseShow()

phase.show - Show details of a specific phase Signature
(phaseId?: string, projectRoot?: string) => Promise<EngineResult>

phaseSet()

phase.set - Set the current phase Signature
(params: { phaseId: string; rollback?: boolean; force?: boolean; dryRun?: boolean; }, projectRoot?: string) => Promise<EngineResult>

phaseStart()

phase.start - Start a pending phase Signature
(phaseId: string, projectRoot?: string) => Promise<EngineResult>

phaseComplete()

phase.complete - Complete an active phase Signature
(phaseId: string, projectRoot?: string) => Promise<EngineResult>

phaseAdvance()

phase.advance - Advance to the next phase Signature
(force?: boolean, projectRoot?: string) => Promise<EngineResult>

phaseRename()

phase.rename - Rename a phase Signature
(oldName: string, newName: string, projectRoot?: string) => Promise<EngineResult>

phaseDelete()

phase.delete - Delete a phase Signature
(phaseId: string, params?: { reassignTo?: string; force?: boolean; }, projectRoot?: string) => Promise<EngineResult>

releasePrepare()

release.prepare - Prepare a release T4788 Signature
(version: string, tasks?: string[], notes?: string, projectRoot?: string) => Promise<EngineResult>

releaseChangelog()

release.changelog - Generate changelog T4788 Signature
(version: string, projectRoot?: string) => Promise<EngineResult>

releaseList()

release.list - List all releases (query operation via data read) T4788 Signature
(optionsOrProjectRoot?: ReleaseListOptions | string, projectRoot?: string) => Promise<EngineResult>

releaseShow()

release.show - Show release details (query operation via data read) T4788 Signature
(version: string, projectRoot?: string) => Promise<EngineResult>

releaseCommit()

release.commit - Mark release as committed (metadata only) T4788 Signature
(version: string, projectRoot?: string) => Promise<EngineResult>

releaseTag()

release.tag - Mark release as tagged (metadata only) T4788 Signature
(version: string, projectRoot?: string) => Promise<EngineResult>

releaseGatesRun()

release.gates.run - Run release gates (validation checks) T4788 Signature
(version: string, projectRoot?: string) => Promise<EngineResult>

releaseRollback()

release.rollback - Rollback a release T4788 Signature
(version: string, reason?: string, projectRoot?: string) => Promise<EngineResult>

releaseCancel()

release.cancel - Cancel and remove a release in draft or prepared state T5602 Signature
(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
(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
(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
(projectRoot: string, params?: { blockedTasksLimit?: number; }) => Promise<EngineResult<DashboardData>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
params: { blockedTasksLimit?: number; }Optional parameters to control blocked tasks display limit
Returns — EngineResult with comprehensive dashboard data Example
const result = await systemDash('/project', { blockedTasksLimit: 5 });

systemStats()

Detailed statistics: tasks by status/priority/type/phase, completion rate, average cycle time. Signature
(projectRoot: string, params?: { period?: number; }) => Promise<EngineResult<StatsData>>

systemLabels()

List all unique labels across tasks with counts and task IDs per label. Signature
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").LabelsResult>>

systemArchiveStats()

Archive metrics: total archived, by reason, average cycle time, archive rate. Signature
(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
(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
(projectRoot: string, params?: { session?: string; }) => EngineResult<ContextData>

systemSequence()

Read task ID sequence state from canonical SQLite metadata. Supports ‘show’ and ‘check’ actions. T4815 Signature
(projectRoot: string, params?: { action?: "show" | "check"; }) => Promise<EngineResult<SequenceData | Record<string, unknown>>>

systemInjectGenerate()

Generate Minimum Viable Injection (MVI). Signature
(projectRoot?: string) => Promise<EngineResult<import("@cleocode/core/internal").InjectGenerateResult>>

systemMetrics()

System metrics: token usage, compliance summary, session counts. T4631 Signature
(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
(projectRoot: string, params?: { detailed?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").HealthResult>>

systemDiagnostics()

System diagnostics: extended health checks with fix suggestions. T4631 Signature
(projectRoot: string, params?: { checks?: string[]; }) => Promise<EngineResult<import("@cleocode/core/internal").DiagnosticsResult>>

systemHelp()

Return help text for the system. T4631 Signature
(_projectRoot: string, params?: { topic?: string; }) => EngineResult<HelpData>

systemRoadmap()

Generate roadmap from pending epics and optional CHANGELOG history. T4631 Signature
(projectRoot: string, params?: { includeHistory?: boolean; upcomingOnly?: boolean; }) => Promise<EngineResult>

systemCompliance()

System compliance report from COMPLIANCE.jsonl. T4631 Signature
(projectRoot: string, params?: { subcommand?: string; days?: number; epic?: string; }) => EngineResult<ComplianceData>

systemBackup()

Create a backup of CLEO data files. T4631 Signature
(projectRoot: string, params?: { type?: string; note?: string; }) => EngineResult<import("@cleocode/core/internal").BackupResult>

systemListBackups()

List available system backups (read-only). T4783 Signature
(projectRoot: string) => EngineResult<import("@cleocode/core/internal").BackupEntry[]>

systemRestore()

Restore from a backup. T4631 Signature
(projectRoot: string, params: { backupId: string; force?: boolean; }) => EngineResult<import("@cleocode/core/internal").RestoreResult>

backupRestore()

Restore an individual file from backup. T5329 Signature
(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
(projectRoot: string, params?: { target?: string; dryRun?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").MigrateResult>>

systemCleanup()

Cleanup stale data (sessions, backups, logs). T4631 Signature
(projectRoot: string, params: { target: string; olderThan?: string; dryRun?: boolean; }) => Promise<EngineResult<import("@cleocode/core/internal").CleanupResult>>

systemAudit()

Audit data integrity. T4631 Signature
(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
(_projectRoot: string, params?: { direction?: string; }) => EngineResult<SyncData>

systemSafestop()

Safe stop: signal clean shutdown for agents. T4631 Signature
(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
(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
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").DoctorReport>>

systemFix()

Run auto-fix for failed doctor checks. T4795 Signature
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").FixResult[]>>

systemRuntime()

Runtime/channel diagnostics for CLI installation mode checks. T4815 Signature
(_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
(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
() => Promise<EngineResult<ScaffoldHubData>>

systemSequenceRepair()

Repair task ID sequence using canonical core implementation. T4815 Signature
(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
() => Promise<EngineResult<SmokeResult>>

parseIssueTemplates(projectRoot)

Parse all templates from the repo’s .github/ISSUE_TEMPLATE/ directory. Signature
(projectRoot: string) => EngineResult<import("@cleocode/core/internal").TemplateConfig>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
Returns — EngineResult containing the parsed template configuration Example
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
(projectRoot: string, subcommand: string) => EngineResult<import("@cleocode/core/internal").IssueTemplate>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
subcommandstringTemplate subcommand identifier (e.g. “bug”, “feature”)
Returns — EngineResult containing the matched issue template Example
const result = getTemplateForSubcommand('/path/to/project', 'bug');

generateTemplateConfig(projectRoot)

Generate and cache the config as .cleo/issue-templates.json. Signature
(projectRoot: string) => Promise<EngineResult<import("@cleocode/core/internal").TemplateConfig>>
Parameters
NameTypeDescription
projectRootstringAbsolute path to the project root
Returns — EngineResult containing the generated template configuration Example
const result = await generateTemplateConfig('/path/to/project');

validateLabels(labels, repoLabels)

Validate that labels exist on a GitHub repo. Signature
(labels: string[], repoLabels: string[]) => EngineResult<{ existing: string[]; missing: string[]; }>
Parameters
NameTypeDescription
labelsstring[]Labels required by the template
repoLabelsstring[]Labels that exist on the GitHub repo
Returns — EngineResult with existing and missing label lists Example
const result = validateLabels(['bug', 'enhancement'], repoLabels);

validateSchemaOp()

validate.schema - JSON Schema validation T4477 Signature
(type: string, data?: unknown, projectRoot?: string) => EngineResult

validateTask()

validate.task - Anti-hallucination task validation T4477 Signature
(taskId: string, projectRoot?: string) => Promise<EngineResult>

validateProtocol()

validate.protocol - Protocol compliance check T4477 Signature
(taskId: string, protocolType?: string, projectRoot?: string) => Promise<EngineResult>

validateManifest()

validate.manifest - Manifest entry validation T4477 Signature
(projectRoot?: string) => EngineResult

validateOutput()

validate.output - Output file validation T4477 Signature
(filePath: string, taskId?: string, projectRoot?: string) => EngineResult

validateComplianceSummary()

validate.compliance.summary - Aggregated compliance metrics T4477 Signature
(projectRoot?: string) => EngineResult

validateComplianceViolations()

validate.compliance.violations - List compliance violations T4477 Signature
(limit?: number, projectRoot?: string) => EngineResult

validateComplianceRecord()

validate.compliance.record - Record compliance check result T4477 Signature
(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
(projectRoot?: string) => EngineResult

validateCoherenceCheck()

validate.coherence-check - Cross-validate task graph for consistency T4477 Signature
(projectRoot?: string) => Promise<EngineResult<{ coherent: boolean; issues: CoherenceIssue[]; }>>

validateTestRun()

validate.test.run - Execute test suite via subprocess T4632 Signature
(params?: { scope?: string; pattern?: string; parallel?: boolean; }, projectRoot?: string) => EngineResult

validateBatchValidate()

validate.batch-validate - Batch validate all tasks against schema and rules T4632 Signature
(projectRoot?: string) => Promise<EngineResult>

validateTestCoverage()

validate.test.coverage - Coverage metrics T4477 Signature
(projectRoot?: string) => EngineResult

validateProtocolConsensus()

check.protocol.consensus - Validate consensus protocol compliance T5327 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolContribution()

check.protocol.contribution - Validate contribution protocol compliance T5327 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolDecomposition()

check.protocol.decomposition - Validate decomposition protocol compliance T5327 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolImplementation()

check.protocol.implementation - Validate implementation protocol compliance T5327 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolSpecification()

check.protocol.specification - Validate specification protocol compliance T5327 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolResearch()

check.protocol.research - Validate research protocol compliance T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolArchitectureDecision()

check.protocol.architecture-decision - Validate ADR protocol compliance T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolValidation()

check.protocol.validation - Validate validation-stage protocol compliance T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolTesting()

check.protocol.testing - Validate testing-stage protocol compliance (IVT loop) T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolRelease()

check.protocol.release - Validate release protocol compliance T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolArtifactPublish()

check.protocol.artifact-publish - Validate artifact-publish protocol compliance T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateProtocolProvenance()

check.protocol.provenance - Validate provenance protocol compliance T260 Signature
(params: ProtocolValidationParams, _projectRoot?: string) => Promise<EngineResult>

validateGateVerify()

check.gate.verify - View or modify verification gates for a task T5327 Signature
(params: GateVerifyParams, projectRoot?: string) => Promise<EngineResult<GateVerifyResult>>

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

Build metadata for a dispatch domain response. Signature
(gateway: string, domain: string, operation: string, startTime: number, source?: Source) => DispatchResponse["_meta"]
Parameters
NameTypeDescription
gatewaystringGateway name (e.g., ‘query’, ‘mutate’)
domainstringDomain name (e.g., ‘tasks’, ‘session’)
operationstringOperation name (e.g., ‘show’, ‘list’)
startTimenumberTimestamp from Date.now() at start of request
source: SourceWhere 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
(result: EngineResult, gateway: string, domain: string, operation: string, startTime: number) => DispatchResponse

errorResult()

Return a standard error response. Signature
(gateway: string, domain: string, operation: string, code: string, message: string, startTime: number) => DispatchResponse

unsupportedOp()

Return a standard “unsupported operation” error response. Signature
(gateway: string, domain: string, operation: string, startTime: number) => DispatchResponse

getListParams()

Extract limit and offset pagination params from a params dict. Signature
(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
(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
<T>(params: Record<string, unknown> | undefined, paramName: string, routes: Record<string, () => T>, defaultRoute?: string) => T

BackgroundJobManager

Manages background jobs for long-running operations Signature
typeof BackgroundJobManager
Methods

startJob()

Start a new background job
(operation: string, executor: () => Promise<unknown>) => Promise<string>

getJob()

Get a specific job by ID
(jobId: string) => BackgroundJob | undefined

listJobs()

List all jobs, optionally filtered by status
(status?: string) => BackgroundJob[]

cancelJob()

Cancel a running job
(jobId: string) => boolean

updateProgress()

Update job progress (0-100)
(jobId: string, progress: number) => boolean

cleanup()

Cleanup old completed/failed/cancelled jobs past retention period
() => number

destroy()

Destroy the manager: cancel all running jobs and clear state
() => void

executeJob()

Execute a job’s executor function and update status on completion/failure
(jobId: string, executor: () => Promise<unknown>, signal: AbortSignal) => Promise<void>

setJobManager()

Signature
(manager: BackgroundJobManager) => void

getJobManager()

Signature
() => BackgroundJobManager | null

AdminHandler

Signature
typeof AdminHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

CheckHandler

Signature
typeof CheckHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

ConduitHandler

Conduit dispatch handler for agent messaging operations. Signature
typeof ConduitHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

resolveCredential()

Resolve agent credential from the registry.
(agentId?: string) => Promise<import("/mnt/projects/cleocode/packages/contracts/dist/agent-registry").AgentCredential>

getStatus()

Get connection status and unread count.
(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.
(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.
(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.
() => { success: boolean; data: { message: string; agentId?: undefined; }; } | { success: boolean; data: { agentId: string | null; message: string; }; }

sendMessage()

Send a message to an agent or conversation.
(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
typeof MemoryHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

nexusStatus()

Get nexus status (initialized, project count, last updated). Signature
() => Promise<EngineResult<{ initialized: boolean; projectCount: number; lastUpdated: string | null; }>>

nexusListProjects()

List all registered projects. Signature
(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
(name: string) => Promise<EngineResult<Awaited<ReturnType<typeof nexusGetProject>>>>

nexusResolve()

Resolve a cross-project task query. Signature
(query: string, currentProject?: string) => Promise<EngineResult<Awaited<ReturnType<typeof resolveTask>>>>

nexusDepsQuery()

Get cross-project dependencies for a task query. Signature
(query: string, direction?: "forward" | "reverse") => Promise<EngineResult<Awaited<ReturnType<typeof nexusDeps>>>>

nexusGraph()

Build the global dependency graph. Signature
() => Promise<EngineResult<Awaited<ReturnType<typeof buildGlobalGraph>>>>

nexusCriticalPath()

Get the critical path across projects. Signature
() => Promise<EngineResult<Awaited<ReturnType<typeof criticalPath>>>>

nexusBlockers()

Analyze blockers for a task query. Signature
(query: string) => Promise<EngineResult<Awaited<ReturnType<typeof blockingAnalysis>>>>

nexusOrphans()

List orphaned cross-project tasks. Signature
(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
(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
(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
() => Promise<EngineResult<{ message: string; }>>

nexusRegisterProject()

Register a project in the nexus. Signature
(path: string, name?: string, permission?: NexusPermissionLevel) => Promise<EngineResult<{ hash: string; message: string; }>>

nexusUnregisterProject()

Unregister a project from the nexus. Signature
(name: string) => Promise<EngineResult<{ message: string; }>>

nexusSyncProject()

Sync a specific project or all projects. Signature
(name?: string) => Promise<EngineResult<unknown>>

nexusSetPermission()

Set permission level for a project. Signature
(name: string, level: NexusPermissionLevel) => Promise<EngineResult<{ message: string; }>>

nexusReconcileProject()

Reconcile the nexus registry with the filesystem. Signature
(projectRoot: string) => Promise<EngineResult<Awaited<ReturnType<typeof nexusReconcile>>>>

nexusShareStatus()

Get sharing status for a project. Signature
(projectRoot: string) => Promise<EngineResult<Awaited<ReturnType<typeof getSharingStatus>>>>

nexusShareSnapshotExport()

Export a snapshot of the project’s tasks. Signature
(projectRoot: string, outputPath?: string) => Promise<EngineResult<{ path: string; taskCount: number; checksum: string; }>>

nexusShareSnapshotImport()

Import a snapshot into the project. Signature
(projectRoot: string, inputPath: string) => Promise<EngineResult<Awaited<ReturnType<typeof importSnapshot>>>>

nexusTransferPreview()

Preview a cross-project task transfer (dry run). Signature
(params: TransferParams) => Promise<EngineResult<TransferResult>>

nexusTransferExecute()

Execute a cross-project task transfer. Signature
(params: TransferParams) => Promise<EngineResult<TransferResult>>

NexusHandler

Signature
typeof NexusHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

OrchestrateHandler

Signature
typeof OrchestrateHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

PipelineHandler

Signature
typeof PipelineHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

queryStage()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateStage()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

queryRelease()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateRelease()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

queryManifest()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

queryPhase()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateManifest()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutatePhase()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

queryChain()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateChain()

(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
(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
() => SessionContext | null

hasSession()

Check whether a session is currently bound. Signature
() => boolean

unbindSession()

Unbind the current session context. Called by session.end mutation handler. Signature
() => SessionContext | null
Returns — The unbound context, or null if nothing was bound.

resetSessionContext()

Reset the session context (for testing only). Signature
() => void

SessionHandler

Signature
typeof SessionHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

stickyAdd(projectRoot, params)

Create a new sticky note. Signature
(projectRoot: string, params: CreateStickyParams) => Promise<EngineResult<StickyNote>>
Parameters
NameTypeDescription
projectRootstringProject root path
paramsCreateStickyParamsCreation parameters
Returns — EngineResult with created sticky note

stickyList(projectRoot, params)

List sticky notes with optional filtering. Signature
(projectRoot: string, params?: ListStickiesParams) => Promise<EngineResult<{ stickies: StickyNote[]; total: number; }>>
Parameters
NameTypeDescription
projectRootstringProject root path
params: ListStickiesParamsFilter parameters
Returns — EngineResult with array of sticky notes

stickyShow(projectRoot, id)

Get a single sticky note by ID. Signature
(projectRoot: string, id: string) => Promise<EngineResult<StickyNote | null>>
Parameters
NameTypeDescription
projectRootstringProject root path
idstringSticky note ID
Returns — EngineResult with sticky note or null

stickyConvertToTask(projectRoot, stickyId, title)

Convert a sticky note to a task. Signature
(projectRoot: string, stickyId: string, title?: string) => Promise<EngineResult<{ taskId: string; }>>
Parameters
NameTypeDescription
projectRootstringProject root path
stickyIdstringSticky note ID
title: stringOptional task title
Returns — EngineResult with new task ID

stickyConvertToMemory(projectRoot, stickyId, memoryType)

Convert a sticky note to a memory observation. Signature
(projectRoot: string, stickyId: string, memoryType?: string) => Promise<EngineResult<{ memoryId: string; }>>
Parameters
NameTypeDescription
projectRootstringProject root path
stickyIdstringSticky note ID
memoryType: stringOptional memory type
Returns — EngineResult with new memory entry ID

stickyArchive(projectRoot, id)

Archive a sticky note. Signature
(projectRoot: string, id: string) => Promise<EngineResult<StickyNote>>
Parameters
NameTypeDescription
projectRootstringProject root path
idstringSticky note ID
Returns — EngineResult with archived sticky note

stickyConvertToTaskNote(projectRoot, stickyId, taskId)

Convert a sticky note to a task note. Signature
(projectRoot: string, stickyId: string, taskId: string) => Promise<EngineResult<{ taskId: string; }>>
Parameters
NameTypeDescription
projectRootstringProject root path
stickyIdstringSticky note ID
taskIdstringTarget task ID
Returns — EngineResult with updated task ID

stickyConvertToSessionNote(projectRoot, stickyId, sessionId)

Convert a sticky note to a session note. Signature
(projectRoot: string, stickyId: string, sessionId?: string) => Promise<EngineResult<{ sessionId: string; }>>
Parameters
NameTypeDescription
projectRootstringProject root path
stickyIdstringSticky note ID
sessionId: stringOptional target session ID
Returns — EngineResult with session ID

stickyPurge(projectRoot, id)

Purge (permanently delete) a sticky note. Signature
(projectRoot: string, id: string) => Promise<EngineResult<StickyNote>>
Parameters
NameTypeDescription
projectRootstringProject root path
idstringSticky note ID
Returns — EngineResult with purged sticky note

StickyHandler

Signature
typeof StickyHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

TasksHandler

Signature
typeof TasksHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

codeOutline()

code.outline — file structural skeleton. Signature
(params?: Record<string, unknown>) => Promise<EngineResult>

codeSearch()

code.search — cross-codebase symbol search. Signature
(params?: Record<string, unknown>) => Promise<EngineResult>

codeUnfold()

code.unfold — single symbol extraction. Signature
(params?: Record<string, unknown>) => Promise<EngineResult>

codeParse()

code.parse — raw AST parse for a single file. Signature
(params?: Record<string, unknown>) => Promise<EngineResult>

toolsIssueDiagnostics()

Collect issue diagnostics. Signature
() => EngineResult<ReturnType<typeof collectDiagnostics>>

toolsSkillList()

List all discovered skills. Signature
(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
(name: string) => Promise<EngineResult<{ skill: Awaited<ReturnType<typeof discoverSkill>>; }>>

toolsSkillFind()

Find skills matching a query string. Signature
(query?: string) => Promise<EngineResult<{ skills: Awaited<ReturnType<typeof discoverSkills>>; count: number; query: string; }>>

toolsSkillDispatch()

Get dispatch matrix entries for a skill. Signature
(name: string) => EngineResult<{ skill: string; dispatch: { byTaskType: string[]; byKeyword: string[]; byProtocol: string[]; }; }>

toolsSkillVerify()

Verify a skill’s installation and catalog status. Signature
(name: string) => Promise<EngineResult<{ skill: string; installed: boolean; inCatalog: boolean; installPath: string | null; }>>

toolsSkillDependencies()

Get dependency tree for a skill. Signature
(name: string) => EngineResult<{ skill: string; direct: ReturnType<typeof catalog.getSkillDependencies>; tree: ReturnType<typeof catalog.resolveDependencyTree>; }>

toolsSkillSpawnProviders()

Get spawn-capable providers by capability. Signature
(capability?: "supportsSubagents" | "supportsProgrammaticSpawn" | "supportsInterAgentComms" | "supportsParallelSpawn") => Promise<EngineResult<{ providers: unknown[]; capability: string; count: number; }>>

toolsSkillCatalogInfo()

Get catalog info (protocols, profiles, resources, or summary). Signature
() => EngineResult<{ available: boolean; version: string | null; libraryRoot: string | null; skillCount: number; protocolCount: number; profileCount: number; }>

toolsSkillCatalogProtocols()

List catalog protocols. Signature
(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
(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
(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
() => Promise<EngineResult<{ precedenceMap: unknown; }>>

toolsSkillPrecedenceResolve()

Resolve skill paths for a specific provider. Signature
(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
(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
(name: string, projectRoot: string, isGlobal?: boolean) => Promise<EngineResult<{ removed: string[]; errors: string[]; }>>

toolsSkillRefresh()

Refresh all tracked skills that have updates available. Signature
(projectRoot: string) => Promise<EngineResult<{ updated: string[]; failed: Array<{ name: string; error: string; }>; checked: number; }>>

toolsProviderList()

List all registered providers. Signature
(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
() => EngineResult<{ providers: ReturnType<typeof detectAllProviders>; count: number; }>

toolsProviderInjectStatus()

Check injection status for all installed providers. Signature
(projectRoot: string, scope?: "project" | "global", content?: string) => Promise<EngineResult<{ checks: unknown[]; count: number; }>>

toolsProviderSupports()

Check if a provider supports a specific capability. Signature
(providerId: string, capability: string) => Promise<EngineResult<{ providerId: string; capability: string; supported: boolean; }>>

toolsProviderHooks()

Query hook providers for a specific event. Signature
(event: string) => Promise<EngineResult<unknown>>

toolsProviderInject()

Inject CLEO directives into all installed provider instruction files. Signature
(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
(projectRoot: string) => EngineResult<{ adapters: ReturnType<AdapterManager["listAdapters"]>; count: number; }>

toolsAdapterShow()

Show a single adapter by ID. Signature
(projectRoot: string, id: string) => EngineResult<{ manifest: unknown; initialized: boolean; active: boolean; }>

toolsAdapterDetect()

Detect active adapters. Signature
(projectRoot: string) => EngineResult<{ detected: string[]; count: number; }>

toolsAdapterHealth()

Get adapter health status. Signature
(projectRoot: string, id?: string) => EngineResult<{ adapters: ReturnType<AdapterManager["listAdapters"]>; count: number; }>

toolsAdapterActivate()

Activate an adapter by ID. Signature
(projectRoot: string, id: string) => Promise<EngineResult<{ id: string; name: string; version: string; active: boolean; }>>

toolsAdapterDispose()

Dispose one or all adapters. Signature
(projectRoot: string, id?: string) => Promise<EngineResult<{ disposed: string; }>>

ToolsHandler

Signature
typeof ToolsHandler
Methods

query()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

mutate()

(operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

getSupportedOperations()

() => { query: string[]; mutate: string[]; }

queryIssue()

(sub: string, _params: Record<string, unknown> | undefined, startTime: number) => DispatchResponse

mutateIssue()

(sub: string, _params: Record<string, unknown> | undefined, startTime: number) => DispatchResponse

querySkill()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateSkill()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

queryProvider()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateProvider()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

queryAdapter()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => DispatchResponse

queryCode()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

mutateAdapter()

(sub: string, params: Record<string, unknown> | undefined, startTime: number) => Promise<DispatchResponse>

handleError()

(gateway: string, domain: string, operation: string, error: unknown, startTime: number) => DispatchResponse

createDomainHandlers()

Create a Map of all canonical domain handlers. Signature
() => Map<string, DomainHandler>

RateLimiter

Sliding-window rate limiter for the dispatch pipeline. Signature
typeof RateLimiter
Methods

check()

(req: DispatchRequest) => RateLimitMeta & { allowed: boolean; }

resolveCategory()

(gateway: string, domain: string, operation: string) => "query" | "mutate" | "spawn"

getLimitConfig()

(category: "query" | "mutate" | "spawn") => RateLimitConfig

createRateLimiter(config)

Creates a rate limiting middleware for the dispatch pipeline. Signature
(config?: Partial<RateLimitingConfig>) => Middleware
Parameters
NameTypeDescription
config: Partial<RateLimitingConfig>Optional partial config to override defaults
Returns — Middleware function that enforces rate limits Example
import { createRateLimiter } from './rate-limiter.js';

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

ConfigValidationError

Configuration validation error Signature
typeof ConfigValidationError

validateConfig()

Validate complete configuration Signature
(config: DispatchConfig) => void

loadConfig()

Load configuration from all sources Priority order: 1. Environment variables (CLEO_*) 2. Config file (.cleo/config.json) 3. Defaults Signature
(projectRoot?: string) => DispatchConfig

getConfig()

Get global configuration (singleton) Signature
() => DispatchConfig

resetConfig()

Reset global configuration (for testing) Signature
() => void

createAudit()

Creates an audit middleware that logs all mutate operations (and query operations during grade sessions) to Pino + SQLite. Signature
() => 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
() => 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
(getProjectRoot?: () => string) => Middleware
Parameters
NameTypeDescription
getProjectRoot: (Optional function to resolve the current project root for path sanitization
Returns — Middleware function that sanitizes request params Example
import { createSanitizer } from './sanitizer.js';

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

createSessionResolver(cliSessionLookup)

Creates the session resolver middleware. Signature
(cliSessionLookup?: () => Promise<string | null>) => Middleware
Parameters
NameTypeDescription
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
() => 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
() => Dispatcher

resetCliDispatcher()

Reset the singleton dispatcher (for testing). Signature
() => 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
(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
(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
(gateway: Gateway, domain: string, operation: string, params?: Record<string, unknown>) => Promise<DispatchResponse>

registerAddCommand()

Register the add command. T4460 Signature
(program: Command) => void

registerAdminCommand()

Register the admin command group. Signature
(program: Command) => void

registerAdrCommand()

Signature
(program: Command) => void

registerAgentCommand()

Register the cleo agent command group. Signature
(program: Command) => void

registerAgentsCommand()

Register agents as an alias that prints deprecation notice. Health monitoring is now under cleo agent health. Signature
(_program: Command) => void

registerAnalyzeCommand()

Register the analyze command. T4538 Signature
(program: Command) => void

registerArchiveCommand()

Register the archive command. T4461 Signature
(program: Command) => void

registerArchiveStatsCommand()

Register the archive-stats command. Routes through dispatch layer to admin.archive.stats. T4555 Signature
(program: Command) => void

registerBackfillCommand(program)

Register the cleo backfill CLI command. Signature
(program: Command) => void
Parameters
NameTypeDescription
programCommandThe root CLI command to attach to
Example
registerBackfillCommand(rootCommand);
// Adds: cleo backfill [--dry-run] [--rollback] [--embeddings]

registerBackupCommand()

Signature
(program: Command) => void

registerBlockersCommand()

Signature
(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
(program: Command) => void
Parameters
NameTypeDescription
programCommandThe root CLI command to attach to
Example
registerBrainCommand(rootCommand);
// Adds: cleo brain maintenance [--skip-decay] [--skip-consolidation] [--skip-embeddings] [--json]

registerBriefingCommand()

Register the briefing command. T4916 Signature
(program: Command) => void

registerBugCommand()

Register the bug command. T4913 Signature
(program: Command) => void

registerCantCommand()

Signature
(program: Command) => void

registerCheckCommand()

Register the check command group. Signature
(program: Command) => void

registerCheckpointCommand()

Register the checkpoint command. Delegates to src/store/git-checkpoint.ts for isolated .cleo/.git operations. T4551 T4872 Signature
(program: Command) => void

registerCommandsCommand()

Register the commands command. T4551, T5671 Signature
(program: Command) => void

registerCompleteCommand()

Register the complete command. T4461 Signature
(program: Command) => void

registerComplianceCommand()

Signature
(program: Command) => void

registerConfigCommand()

Signature
(program: Command) => void

registerConsensusCommand()

Register the consensus command group. T4537 Signature
(program: Command) => void

registerContextCommand()

Signature
(program: Command) => void

registerContributionCommand()

Register the contribution command group. T4537 Signature
(program: Command) => void

registerCurrentCommand()

Register the current command. T4756 T4666 Signature
(program: Command) => void

registerDashCommand()

Register the dash command. T4535 Signature
(program: Command) => void

registerDecompositionCommand()

Register the decomposition command group. T4537 Signature
(program: Command) => void

registerDeleteCommand()

Register the delete command. T4461 Signature
(program: Command) => void

registerDepsCommand(program)

Register the deps command group and its subcommands. Signature
(program: Command) => void
Parameters
NameTypeDescription
programCommandRoot CLI program instance.

registerTreeCommand(program)

Register the tree command. Signature
(program: Command) => void
Parameters
NameTypeDescription
programCommandRoot CLI program instance.

registerDetectCommand()

Signature
(program: Command) => void

registerDetectDriftCommand()

Signature
(program: Command) => void

registerDocsCommand()

Register the docs command. T4551 Signature
(program: Command) => void

ProgressTracker

Simple progress tracker for CLI operations. Signature
typeof ProgressTracker
Methods

start()

Start the progress tracker.
() => void

step()

Update to a specific step.
(index: number, message?: string) => void

next()

Move to next step.
(message?: string) => void

complete()

Mark as complete with optional summary.
(summary?: string) => void

error()

Report an error.
(message: string) => void

Spinner

Simple spinner for indeterminate progress. Signature
typeof Spinner
Methods

start()

Start the spinner.
() => void

stop()

Stop the spinner.
(finalMessage?: string) => void

update()

Update the spinner message.
(message: string) => void

createSelfUpdateProgress()

Create a progress tracker for self-update operations. Signature
(enabled: boolean) => ProgressTracker

createDoctorProgress()

Create a progress tracker for doctor operations. Signature
(enabled: boolean) => ProgressTracker

createUpgradeProgress()

Create a progress tracker for upgrade operations. Signature
(enabled: boolean) => ProgressTracker

registerDoctorCommand()

Signature
(program: Command) => void

registerEnvCommand()

Register the env command group. T4581 Signature
(program: Command) => void

registerExistsCommand(program)

Register the exists command. Signature
(program: Command) => void
Parameters
NameTypeDescription
programCommandRoot CLI program instance.
Example
registerExistsCommand(rootCommand);
// cleo exists T001 → exit 0 if found, exit 4 if not

registerExportCommand()

Signature
(program: Command) => void

registerExportTasksCommand()

Signature
(program: Command) => void

registerFindCommand()

Register the find command. T4460 T4668 Signature
(program: Command) => void

registerGenerateChangelogCommand()

Register the generate-changelog command. T4555 Signature
(program: Command) => void

registerGradeCommand()

Signature
(program: Command) => void

registerHistoryCommand()

Signature
(program: Command) => void

registerImplementationCommand()

Register the implementation command group. T4537 Signature
(program: Command) => void

registerImportCommand()

Signature
(program: Command) => void

registerImportTasksCommand()

Signature
(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
() => string

registerInitCommand()

Register the init command. T4681 T4663 Signature
(program: Command) => void

registerInjectCommand()

Signature
(program: Command) => void

registerIssueCommand()

Register the issue command with all subcommands. T4555 Signature
(program: Command) => void

registerLabelsCommand()

Register the labels command group. T4538 Signature
(program: Command) => void

registerLifecycleCommand()

Signature
(program: Command) => void

registerListCommand()

Register the list command. T4460 T4668 Signature
(program: Command) => void

registerLogCommand()

Register the log command. T4538 Signature
(program: Command) => void

registerMapCommand()

Register the map command. Signature
(program: Command) => void

registerMemoryBrainCommand()

Signature
(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
(program: Command) => void

registerNextCommand()

Signature
(program: Command) => void

registerNexusCommand()

Register the nexus command group. T4554 Signature
(program: Command) => void

registerObserveCommand()

Signature
(program: Command) => void

registerOpsCommand()

Register the ops command. Signature
(program: Command) => void

registerOrchestrateCommand()

Signature
(program: Command) => void

registerOtelCommand()

Register the otel command group. T4535 Signature
(program: Command) => void

registerPhaseCommand()

Register the phase command group. T4464, T5326 Signature
(program: Command) => void

registerPhasesCommand()

Register the phases command group. T4538, T5326 Signature
(program: Command) => void

registerPlanCommand()

Signature
(program: Command) => void

registerPromoteCommand()

Signature
(program: Command) => void

registerReasonCommand(program)

Register the cleo reason command group and its subcommands. Signature
(program: Command) => void
Parameters
NameTypeDescription
programCommandRoot CLI program instance (commander shim).
Example
registerReasonCommand(rootCommand);
// Adds: cleo reason why|similar|impact|timeline

registerRefreshMemoryCommand()

Signature
(program: Command) => void

registerRelatesCommand()

Register the relates command group. T4538 Signature
(program: Command) => void

registerReleaseCommand()

Signature
(program: Command) => void

registerRemoteCommand()

Register the remote command with add/remove/list/push/pull subcommands. T4884 Signature
(program: Command) => void

registerReorderCommand()

Signature
(program: Command) => void

registerReparentCommand()

Signature
(program: Command) => void

registerResearchCommand()

Signature
(program: Command) => void

registerRestoreCommand()

Signature
(program: Command) => void

registerRoadmapCommand()

Signature
(program: Command) => void

registerSafestopCommand()

Register the safestop command. T4551 Signature
(program: Command) => void

registerSelfUpdateCommand()

Signature
(program: Command) => void

registerSequenceCommand()

Signature
(program: Command) => void

registerSessionCommand()

Register the session command group. T4463 Signature
(program: Command) => void

registerShowCommand()

Register the show command. T4460 T4666 Signature
(program: Command) => void

registerSkillsCommand()

Register the skills command with all subcommands. T4555 Signature
(program: Command) => void

registerSnapshotCommand()

Signature
(program: Command) => void

registerSpecificationCommand()

Register the specification command group. T4537 Signature
(program: Command) => void

registerStartCommand()

Register the start command. T4756 T4666 Signature
(program: Command) => void

registerStatsCommand()

Register the stats command. T4535 Signature
(program: Command) => void

registerStickyCommand()

Register the sticky command group. T5281 Signature
(program: Command) => void

registerStopCommand()

Register the stop command. T4756 T4666 Signature
(program: Command) => void

registerTestingCommand()

Register the testing command. T4551 Signature
(program: Command) => void

registerTokenCommand()

Signature
(program: Command) => void

registerUpdateCommand()

Register the update command. T4461 Signature
(program: Command) => void

registerUpgradeCommand()

Signature
(program: Command) => void

registerValidateCommand()

Signature
(program: Command) => void

registerVerifyCommand()

Signature
(program: Command) => void

registerWebCommand()

Register the web command. T4551 Signature
(program: Command) => void

initCliLogger()

Initialize CLI logger with optional projectHash correlation context. Signature
(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
(_program: Command) => void

renderErrorMarkdown()

Render a CleoError as structured markdown for CLI display. Signature
(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
(strictMode?: boolean) => Middleware
Parameters
NameTypeDescription
strictMode: booleanWhen true, blocks operations that violate protocol rules
Returns — Middleware function that enforces protocol compliance Example
import { createProtocolEnforcement } from './protocol-enforcement.js';

const enforcement = createProtocolEnforcement(true);

createVerificationGates(strictMode)

Creates a middleware that enforces verification gates on task operations. Signature
(strictMode?: boolean) => Middleware
Parameters
NameTypeDescription
strictMode: booleanWhen true, blocks operations that fail verification gates
Returns — Middleware function that enforces verification gates Example
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
(domain: string, operation: string, gateway: Gateway) => JSONSchemaObject
Parameters
NameTypeDescription
domainstringCanonical domain name (e.g. ‘tasks’, ‘session’)
operationstringOperation name (e.g. ‘show’, ‘add’)
gatewayGatewayGateway (‘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
(gateway: Gateway) => Record<string, JSONSchemaObject>
Returns — Record keyed by ”.” → JSONSchemaObject

resolveTier(params, sessionScope)

Resolve tier from request params, defaulting to ‘standard’. Signature
(params?: Record<string, unknown>, sessionScope?: { type: string; epicId?: string; } | null) => MviTier
Parameters
NameTypeDescription
params: Record<stringRequest params that may contain a _mviTier field
sessionScope: { type: string; epicId?: string; } | nullCurrent session scope for auto-tier detection
Returns — The resolved MVI tier Example
import { resolveTier } from './projections.js';

const tier = resolveTier(req.params, currentSession?.scope);

isOperationAllowed()

Check if a domain is allowed at the given tier. Signature
(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
<T>(data: T, config: ProjectionConfig) => T

createProjectionContext()

Create projection context from request params. Signature
(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
() => Middleware