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
Parameters Returns — EngineResult with success=false and properly structured error Example

engineSuccess(data)

Create an engine success result. Signature
Parameters Returns — EngineResult with success=true Example

taskShow(projectRoot, taskId)

Get a single task by ID. Signature
Parameters Returns — EngineResult containing the task record Example

taskList(projectRoot, params)

List tasks with optional filters. Signature
Parameters Returns — EngineResult with task array, total count, and filtered count Example

taskFind(projectRoot, query, limit, options)

Fuzzy search tasks by title/description/ID. Signature
Parameters Returns — EngineResult with matching tasks and total count Example

taskExists(projectRoot, taskId)

Check if a task exists. Signature
Parameters Returns — EngineResult with exists flag and the queried taskId Example

taskCreate(projectRoot, params)

Create a new task. Signature
Parameters Returns — EngineResult with the created task record and duplicate flag Example

taskUpdate(projectRoot, taskId, updates)

Update a task’s fields. Signature
Parameters Returns — EngineResult with the updated task record and list of changes Example

taskComplete(projectRoot, taskId, notes)

Complete a task (set status to done). Signature
Parameters Returns — EngineResult with the completed task, auto-completed parents, and unblocked tasks Example

taskDelete(projectRoot, taskId, force)

Delete a task. Signature
Parameters Returns — EngineResult with the deleted task and optional cascade info Example

taskArchive(projectRoot, taskId, before)

Archive completed tasks. Moves done/cancelled tasks from active task data to archive. Signature
Parameters Returns — EngineResult with count and list of archived task IDs Example

taskNext(projectRoot, params)

Suggest next task to work on based on priority, phase alignment, age, and dependency readiness. Signature
Parameters Returns — EngineResult with scored suggestions and total candidate count Example

taskBlockers(projectRoot, params)

Show blocked tasks and analyze blocking chains. Signature
Parameters Returns — EngineResult with blocked tasks, critical blockers, and summary Example

taskTree(projectRoot, taskId)

Build hierarchy tree. Signature
Parameters Returns — EngineResult with the hierarchical tree data Example

taskDeps(projectRoot, taskId)

Show dependencies for a task - both what it depends on and what depends on it. Signature
Parameters Returns — EngineResult with dependency information in both directions Example

taskRelates(projectRoot, taskId)

Show task relations (existing relates entries). Signature
Parameters Returns — EngineResult with relations array and count Example

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

Add a relation between two tasks. Signature
Parameters Returns — EngineResult confirming the relation was added Example

taskAnalyze(projectRoot, taskId, params)

Analyze a task for description quality, missing fields, and dependency health. Signature
Parameters Returns — EngineResult with recommended task, bottlenecks, tiers, and metrics Example

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
Parameters Returns — Impact prediction report Example

taskRestore(projectRoot, taskId, params)

Restore a cancelled task back to pending. Signature
Parameters Returns — EngineResult with restored task IDs and count Example

taskUnarchive(projectRoot, taskId, params)

Move an archived task back to active task data with status ‘done’ (or specified status). Signature
Parameters Returns — EngineResult with the unarchived task info Example

taskReorder(projectRoot, taskId, position)

Change task position within its sibling group. Signature
Parameters Returns — EngineResult with new position and total siblings Example

taskReparent(projectRoot, taskId, newParentId)

Move task under a different parent. Signature
Parameters Returns — EngineResult with old and new parent information Example

taskPromote(projectRoot, taskId)

Promote a subtask to task or task to root (remove parent). Signature
Parameters Returns — EngineResult with promotion details Example

taskReopen(projectRoot, taskId, params)

Reopen a completed task (set status back to pending). Signature
Parameters Returns — EngineResult with reopen details including previous and new status Example

taskCancel(projectRoot, taskId, reason)

Cancel a task (soft terminal state — reversible via restore). Signature
Parameters Returns — EngineResult with cancellation details Example

taskComplexityEstimate(projectRoot, params)

Deterministic complexity scoring from task metadata. Signature
Parameters Returns — EngineResult with size, score, factors, and structural metrics Example

taskDepends()

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

taskDepsOverview()

Overview of all dependencies across the project. T5157 Signature

taskDepsCycles()

Detect circular dependencies across the project. T5157 Signature

taskStats()

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

taskExport()

Export tasks as JSON or CSV. T4657 T4790 T4654 Signature

taskHistory()

Get task history from the log file. T4657 T4790 T4654 Signature

taskLint()

Lint tasks for common issues. T4657 T4790 T4654 Signature

taskBatchValidate()

Validate multiple tasks at once. T4657 T4790 T4654 Signature

taskImport()

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

taskPlan()

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

taskRelatesFind()

Find related tasks using semantic search or keyword matching. T5672 Signature

taskLabelList()

List all labels used in tasks. T5672 Signature

taskLabelShow()

Show tasks associated with a label. T5672 Signature

taskSyncReconcile()

Reconcile external tasks with CLEO as SSoT. Signature
List external task links by provider or task ID. Signature

taskSyncLinksRemove()

Remove all external task links for a provider. Signature

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

taskUnclaim()

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

sessionStatus(projectRoot)

Get current session status. Signature
Parameters Returns — EngineResult with active session flag, session record, and task work state Example

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
Parameters Returns — EngineResult with sessions array, total, filtered count, and truncation metadata Example

sessionFind(projectRoot, params)

Lightweight session discovery — returns minimal session records. Signature
Parameters Returns — EngineResult with array of minimal session records Example

sessionShow(projectRoot, sessionId)

Show a specific session by ID. Signature
Parameters Returns — EngineResult with the full Session record Example

taskCurrentGet()

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

taskStart()

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

taskStop()

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

taskWorkHistory()

Get task work history from session notes. T5323 Signature

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

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

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

sessionGc()

Garbage collect old sessions. T4782 Signature

sessionSuspend()

Suspend an active session. T4782 Signature

sessionHistory()

List session history with focus changes and completed tasks. T4782 Signature

sessionCleanup()

Remove orphaned sessions and clean up stale data. T4782 Signature

sessionRecordDecision()

Record a decision to the audit trail. T4782 Signature

sessionDecisionLog()

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

sessionContextDrift()

Compute context drift score for the current session. T4782 Signature

sessionRecordAssumption()

Record an assumption made during a session. T4782 Signature

sessionStats()

Compute session statistics, optionally for a specific session. T4782 Signature

sessionSwitch()

Switch to a different session. T4782 Signature

sessionArchive()

Archive old/ended sessions. T4782 Signature

sessionHandoff()

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

sessionComputeHandoff()

Compute and persist handoff data for a session. T4915 Signature

sessionBriefing()

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

sessionComputeDebrief()

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

sessionDebriefShow()

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

sessionChainShow()

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

sessionContextInject()

Inject context protocol content. T5673 Signature

listRcsdEpics()

List all epic IDs that have RCASD pipeline data. Signature

lifecycleStatus()

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

lifecycleHistory()

lifecycle.history - Stage transition history. T4785 Signature

lifecycleGates()

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

lifecyclePrerequisites()

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

lifecycleCheck()

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

lifecycleProgress()

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

lifecycleSkip()

lifecycle.skip - Skip a stage with reason. T4785 Signature

lifecycleReset()

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

lifecycleGatePass()

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

lifecycleGateFail()

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

createGatewayMeta(gateway, domain, operation, startTime)

Create a fully typed GatewayMeta for domain responses. Signature
Parameters 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
Parameters 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

ShimCommand

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

command()

Register a subcommand. Returns the new subcommand for chaining.

description()

Set description (chaining).

description()

Get description (Commander compat).

description()

alias()

option()

requiredOption()

argument()

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

action()

allowUnknownOption()

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

allowExcessArguments()

No-op for Commander compatibility.

name()

Get the command name. Commander compat method.

optsWithGlobals()

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

opts()

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

setFieldContext()

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

getFieldContext()

Get the current field extraction context. Signature

resolveFieldContext()

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

setFormatContext()

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

getFormatContext()

Get the current resolved format. Signature

isJsonFormat()

Check if output should be JSON format. Signature

isHumanFormat()

Check if output should be human-readable format. Signature

isQuiet()

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

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
Parameters 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
Parameters 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
Parameters 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

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

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

statusSymbol()

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

statusColor()

Map task status to a color escape. Signature

prioritySymbol()

Map task priority to a display symbol. Signature

priorityColor()

Map task priority to a color escape. Signature

hRule()

Create a horizontal rule with box-drawing characters. Signature

shortDate()

Format a date string as YYYY-MM-DD. Signature

renderDoctor()

Signature

renderStats()

Signature

renderNext()

Signature

renderBlockers()

Signature

renderTree()

Signature

renderStart()

Signature

renderStop()

Signature

renderCurrent()

Signature

renderSession()

Signature

renderVersion()

Signature

renderPlan()

Signature

renderGeneric()

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

renderShow()

Render a single task in a box format (mirrors bash display_text). Signature

renderList()

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

renderFind()

Render search results. Signature

renderAdd()

Render add result. Signature

renderUpdate()

Render update result. Signature

renderComplete()

Render complete result. Signature

renderDelete()

Render delete result. Signature

renderArchive()

Render archive result. Signature

renderRestore()

Render restore result. Signature

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

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

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

Create metadata for a dispatch response. Signature
Parameters 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
Parameters Returns — A single composed Middleware function Example

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

getGatewayDomains()

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

resolve()

Resolves a domain + operation to its registered definition. Signature

validateRequiredParams()

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

getByDomain()

Get all operations for a specific canonical domain. Signature

getByGateway()

Get all operations for a specific gateway. Signature

getByTier()

Get all operations available at or below a specific tier. Signature

getActiveDomains()

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

getCounts()

Returns summary counts of operations for module validation. Signature

Dispatcher

Signature
Methods

dispatch()

mapCodebase(projectRoot, options)

Analyze a codebase and return structured mapping. When storeToBrain is true, findings are persisted to brain.db. Signature
Parameters Returns — EngineResult containing the structured codebase map Example

configGet()

Get config value by key (dot-notation supported) Signature

configSet()

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

configSetPreset()

Apply a strictness preset to the project config. T067 Signature

configListPresets()

List all available strictness presets. T067 Signature

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
Parameters 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
Parameters 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
Parameters 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

isAutoInitEnabled()

Check if auto-init is enabled via environment variable Signature

ensureInitialized()

Check initialization status and auto-init if configured Signature

getVersion()

Get current version (native implementation) Signature

orchestrateStatus()

orchestrate.status - Get orchestrator status T4478 Signature

orchestrateAnalyze()

orchestrate.analyze - Dependency analysis T4478 Signature

orchestrateReady()

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

orchestrateNext()

orchestrate.next - Next task to spawn T4478 Signature

orchestrateWaves()

orchestrate.waves - Compute dependency waves T4478 Signature

orchestrateContext()

orchestrate.context - Context usage check T4478 Signature

orchestrateValidate()

orchestrate.validate - Validate spawn readiness for a task T4478 Signature

orchestrateSpawnSelectProvider()

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

orchestrateSpawnExecute()

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

orchestrateSpawn()

orchestrate.spawn - Generate spawn prompt for a task T4478 Signature

orchestrateStartup()

orchestrate.startup - Initialize orchestration for an epic T4478 Signature

orchestrateBootstrap()

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

orchestrateCriticalPath()

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

orchestrateUnblockOpportunities()

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

orchestrateParallel()

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

orchestrateParallelStart()

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

orchestrateParallelEnd()

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

orchestrateCheck()

orchestrate.check - Check current orchestration state T4632 Signature

orchestrateSkillInject()

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

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

phaseList()

phase.list - List all project phases Signature

phaseShow()

phase.show - Show details of a specific phase Signature

phaseSet()

phase.set - Set the current phase Signature

phaseStart()

phase.start - Start a pending phase Signature

phaseComplete()

phase.complete - Complete an active phase Signature

phaseAdvance()

phase.advance - Advance to the next phase Signature

phaseRename()

phase.rename - Rename a phase Signature

phaseDelete()

phase.delete - Delete a phase Signature

releasePrepare()

release.prepare - Prepare a release T4788 Signature

releaseChangelog()

release.changelog - Generate changelog T4788 Signature

releaseList()

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

releaseShow()

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

releaseCommit()

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

releaseTag()

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

releaseGatesRun()

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

releaseRollback()

release.rollback - Rollback a release T4788 Signature

releaseCancel()

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

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

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

systemDash(projectRoot, params)

Project dashboard: task counts by status, active session info, current focus, recent completions. Signature
Parameters Returns — EngineResult with comprehensive dashboard data Example

systemStats()

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

systemLabels()

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

systemArchiveStats()

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

systemLog()

Query audit log with optional filters. Reads from SQLite audit_log table. T4837 Signature

systemContext()

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

systemSequence()

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

systemInjectGenerate()

Generate Minimum Viable Injection (MVI). Signature

systemMetrics()

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

systemHealth()

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

systemDiagnostics()

System diagnostics: extended health checks with fix suggestions. T4631 Signature

systemHelp()

Return help text for the system. T4631 Signature

systemRoadmap()

Generate roadmap from pending epics and optional CHANGELOG history. T4631 Signature

systemCompliance()

System compliance report from COMPLIANCE.jsonl. T4631 Signature

systemBackup()

Create a backup of CLEO data files. T4631 Signature

systemListBackups()

List available system backups (read-only). T4783 Signature

systemRestore()

Restore from a backup. T4631 Signature

backupRestore()

Restore an individual file from backup. T5329 Signature

systemMigrate()

Check/run schema migrations. T4631 Signature

systemCleanup()

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

systemAudit()

Audit data integrity. T4631 Signature

systemSync()

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

systemSafestop()

Safe stop: signal clean shutdown for agents. T4631 Signature

systemUncancel()

Uncancel a cancelled task (restore to pending). T4631 Signature

systemDoctor()

Run comprehensive doctor diagnostics. T4795 Signature

systemFix()

Run auto-fix for failed doctor checks. T4795 Signature

systemRuntime()

Runtime/channel diagnostics for CLI installation mode checks. T4815 Signature

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

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

systemSequenceRepair()

Repair task ID sequence using canonical core implementation. T4815 Signature

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

parseIssueTemplates(projectRoot)

Parse all templates from the repo’s .github/ISSUE_TEMPLATE/ directory. Signature
Parameters Returns — EngineResult containing the parsed template configuration Example

getTemplateForSubcommand(projectRoot, subcommand)

Get template config for a specific subcommand (bug/feature/help). Signature
Parameters Returns — EngineResult containing the matched issue template Example

generateTemplateConfig(projectRoot)

Generate and cache the config as .cleo/issue-templates.json. Signature
Parameters Returns — EngineResult containing the generated template configuration Example

validateLabels(labels, repoLabels)

Validate that labels exist on a GitHub repo. Signature
Parameters Returns — EngineResult with existing and missing label lists Example

validateSchemaOp()

validate.schema - JSON Schema validation T4477 Signature

validateTask()

validate.task - Anti-hallucination task validation T4477 Signature

validateProtocol()

validate.protocol - Protocol compliance check T4477 Signature

validateManifest()

validate.manifest - Manifest entry validation T4477 Signature

validateOutput()

validate.output - Output file validation T4477 Signature

validateComplianceSummary()

validate.compliance.summary - Aggregated compliance metrics T4477 Signature

validateComplianceViolations()

validate.compliance.violations - List compliance violations T4477 Signature

validateComplianceRecord()

validate.compliance.record - Record compliance check result T4477 Signature

validateTestStatus()

validate.test.status - Test suite status T4477 Signature

validateCoherenceCheck()

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

validateTestRun()

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

validateBatchValidate()

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

validateTestCoverage()

validate.test.coverage - Coverage metrics T4477 Signature

validateProtocolConsensus()

check.protocol.consensus - Validate consensus protocol compliance T5327 Signature

validateProtocolContribution()

check.protocol.contribution - Validate contribution protocol compliance T5327 Signature

validateProtocolDecomposition()

check.protocol.decomposition - Validate decomposition protocol compliance T5327 Signature

validateProtocolImplementation()

check.protocol.implementation - Validate implementation protocol compliance T5327 Signature

validateProtocolSpecification()

check.protocol.specification - Validate specification protocol compliance T5327 Signature

validateProtocolResearch()

check.protocol.research - Validate research protocol compliance T260 Signature

validateProtocolArchitectureDecision()

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

validateProtocolValidation()

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

validateProtocolTesting()

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

validateProtocolRelease()

check.protocol.release - Validate release protocol compliance T260 Signature

validateProtocolArtifactPublish()

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

validateProtocolProvenance()

check.protocol.provenance - Validate provenance protocol compliance T260 Signature

validateGateVerify()

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

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

Build metadata for a dispatch domain response. Signature
Parameters 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

errorResult()

Return a standard error response. Signature

unsupportedOp()

Return a standard “unsupported operation” error response. Signature

getListParams()

Extract limit and offset pagination params from a params dict. Signature

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

routeByParam()

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

BackgroundJobManager

Manages background jobs for long-running operations Signature
Methods

startJob()

Start a new background job

getJob()

Get a specific job by ID

listJobs()

List all jobs, optionally filtered by status

cancelJob()

Cancel a running job

updateProgress()

Update job progress (0-100)

cleanup()

Cleanup old completed/failed/cancelled jobs past retention period

destroy()

Destroy the manager: cancel all running jobs and clear state

executeJob()

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

setJobManager()

Signature

getJobManager()

Signature

AdminHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

CheckHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

ConduitHandler

Conduit dispatch handler for agent messaging operations. Signature
Methods

query()

mutate()

getSupportedOperations()

resolveCredential()

Resolve agent credential from the registry.

getStatus()

Get connection status and unread count.

peek()

One-shot peek for messages.

startPolling()

Start continuous polling via cleocode/runtime AgentPoller.

stopPolling()

Stop the active polling loop.

sendMessage()

Send a message to an agent or conversation.

MemoryHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

nexusStatus()

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

nexusListProjects()

List all registered projects. Signature

nexusShowProject()

Show a single project by name. Signature

nexusResolve()

Resolve a cross-project task query. Signature

nexusDepsQuery()

Get cross-project dependencies for a task query. Signature

nexusGraph()

Build the global dependency graph. Signature

nexusCriticalPath()

Get the critical path across projects. Signature

nexusBlockers()

Analyze blockers for a task query. Signature

nexusOrphans()

List orphaned cross-project tasks. Signature

nexusDiscover()

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

nexusSearch()

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

nexusInitialize()

Initialize the nexus. Signature

nexusRegisterProject()

Register a project in the nexus. Signature

nexusUnregisterProject()

Unregister a project from the nexus. Signature

nexusSyncProject()

Sync a specific project or all projects. Signature

nexusSetPermission()

Set permission level for a project. Signature

nexusReconcileProject()

Reconcile the nexus registry with the filesystem. Signature

nexusShareStatus()

Get sharing status for a project. Signature

nexusShareSnapshotExport()

Export a snapshot of the project’s tasks. Signature

nexusShareSnapshotImport()

Import a snapshot into the project. Signature

nexusTransferPreview()

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

nexusTransferExecute()

Execute a cross-project task transfer. Signature

NexusHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

OrchestrateHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

PipelineHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

queryStage()

mutateStage()

queryRelease()

mutateRelease()

queryManifest()

queryPhase()

mutateManifest()

mutatePhase()

queryChain()

mutateChain()

bindSession()

Bind a session to the current process. Called by session.start mutation handler after successful session creation. Signature
Throws
  • if a session is already bound (call unbindSession first).

getBoundSession()

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

hasSession()

Check whether a session is currently bound. Signature

unbindSession()

Unbind the current session context. Called by session.end mutation handler. Signature
Returns — The unbound context, or null if nothing was bound.

resetSessionContext()

Reset the session context (for testing only). Signature

SessionHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

stickyAdd(projectRoot, params)

Create a new sticky note. Signature
Parameters Returns — EngineResult with created sticky note

stickyList(projectRoot, params)

List sticky notes with optional filtering. Signature
Parameters Returns — EngineResult with array of sticky notes

stickyShow(projectRoot, id)

Get a single sticky note by ID. Signature
Parameters Returns — EngineResult with sticky note or null

stickyConvertToTask(projectRoot, stickyId, title)

Convert a sticky note to a task. Signature
Parameters Returns — EngineResult with new task ID

stickyConvertToMemory(projectRoot, stickyId, memoryType)

Convert a sticky note to a memory observation. Signature
Parameters Returns — EngineResult with new memory entry ID

stickyArchive(projectRoot, id)

Archive a sticky note. Signature
Parameters Returns — EngineResult with archived sticky note

stickyConvertToTaskNote(projectRoot, stickyId, taskId)

Convert a sticky note to a task note. Signature
Parameters Returns — EngineResult with updated task ID

stickyConvertToSessionNote(projectRoot, stickyId, sessionId)

Convert a sticky note to a session note. Signature
Parameters Returns — EngineResult with session ID

stickyPurge(projectRoot, id)

Purge (permanently delete) a sticky note. Signature
Parameters Returns — EngineResult with purged sticky note

StickyHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

TasksHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

codeOutline()

code.outline — file structural skeleton. Signature

codeSearch()

code.search — cross-codebase symbol search. Signature

codeUnfold()

code.unfold — single symbol extraction. Signature

codeParse()

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

toolsIssueDiagnostics()

Collect issue diagnostics. Signature

toolsSkillList()

List all discovered skills. Signature

toolsSkillShow()

Show a single skill by name. Signature

toolsSkillFind()

Find skills matching a query string. Signature

toolsSkillDispatch()

Get dispatch matrix entries for a skill. Signature

toolsSkillVerify()

Verify a skill’s installation and catalog status. Signature

toolsSkillDependencies()

Get dependency tree for a skill. Signature

toolsSkillSpawnProviders()

Get spawn-capable providers by capability. Signature

toolsSkillCatalogInfo()

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

toolsSkillCatalogProtocols()

List catalog protocols. Signature

toolsSkillCatalogProfiles()

List catalog profiles. Signature

toolsSkillCatalogResources()

List catalog shared resources. Signature

toolsSkillPrecedenceShow()

Show skill precedence map. Signature

toolsSkillPrecedenceResolve()

Resolve skill paths for a specific provider. Signature

toolsSkillInstall()

Install a skill to one or more providers. Signature

toolsSkillUninstall()

Uninstall a skill from all providers. Signature

toolsSkillRefresh()

Refresh all tracked skills that have updates available. Signature

toolsProviderList()

List all registered providers. Signature

toolsProviderDetect()

Detect all available providers in the environment. Signature

toolsProviderInjectStatus()

Check injection status for all installed providers. Signature

toolsProviderSupports()

Check if a provider supports a specific capability. Signature

toolsProviderHooks()

Query hook providers for a specific event. Signature

toolsProviderInject()

Inject CLEO directives into all installed provider instruction files. Signature

toolsAdapterList()

List all discovered adapters. Signature

toolsAdapterShow()

Show a single adapter by ID. Signature

toolsAdapterDetect()

Detect active adapters. Signature

toolsAdapterHealth()

Get adapter health status. Signature

toolsAdapterActivate()

Activate an adapter by ID. Signature

toolsAdapterDispose()

Dispose one or all adapters. Signature

ToolsHandler

Signature
Methods

query()

mutate()

getSupportedOperations()

queryIssue()

mutateIssue()

querySkill()

mutateSkill()

queryProvider()

mutateProvider()

queryAdapter()

queryCode()

mutateAdapter()

handleError()

createDomainHandlers()

Create a Map of all canonical domain handlers. Signature

RateLimiter

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

check()

resolveCategory()

getLimitConfig()

createRateLimiter(config)

Creates a rate limiting middleware for the dispatch pipeline. Signature
Parameters Returns — Middleware function that enforces rate limits Example

ConfigValidationError

Configuration validation error Signature

validateConfig()

Validate complete configuration Signature

loadConfig()

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

getConfig()

Get global configuration (singleton) Signature

resetConfig()

Reset global configuration (for testing) Signature

createAudit()

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

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

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
Parameters Returns — Middleware function that sanitizes request params Example

createSessionResolver(cliSessionLookup)

Creates the session resolver middleware. Signature
Parameters

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

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

resetCliDispatcher()

Reset the singleton dispatcher (for testing). Signature

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

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

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

registerAddCommand()

Register the add command. T4460 Signature

registerAdminCommand()

Register the admin command group. Signature

registerAdrCommand()

Signature

registerAgentCommand()

Register the cleo agent command group. Signature

registerAgentsCommand()

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

registerAnalyzeCommand()

Register the analyze command. T4538 Signature

registerArchiveCommand()

Register the archive command. T4461 Signature

registerArchiveStatsCommand()

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

registerBackfillCommand(program)

Register the cleo backfill CLI command. Signature
Parameters Example

registerBackupCommand()

Signature

registerBlockersCommand()

Signature

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
Parameters Example

registerBriefingCommand()

Register the briefing command. T4916 Signature

registerBugCommand()

Register the bug command. T4913 Signature

registerCantCommand()

Signature

registerCheckCommand()

Register the check command group. Signature

registerCheckpointCommand()

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

registerCommandsCommand()

Register the commands command. T4551, T5671 Signature

registerCompleteCommand()

Register the complete command. T4461 Signature

registerComplianceCommand()

Signature

registerConfigCommand()

Signature

registerConsensusCommand()

Register the consensus command group. T4537 Signature

registerContextCommand()

Signature

registerContributionCommand()

Register the contribution command group. T4537 Signature

registerCurrentCommand()

Register the current command. T4756 T4666 Signature

registerDashCommand()

Register the dash command. T4535 Signature

registerDecompositionCommand()

Register the decomposition command group. T4537 Signature

registerDeleteCommand()

Register the delete command. T4461 Signature

registerDepsCommand(program)

Register the deps command group and its subcommands. Signature
Parameters

registerTreeCommand(program)

Register the tree command. Signature
Parameters

registerDetectCommand()

Signature

registerDetectDriftCommand()

Signature

registerDocsCommand()

Register the docs command. T4551 Signature

ProgressTracker

Simple progress tracker for CLI operations. Signature
Methods

start()

Start the progress tracker.

step()

Update to a specific step.

next()

Move to next step.

complete()

Mark as complete with optional summary.

error()

Report an error.

Spinner

Simple spinner for indeterminate progress. Signature
Methods

start()

Start the spinner.

stop()

Stop the spinner.

update()

Update the spinner message.

createSelfUpdateProgress()

Create a progress tracker for self-update operations. Signature

createDoctorProgress()

Create a progress tracker for doctor operations. Signature

createUpgradeProgress()

Create a progress tracker for upgrade operations. Signature

registerDoctorCommand()

Signature

registerEnvCommand()

Register the env command group. T4581 Signature

registerExistsCommand(program)

Register the exists command. Signature
Parameters Example

registerExportCommand()

Signature

registerExportTasksCommand()

Signature

registerFindCommand()

Register the find command. T4460 T4668 Signature

registerGenerateChangelogCommand()

Register the generate-changelog command. T4555 Signature

registerGradeCommand()

Signature

registerHistoryCommand()

Signature

registerImplementationCommand()

Register the implementation command group. T4537 Signature

registerImportCommand()

Signature

registerImportTasksCommand()

Signature

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

registerInitCommand()

Register the init command. T4681 T4663 Signature

registerInjectCommand()

Signature

registerIssueCommand()

Register the issue command with all subcommands. T4555 Signature

registerLabelsCommand()

Register the labels command group. T4538 Signature

registerLifecycleCommand()

Signature

registerListCommand()

Register the list command. T4460 T4668 Signature

registerLogCommand()

Register the log command. T4538 Signature

registerMapCommand()

Register the map command. Signature

registerMemoryBrainCommand()

Signature

registerMigrateClaudeMemCommand()

Register the migrate claude-mem command under a migrate parent command. Usage: cleo migrate claude-mem [—dry-run] [—source ] [—project ] Signature

registerNextCommand()

Signature

registerNexusCommand()

Register the nexus command group. T4554 Signature

registerObserveCommand()

Signature

registerOpsCommand()

Register the ops command. Signature

registerOrchestrateCommand()

Signature

registerOtelCommand()

Register the otel command group. T4535 Signature

registerPhaseCommand()

Register the phase command group. T4464, T5326 Signature

registerPhasesCommand()

Register the phases command group. T4538, T5326 Signature

registerPlanCommand()

Signature

registerPromoteCommand()

Signature

registerReasonCommand(program)

Register the cleo reason command group and its subcommands. Signature
Parameters Example

registerRefreshMemoryCommand()

Signature

registerRelatesCommand()

Register the relates command group. T4538 Signature

registerReleaseCommand()

Signature

registerRemoteCommand()

Register the remote command with add/remove/list/push/pull subcommands. T4884 Signature

registerReorderCommand()

Signature

registerReparentCommand()

Signature

registerResearchCommand()

Signature

registerRestoreCommand()

Signature

registerRoadmapCommand()

Signature

registerSafestopCommand()

Register the safestop command. T4551 Signature

registerSelfUpdateCommand()

Signature

registerSequenceCommand()

Signature

registerSessionCommand()

Register the session command group. T4463 Signature

registerShowCommand()

Register the show command. T4460 T4666 Signature

registerSkillsCommand()

Register the skills command with all subcommands. T4555 Signature

registerSnapshotCommand()

Signature

registerSpecificationCommand()

Register the specification command group. T4537 Signature

registerStartCommand()

Register the start command. T4756 T4666 Signature

registerStatsCommand()

Register the stats command. T4535 Signature

registerStickyCommand()

Register the sticky command group. T5281 Signature

registerStopCommand()

Register the stop command. T4756 T4666 Signature

registerTestingCommand()

Register the testing command. T4551 Signature

registerTokenCommand()

Signature

registerUpdateCommand()

Register the update command. T4461 Signature

registerUpgradeCommand()

Signature

registerValidateCommand()

Signature

registerVerifyCommand()

Signature

registerWebCommand()

Register the web command. T4551 Signature

initCliLogger()

Initialize CLI logger with optional projectHash correlation context. Signature

registerDynamicCommands()

Register dynamically-generated commands onto the Commander program. Stub implementation: no commands registered until T4897 populates OperationDef.params arrays for all operations. Signature

renderErrorMarkdown()

Render a CleoError as structured markdown for CLI display. Signature

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
Parameters Returns — Middleware function that enforces protocol compliance Example

createVerificationGates(strictMode)

Creates a middleware that enforces verification gates on task operations. Signature
Parameters Returns — Middleware function that enforces verification gates Example

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
Parameters 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
Returns — Record keyed by ”.” → JSONSchemaObject

resolveTier(params, sessionScope)

Resolve tier from request params, defaulting to ‘standard’. Signature
Parameters Returns — The resolved MVI tier Example

isOperationAllowed()

Check if a domain is allowed at the given tier. Signature

applyProjection()

Apply field projection to a result object. Removes fields that are excluded at the given tier and prunes depth. Signature

createProjectionContext()

Create projection context from request params. Signature

createProjectionMiddleware()

Create the MVI projection middleware. Extracts _mviTier from params, checks domain access, and applies field exclusions to the response. Signature